All files verify-token.js

100% Statements 25/25
94.44% Branches 17/18
100% Functions 3/3
100% Lines 25/25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 531x 1x   8x 8x 8x 1x       7x 1x     6x   6x 1x     5x     5x   5x   5x 1x       4x 2x 2x     4x 4x 4x   2x       2x   2x          
import jwt from 'jsonwebtoken';
import errors from 'feathers-errors';
 
export default function (options = {}) {
  return function (hook) {
    if (hook.type !== 'before') {
      throw new Error(`The 'verifyToken' hook should only be used as a 'before' hook.`);
    }
 
    // If it was an internal call then skip this hook
    if (!hook.params.provider) {
      return hook;
    }
 
    const token = hook.params.token;
 
    if (!token) {
      throw new errors.NotAuthenticated('Authentication token missing.');
    }
 
    const authOptions = hook.app.get('auth') || {};
 
    // Grab the token options here
    options = Object.assign({}, authOptions.token, options);
 
    const secret = options.secret;
 
    if (!secret) {
      throw new Error(`You need to pass 'options.secret' to the verifyToken() hook or set 'auth.token.secret' it in your config.`);
    }
 
    // Convert the algorithm value to an array
    if (options.algorithm) {
      options.algorithms = [options.algorithm];
      delete options.algorithm;
    }
 
    return new Promise(function (resolve, reject) {
      jwt.verify(token, secret, options, function (error, payload) {
        if (error) {
          // Return a 401 if the token has expired or is invalid.
          return reject(new errors.NotAuthenticated(error));
        }
 
        // Attach our decoded token payload to the params
        hook.params.payload = payload;
 
        resolve(hook);
      });
    });
  };
}