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

worf.js

v2.2.4

Published

A node module that creates a middleware to authenticate against jwt

Downloads

6

Readme

Worf.js

A node module that provides functionalities to authenticate a user through JWT.

Usage

Methods

The module exposes the following methods:

setSecret(secret)

This method must be called once upon initialization in order to set the secret used to decode the JWT.

setTokenKey(key)

Optional, defines a custom key for the token. This will be the name of the cookie and the name of the query parameter that identify the token in a request (see Middleware below for more info).

encode(object, expiresIn, secret)

Returns a JWT for object.

decode(token, secret)

Returns a decoded object from a JWT, if valid.

authenticate(options) - Middleware

Worf provides a middleware to be used in Express-based applications. worf.authenticate(options) returns the middleware function that can be configured via the options parameter:

  • options.optional : boolean, whether the middleware should let the request pass even if no valid token is found (in this case req.user is null). Default: false
  • options.require : object, authenticates only if all fields in the decoded user object match those in require. e.g.:
worf.authenticate({ require : { id: 1, level : 'admin' } })
// only authorizes user with id 1 AND level 'admin' to access the route.
  • options.error : number, overwrite response error code in case of user not authenticated (default: 403)
  • options.secret : object, overwrite secret for this specific route
    • options.secret.require : tries to decode the token with this secret, disregarding global secret set via config.
    • options.secret.alternative : tries to decode the token with the global secret, then tries this alternative in case of failure. e.g.:
    worf.authenticate({ secret : { require : 'xyz' } })
    // only authorizes user with whose token was encode with secret 'xyz'
    worf.authenticate({ secret : { alternative : 'xyz' } })
    // authorize users whose token was encoded either with global or 'xyz' secret

The middleware looks for a JWT token in the request, in order:

  • In the token cookie
  • In the Authorization header
  • In a token parameter in the url query

If a valid token is found, req.user is populated with the user data found int the token itself. Otherwise a 401 is returned.

Example:

var worf = require('worf.js');
var config = require('./secrets.json');
worf.setSecret(config.jwtsecret);

app.get('/some-route', worf.authenticate(), function(req, res){
    console.log('User is autheticated with id ' + req.user.id);
});

app.get('/some-other-route', worf.authenticate({ optional: true}), function(req, res){
	if(req.user) {
	    console.log('User is autheticated with id ' + req.user.id);
	} else {
	    console.log("User is not autheticated, but it's fine anyway");
	}
});

app.get('/john', worf.authenticate({ require : { username : 'john' } }), function(req, res){
	console.log('User ' + req.user.id + ' is called john');
});
getUser(request)

Worf also exposes a getUser function that takes the request as a parameter. If performs the same checks on the request as the middleware and returns a user object on success, null otherwise.

Example - client:

var jwt = /* token */;
var socket = new WebSocket('ws://server:5000?token=' + jwt);

Example - server:

var worf = require('worf.js');
var WebSocketServer = require('ws').Server;
server = new WebSocketServer({ port: 5000 });

server.on('connection', function(socket){

        var user = worf.getUser(socket.upgradeReq);

        if(!user){
            console.log('User not authenticated');
            socket.close();
            return;
        }

        console.log('User is autheticated wiht id ' + req.user.id);
    });