Skip to content

Commit

Permalink
Feature: Pass instantiated strategy to authenticate.
Browse files Browse the repository at this point in the history
  • Loading branch information
rwky committed Dec 11, 2019
1 parent 5147e77 commit 1ab6ab3
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 4 deletions.
12 changes: 8 additions & 4 deletions lib/middleware/authenticate.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,18 +177,22 @@ module.exports = function authenticate(passport, name, options, callback) {

// eslint-disable-next-line consistent-return
(function attempt(i) {
let strategy;
const layer = name[i];
// If no more strategies exist in the chain, authentication has failed.
if (!layer) { return allFailed(); }

// Get the strategy, which will be used as prototype from which to create
// a new instance. Action functions will then be bound to the strategy
// within the context of the HTTP request/response pair.
const prototype = passport._strategy(layer);
if (!prototype) { return next(new Error(`Unknown authentication strategy "${layer}"`)); }

const strategy = Object.create(prototype);
if (typeof layer.authenticate === 'function') {
strategy = layer;
} else {
const prototype = passport._strategy(layer);
if (!prototype) { return next(new Error(`Unknown authentication strategy "${layer}"`)); }

strategy = Object.create(prototype);
}

// ----- BEGIN STRATEGY AUGMENTATION -----
// Augment the new strategy instance with action functions. These action
Expand Down
44 changes: 44 additions & 0 deletions test/authenticator.middleware.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,50 @@ describe('Authenticator', () => {
expect(request.user.username).to.equal('jaredhanson');
});

it('should set authInfo', () => {
expect(request.authInfo).to.be.an('object');
expect(Object.keys(request.authInfo)).to.have.length(0);
});
});
describe('handling a request with instantiated strategy', () => {
function Strategy() {
}
Strategy.prototype.authenticate = function authenticate() {
const user = { id: '1', username: 'jaredhanson' };
this.success(user);
};

const passport = new Authenticator();

let request, error;

before((done) => {
chai.connect.use(passport.authenticate(new Strategy())).req((req) => {
request = req;

req.logIn = function logIn(user, options, done) {
this.user = user;
done();
};
})
.next((err) => {
error = err;
done();
})
.dispatch();
});

it('should not error', () => {
// eslint-disable-next-line no-unused-expressions
expect(error).to.be.undefined;
});

it('should set user', () => {
expect(request.user).to.be.an('object');
expect(request.user.id).to.equal('1');
expect(request.user.username).to.equal('jaredhanson');
});

it('should set authInfo', () => {
expect(request.authInfo).to.be.an('object');
expect(Object.keys(request.authInfo)).to.have.length(0);
Expand Down

0 comments on commit 1ab6ab3

Please sign in to comment.