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

passport-unique-token

v3.0.0

Published

Unique Token authentication strategy for Passport.

Downloads

57,489

Readme

Passport Unique Token Strategy

CircleCI Maintainability Test Coverage Codacy Badge npm npm GitHub Conventional Commits Known Vulnerabilities

Unique token authentication strategy for Passport.

Installation

npm install passport-unique-token

Usage

The unique token authentication strategy authenticates users with a unique token. The strategy requires a verify callback, which accepts these credentials and calls done providing a user.

const { UniqueTokenStrategy } = require('passport-unique-token');

passport.use(
  new UniqueTokenStrategy((token, done) => {
    User.findOne(
      {
        uniqueToken: token,
        expireToken: { $gt: Date.now() },
      },
      (err, user) => {
        if (err) {
          return done(err);
        }

        if (!user) {
          return done(null, false);
        }

        return done(null, user);
      },
    );
  }),
);

By default passport-unique-token checks for token key credentials in either the params url or request body in these locations:

| Type | Default property | | ------ | :--------------: | | Url | token | | Body | token | | Query | token | | Header | token |

Configure

These credential locations can be configured when defining the strategy as follows:

const { UniqueTokenStrategy } = require('passport-unique-token');
const strategyOptions = {
  tokenQuery: 'custom-token',
  tokenParams: 'custom-token',
  tokenField: 'custom-token',
  tokenHeader: 'custom-token',
  failOnMissing: false
};

passport.use(new UniqueTokenStrategy(strategyOptions,
  (token, done) => {
    User.findOne({
      uniqueToken: token,
      expireToken: { $gt: Date.now() }
    }, (err, user) => {
      if (err) {
        return done(err);
      }

      if (!user) {
        return done(null, false);
      }

      return done(null, user);
    });
  }

failOnMissing option allows you to queue multiple strategy, customizing the behavior. By default it's set to true, when it's set to false it lets move on to the next strategy on failure.

How to Authenticate

Use passport.authenticate(), specifying the token strategy to authenticate requests.

For example, as route middleware in an Express application:

app.put('/animals/dogs', passport.authenticate('token'), (req, res) => {
  // User authenticated and can be found in req.user
});

If authentication fails in the above example then a 401 response will be given. However there may be times you wish a bit more control and delegate the failure to your application:

app.put('/animals/dogs', authenticate, (req, res) => {
  // User authenticated and can be found in req.user
});

function authenticate(req, res, next) {
  passport.authenticate('token', (err, user, info) => {
    if (err) {
      return next(err);
    }

    if (!user) {
      res.status(401).json({ message: 'Incorrect token credentials' });
    }

    req.user = user;
    next();
  })(req, res, next);
}

Api Reference

UniqueTokenStrategy()

The token authentication strategy authenticates requests based on the credentials submitted through standard request headers, body, querystring or params.

new UniqueTokenStrategy(
  options?: {
    // the token field name in the body request
    tokenField?: string = 'token',
    // the token field name in the query string request
    tokenQuery?: string = 'token',
    // the token field name in the param request
    tokenParams?: string = 'token',
    // the token field name in the header request
    tokenHeader?: string = 'token',
    // if `true` the express.Request is the first parameter of the verify callback
    passReqToCallback?: false,
    // if `true` the token key is case sensitive (e.g. res.body['uniqueToken'])
    caseSensitive?: false,
    // allows you to queue multiple strategy, customizing the behavior.
    failOnMissing?: true
  },
  verify: (
    req?: express.Request,
    token: string,
    done: (err: Error | null, user?: any, info?: any) => void
  ) => void
)

authenticate()

You can optionally pass options to the authenticate() method. Please refer to the passport documentation for the different signature.

authenticate(
  strategyName: string,
  options?: { badRequestMessage: string },
  callback?: { err: Error, user: any, info: any }
);

// Example:

app.post('/login', passport.authenticate('token', {
  badRequestMessage: 'custom error message'
}));

Credits

Luca Pau