All files / lib/hooks authenticate.js

97.62% Statements 41/42
86.96% Branches 40/46
100% Functions 3/3
97.62% Lines 41/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 981x 1x 1x 1x 1x   1x 21x 1x     20x   20x 20x     20x 2x     18x 1x     17x   17x 1x       16x         16x 1x         15x                 15x   15x   15x 13x     7x     1x     7x 7x   7x 1x     7x     6x 3x     3x   3x     1x   3x     1x     6x        
const errors = require('@feathersjs/errors');
const Debug = require('debug');
const { merge } = require('lodash');
const { NotAuthenticated } = require('@feathersjs/errors');
const debug = Debug('@feathersjs/authentication:hooks:authenticate');
 
module.exports = function authenticate (_strategies, options = {}) {
  if (!_strategies) {
    throw new Error(`The 'authenticate' hook requires one of your registered passport strategies.`);
  }
 
  const strategies = Array.isArray(_strategies) ? _strategies : [ _strategies ];
 
  return function (context) {
    const { app, params, type, data = {} } = context;
 
    // If called internally or we are already authenticated skip
    if (!params.provider || params.authenticated) {
      return Promise.resolve(context);
    }
 
    if (type !== 'before') {
      return Promise.reject(new Error(`The 'authenticate' hook should only be used as a 'before' hook.`));
    }
 
    const strategy = context.data.strategy || strategies[0];
 
    if (strategies.indexOf(strategy) === -1) {
      return Promise.reject(new NotAuthenticated(`Strategy '${strategy}' is not permitted`));
    }
 
    // Handle the case where authenticate hook was registered without a passport strategy specified
    Iif (!strategy) {
      return Promise.reject(new errors.GeneralError(`You must provide an authentication 'strategy'`));
    }
 
    // The client must send a `strategy` name.
    if (!app.passport._strategy(strategy)) {
      return Promise.reject(new errors.BadRequest(`Authentication strategy '${strategy}' is not registered.`));
    }
 
    // NOTE (EK): Passport expects an express/connect
    // like request object. So we need to create one.
    let request = {
      query: context.data,
      body: context.data,
      params: context.params,
      headers: context.params.headers || {},
      cookies: context.params.cookies || {},
      session: {}
    };
 
    const strategyOptions = merge({}, app.passport.options(strategy), options);
 
    debug(`Attempting to authenticate using ${strategy} strategy with options`, strategyOptions);
 
    return app.authenticate(strategy, strategyOptions)(request).then((result = {}) => {
      if (result.fail && options.allowUnauthenticated !== true) {
        // TODO (EK): Reject with something...
        // You get back result.challenge and result.status
        if (strategyOptions.failureRedirect) {
          // TODO (EK): Bypass the service?
          // hook.result = true
          Object.defineProperty(context.data, '__redirect', { value: { status: 302, url: strategyOptions.failureRedirect } });
        }
 
        const { challenge, status = 401 } = result;
        let message = challenge && challenge.message ? challenge.message : challenge;
 
        if (strategyOptions.failureMessage) {
          message = strategyOptions.failureMessage;
        }
 
        return Promise.reject(new errors[status](message, challenge));
      }
 
      if (result.success || options.allowUnauthenticated === true) {
        context.params = Object.assign({ authenticated: result.success }, context.params, result.data);
 
        // Add the user to the original request object so it's available in the socket handler
        Object.assign(request.params, context.params);
 
        if (strategyOptions.successRedirect) {
          // TODO (EK): Bypass the service?
          // hook.result = true
          Object.defineProperty(context.data, '__redirect', { value: { status: 302, url: strategyOptions.successRedirect } });
        }
      } else if (result.redirect) {
        // TODO (EK): Bypass the service?
        // hook.result = true
        Object.defineProperty(context.data, '__redirect', { value: { status: result.status, url: result.url } });
      }
 
      return Promise.resolve(context);
    });
  };
};