Skip to content

Instantly share code, notes, and snippets.

@distracteddev
Created May 10, 2012 23:31
Show Gist options
  • Save distracteddev/2656572 to your computer and use it in GitHub Desktop.
Save distracteddev/2656572 to your computer and use it in GitHub Desktop.
A Modification to the Node.js Passport module that looks for flatiron/union and binds the request functions onto the appropriate object.
/**
* Module dependencies.
*/
// If flatiron/union is being used, then bind the following
// functions to the RoutingStream Prototype
try {
var union = require('union')
, req = union.RoutingStream.prototype;
}
// Otherwise, bind to the native http.req prototype
catch (ex) {
var http = require('http')
, req = http.IncomingMessage.prototype;
}
/**
* Intiate a login session for `user`.
*
* Options:
* - `session` Save login state in session, defaults to _true_
*
* Examples:
*
* req.logIn(user, { session: false });
*
* req.logIn(user, function(err) {
* if (err) { throw err; }
* // session saved
* });
*
* @param {User} user
* @param {Object} options
* @param {Function} done
* @api public
*/
req.login =
req.logIn = function(user, options, done) {
if (!this._passport) throw new Error('passport.initialize() middleware not in use');
if (!done && typeof options === 'function') {
done = options;
options = {};
}
options = options || {};
var property = this._passport.instance._userProperty || 'user';
var session = (options.session === undefined) ? true : options.session;
this[property] = user;
if (session) {
var self = this;
this._passport.instance.serializeUser(user, function(err, obj) {
if (err) { self[property] = null; return done(err); }
self._passport.session.user = obj;
done();
});
} else {
done && done();
}
}
/**
* Terminate an existing login session.
*
* @api public
*/
req.logout =
req.logOut = function() {
if (!this._passport) throw new Error('passport.initialize() middleware not in use');
var property = this._passport.instance._userProperty || 'user';
this[property] = null;
delete this._passport.session.user;
};
/**
* Test if request is authenticated.
*
* @return {Boolean}
* @api public
*/
req.isAuthenticated = function() {
var property = 'user';
if (this._passport && this._passport.instance._userProperty) {
property = this._passport.instance._userProperty;
}
return (this[property]) ? true : false;
};
/**
* Test if request is unauthenticated.
*
* @return {Boolean}
* @api public
*/
req.isUnauthenticated = function() {
return !this.isAuthenticated();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment