All files verifier.js

100% Statements 22/22
90% Branches 9/10
100% Functions 3/3
100% Lines 21/21
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 421x   1x     36x 36x 36x 36x   36x 1x     35x     8x 8x   8x   8x 2x 2x     6x   6x 4x 4x     3x 3x            
import Debug from 'debug';
 
const debug = Debug('feathers-authentication-jwt:verify');
 
class JWTVerifier {
  constructor (app, options = {}) {
    this.app = app;
    this.options = options;
    this.service = typeof options.service === 'string' ? app.service(options.service) : options.service;
 
    if (!this.service) {
      throw new Error(`options.service does not exist.\n\tMake sure you are passing a valid service path or service instance and it is initialized before feathers-authentication-jwt.`);
    }
 
    this.verify = this.verify.bind(this);
  }
 
  verify (req, payload, done) {
    debug('Received JWT payload', payload);
 
    const id = payload[`${this.options.entity}Id`];
 
    if (id === undefined) {
      debug(`JWT payload does not contain ${this.options.entity}Id`);
      return done(null, {}, payload);
    }
 
    debug(`Looking up ${this.options.entity} by id`, id);
 
    this.service.get(id).then(entity => {
      const newPayload = { [`${this.options.entity}Id`]: id };
      return done(null, entity, newPayload);
    })
    .catch(error => {
      debug(`Error populating ${this.options.entity} with id ${id}`, error);
      return done(null, {}, payload);
    });
  }
}
 
export default JWTVerifier;