npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@sempervirens/authorizer

v0.6.0

Published

Middleware for authorizing requests to an Express server

Downloads

13

Readme

Sempervirens Authorizer

Middleware for authorizing requests to an Express server.

Tests badge Version badge

Installation

npm i @sempervirens/authorizer

Usage

Overview

  1. Create JWT private and public keys.
mkdir security && cd security && mkdir jwt && cd jwt
ssh-keygen -t rsa -b 4096 -m PEM -f jwtRS256.key
openssl rsa -in jwtRS256.key -pubout -outform PEM -out jwtRS256.key.pub
  1. Import authorizer into the server's main file, and then initialize authorizer with the JWT public and private keys.

  2. Set up a route that uses authorizer.encrypt to create a token and return the token to the client.

  3. Set up another route with a protected resource that requires a valid token.

  4. From the client, send a request to the server to get the token.

  5. From the client, send a second request for the protected resource, including the 'Authorization': 'Bearer ${token}' header.

Example

import { readFileSync } from 'fs';
import express from 'express';
import authorizer from '@sempervirens/authorizer';

const jwtPublicKey = readFileSync('./security/jwt/jwtRS256.key.pub', 'utf8');
const jwtPrivateKey = readFileSync('./security/jwt/jwtRS256.key', 'utf8');

authorizer.init({ jwtPublicKey, jwtPrivateKey });

const app = express();
app.use(express.json());

// Set up a /login route
app.post('/login', async (req, res, next) => {
  const { email, password } = req.body;
  // Validate email/password combination; do not use the following except for testing
  const isValid = email == '[email protected]' && password == 'testpassword';
  if (isValid) {
    const token = authorizer.encrypt({
      expiresIn: '10m',
      data: { email }
    });
    res.json({ token });
  } else {
    res.json({ error: 'Invalid credentials' });
  }
});

// Set up a protected resource route
app.get('/profile/:id', async (req, res, next) => {
  if (authorizer.isAuthorized(req)) { // Pass request header 'Authorization': 'Bearer ${token}'
    const profile = {
      email: '[email protected]',
      name: 'FirstTest LastTest'
    };
    res.json({ profile });
  } else {
    authorizer.sendUnauthorized(res); // Or send a custom response
  }
});

API

authorizer (Singleton instance)

| Prop | Type | Params | Description | |-------|------|--------|-------------| | init | function | { jwtPublicKey = '', jwtPrivateKey = '' } | Initializes the instance properties. | | encrypt | function | { expiresIn = '', data: {} } | Returns a JWT token. | | decrypt | function | tokenOrReq | Decrypts a JWT token. The token itself or an Express request object containing the authorization header may be given. | | isValid | function | tokenOrReq | Returns true or false. The token itself or an Express request object containing the authorization header may be given. | | invalidate | function | tokenOrReq | Invalidates a token within authorizer. | | reset | function | tokenOrReq | Decrypts the original token, calculates the original token's expiresIn, and adds the origIat property to the data before generating a new token. | | isAuthorized | function | req: express.Request | Parses a token from the 'Authorization': 'Bearer ${token}', checks if it's valid, and returns true or false. | | authorize | function | req: express.Request, res: express.Request, next | Checks if the token is valid. If so, it calls next. If not, it calls sendUnauthorized.| | sendUnauthorized | function | res: express.Request | Sends a 401 response with a pre-formatted data object in the same shape as @sempervirens/endpoint's error response. |