Skip to content

Instantly share code, notes, and snippets.

@killmenot
Forked from mweibel/passport-mock.js
Last active August 29, 2015 13:58
Show Gist options
  • Select an option

  • Save killmenot/9974519 to your computer and use it in GitHub Desktop.

Select an option

Save killmenot/9974519 to your computer and use it in GitHub Desktop.
/**
* Author: Michael Weibel <michael.weibel@gmail.com>
* License: MIT
*/
var passport = require('passport')
, StrategyMock = require('./strategy-mock');
module.exports = function(app, options) {
// create your verify function on your own -- should do similar things as
// the "real" one.
passport.use(new StrategyMock(options, verifyFunction));
app.get('/mock/login', passport.authenticate('mock'));
};
/**
* Author: Michael Weibel <michael.weibel@gmail.com>
* Updated: by Alexey Kucherenko <alexei.kucherenko@gmail.com>
* Original URL: https://gist.github.com/mweibel/5219403
* License: MIT
*/
'use strict';
var passport = require('passport'),
util = require('util');
function StrategyMock(options, verify) {
if (typeof(options) === 'function') {
verify = options;
options = {};
}
this.name = 'mock';
this.passAuthentication = options.passAuthentication || true;
this.username = options.username || 'user';
this.verify = verify;
}
util.inherits(StrategyMock, passport.Strategy);
StrategyMock.prototype.authenticate = function authenticate(req) {
if (this.passAuthentication) {
var user = {
username: req.query.username || this.username
},
self = this;
this.verify(user, function (err, resident) {
if (err) {
self.fail(err);
} else {
self.success(resident);
}
});
} else {
this.fail('Unauthorized');
}
};
module.exports = StrategyMock;
/**
* Author: Michael Weibel <michael.weibel@gmail.com>
* License: MIT
*/
var request = require('supertest')
, superagent = require('superagent')
, path = require('path')
, app = require(path.join(process.cwd(), 'index.js'))()
, passportMock = require(path.join(process.cwd(), 'src', 'shared', 'test', 'passport-mock'));
describe('GET /protected-resource authorized', function() {
var agent = superagent.agent();
beforeEach(function(done) {
passportMock(app, {
passAuthentication: true,
username: 'username'
});
request(app)
.get('/mock/login')
.end(function(err, result) {
if (!err) {
agent.saveCookies(result.res);
done();
} else {
done(err);
}
});
})
it('should allow access to /protected-resource', function(done) {
var req = request(app).get('/protected-resource');
agent.attachCookies(req);
req.expect(200, done);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment