Initial working google auth
This commit is contained in:
parent
fb52d49f74
commit
00a40f6bba
1058 changed files with 114441 additions and 0 deletions
486
auth-service/node_modules/passport/lib/authenticator.js
generated
vendored
Normal file
486
auth-service/node_modules/passport/lib/authenticator.js
generated
vendored
Normal file
|
|
@ -0,0 +1,486 @@
|
|||
// Module dependencies.
|
||||
var SessionStrategy = require('./strategies/session')
|
||||
, SessionManager = require('./sessionmanager');
|
||||
|
||||
|
||||
/**
|
||||
* Create a new `Authenticator` object.
|
||||
*
|
||||
* @public
|
||||
* @class
|
||||
*/
|
||||
function Authenticator() {
|
||||
this._key = 'passport';
|
||||
this._strategies = {};
|
||||
this._serializers = [];
|
||||
this._deserializers = [];
|
||||
this._infoTransformers = [];
|
||||
this._framework = null;
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize authenticator.
|
||||
*
|
||||
* Initializes the `Authenticator` instance by creating the default `{@link SessionManager}`,
|
||||
* {@link Authenticator#use `use()`}'ing the default `{@link SessionStrategy}`, and
|
||||
* adapting it to work as {@link https://github.com/senchalabs/connect#readme Connect}-style
|
||||
* middleware, which is also compatible with {@link https://expressjs.com/ Express}.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
Authenticator.prototype.init = function() {
|
||||
this.framework(require('./framework/connect')());
|
||||
this.use(new SessionStrategy({ key: this._key }, this.deserializeUser.bind(this)));
|
||||
this._sm = new SessionManager({ key: this._key }, this.serializeUser.bind(this));
|
||||
};
|
||||
|
||||
/**
|
||||
* Register a strategy for later use when authenticating requests. The name
|
||||
* with which the strategy is registered is passed to {@link Authenticator#authenticate `authenticate()`}.
|
||||
*
|
||||
* @public
|
||||
* @param {string} [name=strategy.name] - Name of the strategy. When specified,
|
||||
* this value overrides the strategy's name.
|
||||
* @param {Strategy} strategy - Authentication strategy.
|
||||
* @returns {this}
|
||||
*
|
||||
* @example <caption>Register strategy.</caption>
|
||||
* passport.use(new GoogleStrategy(...));
|
||||
*
|
||||
* @example <caption>Register strategy and override name.</caption>
|
||||
* passport.use('password', new LocalStrategy(function(username, password, cb) {
|
||||
* // ...
|
||||
* }));
|
||||
*/
|
||||
Authenticator.prototype.use = function(name, strategy) {
|
||||
if (!strategy) {
|
||||
strategy = name;
|
||||
name = strategy.name;
|
||||
}
|
||||
if (!name) { throw new Error('Authentication strategies must have a name'); }
|
||||
|
||||
this._strategies[name] = strategy;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Deregister a strategy that was previously registered with the given name.
|
||||
*
|
||||
* In a typical application, the necessary authentication strategies are
|
||||
* registered when initializing the app and, once registered, are always
|
||||
* available. As such, it is typically not necessary to call this function.
|
||||
*
|
||||
* @public
|
||||
* @param {string} name - Name of the strategy.
|
||||
* @returns {this}
|
||||
*
|
||||
* @example
|
||||
* passport.unuse('acme');
|
||||
*/
|
||||
Authenticator.prototype.unuse = function(name) {
|
||||
delete this._strategies[name];
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Adapt this `Authenticator` to work with a specific framework.
|
||||
*
|
||||
* By default, Passport works as {@link https://github.com/senchalabs/connect#readme Connect}-style
|
||||
* middleware, which makes it compatible with {@link https://expressjs.com/ Express}.
|
||||
* For any app built using Express, there is no need to call this function.
|
||||
*
|
||||
* @public
|
||||
* @param {Object} fw
|
||||
* @returns {this}
|
||||
*/
|
||||
Authenticator.prototype.framework = function(fw) {
|
||||
this._framework = fw;
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Create initialization middleware.
|
||||
*
|
||||
* Returns middleware that initializes Passport to authenticate requests.
|
||||
*
|
||||
* As of v0.6.x, it is typically no longer necessary to use this middleware. It
|
||||
* exists for compatiblity with apps built using previous versions of Passport,
|
||||
* in which this middleware was necessary.
|
||||
*
|
||||
* The primary exception to the above guidance is when using strategies that
|
||||
* depend directly on `passport@0.4.x` or earlier. These earlier versions of
|
||||
* Passport monkeypatch Node.js `http.IncomingMessage` in a way that expects
|
||||
* certain Passport-specific properties to be available. This middleware
|
||||
* provides a compatibility layer for this situation.
|
||||
*
|
||||
* @public
|
||||
* @param {Object} [options]
|
||||
* @param {string} [options.userProperty='user'] - Determines what property on
|
||||
* `req` will be set to the authenticated user object.
|
||||
* @param {boolean} [options.compat=true] - When `true`, enables a compatibility
|
||||
* layer for packages that depend on `passport@0.4.x` or earlier.
|
||||
* @returns {function}
|
||||
*
|
||||
* @example
|
||||
* app.use(passport.initialize());
|
||||
*/
|
||||
Authenticator.prototype.initialize = function(options) {
|
||||
options = options || {};
|
||||
return this._framework.initialize(this, options);
|
||||
};
|
||||
|
||||
/**
|
||||
* Create authentication middleware.
|
||||
*
|
||||
* Returns middleware that authenticates the request by applying the given
|
||||
* strategy (or strategies).
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* passport.authenticate('local', function(err, user) {
|
||||
* if (!user) { return res.redirect('/login'); }
|
||||
* res.end('Authenticated!');
|
||||
* })(req, res);
|
||||
*
|
||||
* @public
|
||||
* @param {string|string[]|Strategy} strategy
|
||||
* @param {Object} [options]
|
||||
* @param {boolean} [options.session=true]
|
||||
* @param {boolean} [options.keepSessionInfo=false]
|
||||
* @param {string} [options.failureRedirect]
|
||||
* @param {boolean|string|Object} [options.failureFlash=false]
|
||||
* @param {boolean|string} [options.failureMessage=false]
|
||||
* @param {boolean|string|Object} [options.successFlash=false]
|
||||
* @param {string} [options.successReturnToOrRedirect]
|
||||
* @param {string} [options.successRedirect]
|
||||
* @param {boolean|string} [options.successMessage=false]
|
||||
* @param {boolean} [options.failWithError=false]
|
||||
* @param {string} [options.assignProperty]
|
||||
* @param {boolean} [options.authInfo=true]
|
||||
* @param {function} [callback]
|
||||
* @returns {function}
|
||||
*
|
||||
* @example <caption>Authenticate username and password submitted via HTML form.</caption>
|
||||
* app.get('/login/password', passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' }));
|
||||
*
|
||||
* @example <caption>Authenticate bearer token used to access an API resource.</caption>
|
||||
* app.get('/api/resource', passport.authenticate('bearer', { session: false }));
|
||||
*/
|
||||
Authenticator.prototype.authenticate = function(strategy, options, callback) {
|
||||
return this._framework.authenticate(this, strategy, options, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Create third-party service authorization middleware.
|
||||
*
|
||||
* Returns middleware that will authorize a connection to a third-party service.
|
||||
*
|
||||
* This middleware is identical to using {@link Authenticator#authenticate `authenticate()`}
|
||||
* middleware with the `assignProperty` option set to `'account'`. This is
|
||||
* useful when a user is already authenticated (for example, using a username
|
||||
* and password) and they want to connect their account with a third-party
|
||||
* service.
|
||||
*
|
||||
* In this scenario, the user's third-party account will be set at
|
||||
* `req.account`, and the existing `req.user` and login session data will be
|
||||
* be left unmodified. A route handler can then link the third-party account to
|
||||
* the existing local account.
|
||||
*
|
||||
* All arguments to this function behave identically to those accepted by
|
||||
* `{@link Authenticator#authenticate}`.
|
||||
*
|
||||
* @public
|
||||
* @param {string|string[]|Strategy} strategy
|
||||
* @param {Object} [options]
|
||||
* @param {function} [callback]
|
||||
* @returns {function}
|
||||
*
|
||||
* @example
|
||||
* app.get('/oauth/callback/twitter', passport.authorize('twitter'));
|
||||
*/
|
||||
Authenticator.prototype.authorize = function(strategy, options, callback) {
|
||||
options = options || {};
|
||||
options.assignProperty = 'account';
|
||||
|
||||
var fn = this._framework.authorize || this._framework.authenticate;
|
||||
return fn(this, strategy, options, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Middleware that will restore login state from a session.
|
||||
*
|
||||
* Web applications typically use sessions to maintain login state between
|
||||
* requests. For example, a user will authenticate by entering credentials into
|
||||
* a form which is submitted to the server. If the credentials are valid, a
|
||||
* login session is established by setting a cookie containing a session
|
||||
* identifier in the user's web browser. The web browser will send this cookie
|
||||
* in subsequent requests to the server, allowing a session to be maintained.
|
||||
*
|
||||
* If sessions are being utilized, and a login session has been established,
|
||||
* this middleware will populate `req.user` with the current user.
|
||||
*
|
||||
* Note that sessions are not strictly required for Passport to operate.
|
||||
* However, as a general rule, most web applications will make use of sessions.
|
||||
* An exception to this rule would be an API server, which expects each HTTP
|
||||
* request to provide credentials in an Authorization header.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* app.use(connect.cookieParser());
|
||||
* app.use(connect.session({ secret: 'keyboard cat' }));
|
||||
* app.use(passport.initialize());
|
||||
* app.use(passport.session());
|
||||
*
|
||||
* Options:
|
||||
* - `pauseStream` Pause the request stream before deserializing the user
|
||||
* object from the session. Defaults to _false_. Should
|
||||
* be set to true in cases where middleware consuming the
|
||||
* request body is configured after passport and the
|
||||
* deserializeUser method is asynchronous.
|
||||
*
|
||||
* @param {Object} options
|
||||
* @return {Function} middleware
|
||||
* @api public
|
||||
*/
|
||||
Authenticator.prototype.session = function(options) {
|
||||
return this.authenticate('session', options);
|
||||
};
|
||||
|
||||
// TODO: Make session manager pluggable
|
||||
/*
|
||||
Authenticator.prototype.sessionManager = function(mgr) {
|
||||
this._sm = mgr;
|
||||
return this;
|
||||
}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Registers a function used to serialize user objects into the session.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* passport.serializeUser(function(user, done) {
|
||||
* done(null, user.id);
|
||||
* });
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
Authenticator.prototype.serializeUser = function(fn, req, done) {
|
||||
if (typeof fn === 'function') {
|
||||
return this._serializers.push(fn);
|
||||
}
|
||||
|
||||
// private implementation that traverses the chain of serializers, attempting
|
||||
// to serialize a user
|
||||
var user = fn;
|
||||
|
||||
// For backwards compatibility
|
||||
if (typeof req === 'function') {
|
||||
done = req;
|
||||
req = undefined;
|
||||
}
|
||||
|
||||
var stack = this._serializers;
|
||||
(function pass(i, err, obj) {
|
||||
// serializers use 'pass' as an error to skip processing
|
||||
if ('pass' === err) {
|
||||
err = undefined;
|
||||
}
|
||||
// an error or serialized object was obtained, done
|
||||
if (err || obj || obj === 0) { return done(err, obj); }
|
||||
|
||||
var layer = stack[i];
|
||||
if (!layer) {
|
||||
return done(new Error('Failed to serialize user into session'));
|
||||
}
|
||||
|
||||
|
||||
function serialized(e, o) {
|
||||
pass(i + 1, e, o);
|
||||
}
|
||||
|
||||
try {
|
||||
var arity = layer.length;
|
||||
if (arity == 3) {
|
||||
layer(req, user, serialized);
|
||||
} else {
|
||||
layer(user, serialized);
|
||||
}
|
||||
} catch(e) {
|
||||
return done(e);
|
||||
}
|
||||
})(0);
|
||||
};
|
||||
|
||||
/**
|
||||
* Registers a function used to deserialize user objects out of the session.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* passport.deserializeUser(function(id, done) {
|
||||
* User.findById(id, function (err, user) {
|
||||
* done(err, user);
|
||||
* });
|
||||
* });
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
Authenticator.prototype.deserializeUser = function(fn, req, done) {
|
||||
if (typeof fn === 'function') {
|
||||
return this._deserializers.push(fn);
|
||||
}
|
||||
|
||||
// private implementation that traverses the chain of deserializers,
|
||||
// attempting to deserialize a user
|
||||
var obj = fn;
|
||||
|
||||
// For backwards compatibility
|
||||
if (typeof req === 'function') {
|
||||
done = req;
|
||||
req = undefined;
|
||||
}
|
||||
|
||||
var stack = this._deserializers;
|
||||
(function pass(i, err, user) {
|
||||
// deserializers use 'pass' as an error to skip processing
|
||||
if ('pass' === err) {
|
||||
err = undefined;
|
||||
}
|
||||
// an error or deserialized user was obtained, done
|
||||
if (err || user) { return done(err, user); }
|
||||
// a valid user existed when establishing the session, but that user has
|
||||
// since been removed
|
||||
if (user === null || user === false) { return done(null, false); }
|
||||
|
||||
var layer = stack[i];
|
||||
if (!layer) {
|
||||
return done(new Error('Failed to deserialize user out of session'));
|
||||
}
|
||||
|
||||
|
||||
function deserialized(e, u) {
|
||||
pass(i + 1, e, u);
|
||||
}
|
||||
|
||||
try {
|
||||
var arity = layer.length;
|
||||
if (arity == 3) {
|
||||
layer(req, obj, deserialized);
|
||||
} else {
|
||||
layer(obj, deserialized);
|
||||
}
|
||||
} catch(e) {
|
||||
return done(e);
|
||||
}
|
||||
})(0);
|
||||
};
|
||||
|
||||
/**
|
||||
* Registers a function used to transform auth info.
|
||||
*
|
||||
* In some circumstances authorization details are contained in authentication
|
||||
* credentials or loaded as part of verification.
|
||||
*
|
||||
* For example, when using bearer tokens for API authentication, the tokens may
|
||||
* encode (either directly or indirectly in a database), details such as scope
|
||||
* of access or the client to which the token was issued.
|
||||
*
|
||||
* Such authorization details should be enforced separately from authentication.
|
||||
* Because Passport deals only with the latter, this is the responsiblity of
|
||||
* middleware or routes further along the chain. However, it is not optimal to
|
||||
* decode the same data or execute the same database query later. To avoid
|
||||
* this, Passport accepts optional `info` along with the authenticated `user`
|
||||
* in a strategy's `success()` action. This info is set at `req.authInfo`,
|
||||
* where said later middlware or routes can access it.
|
||||
*
|
||||
* Optionally, applications can register transforms to proccess this info,
|
||||
* which take effect prior to `req.authInfo` being set. This is useful, for
|
||||
* example, when the info contains a client ID. The transform can load the
|
||||
* client from the database and include the instance in the transformed info,
|
||||
* allowing the full set of client properties to be convieniently accessed.
|
||||
*
|
||||
* If no transforms are registered, `info` supplied by the strategy will be left
|
||||
* unmodified.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* passport.transformAuthInfo(function(info, done) {
|
||||
* Client.findById(info.clientID, function (err, client) {
|
||||
* info.client = client;
|
||||
* done(err, info);
|
||||
* });
|
||||
* });
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
Authenticator.prototype.transformAuthInfo = function(fn, req, done) {
|
||||
if (typeof fn === 'function') {
|
||||
return this._infoTransformers.push(fn);
|
||||
}
|
||||
|
||||
// private implementation that traverses the chain of transformers,
|
||||
// attempting to transform auth info
|
||||
var info = fn;
|
||||
|
||||
// For backwards compatibility
|
||||
if (typeof req === 'function') {
|
||||
done = req;
|
||||
req = undefined;
|
||||
}
|
||||
|
||||
var stack = this._infoTransformers;
|
||||
(function pass(i, err, tinfo) {
|
||||
// transformers use 'pass' as an error to skip processing
|
||||
if ('pass' === err) {
|
||||
err = undefined;
|
||||
}
|
||||
// an error or transformed info was obtained, done
|
||||
if (err || tinfo) { return done(err, tinfo); }
|
||||
|
||||
var layer = stack[i];
|
||||
if (!layer) {
|
||||
// if no transformers are registered (or they all pass), the default
|
||||
// behavior is to use the un-transformed info as-is
|
||||
return done(null, info);
|
||||
}
|
||||
|
||||
|
||||
function transformed(e, t) {
|
||||
pass(i + 1, e, t);
|
||||
}
|
||||
|
||||
try {
|
||||
var arity = layer.length;
|
||||
if (arity == 1) {
|
||||
// sync
|
||||
var t = layer(info);
|
||||
transformed(null, t);
|
||||
} else if (arity == 3) {
|
||||
layer(req, info, transformed);
|
||||
} else {
|
||||
layer(info, transformed);
|
||||
}
|
||||
} catch(e) {
|
||||
return done(e);
|
||||
}
|
||||
})(0);
|
||||
};
|
||||
|
||||
/**
|
||||
* Return strategy with given `name`.
|
||||
*
|
||||
* @param {String} name
|
||||
* @return {Strategy}
|
||||
* @api private
|
||||
*/
|
||||
Authenticator.prototype._strategy = function(name) {
|
||||
return this._strategies[name];
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Expose `Authenticator`.
|
||||
*/
|
||||
module.exports = Authenticator;
|
||||
20
auth-service/node_modules/passport/lib/errors/authenticationerror.js
generated
vendored
Normal file
20
auth-service/node_modules/passport/lib/errors/authenticationerror.js
generated
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
/**
|
||||
* `AuthenticationError` error.
|
||||
*
|
||||
* @constructor
|
||||
* @api private
|
||||
*/
|
||||
function AuthenticationError(message, status) {
|
||||
Error.call(this);
|
||||
Error.captureStackTrace(this, arguments.callee);
|
||||
this.name = 'AuthenticationError';
|
||||
this.message = message;
|
||||
this.status = status || 401;
|
||||
}
|
||||
|
||||
// Inherit from `Error`.
|
||||
AuthenticationError.prototype.__proto__ = Error.prototype;
|
||||
|
||||
|
||||
// Expose constructor.
|
||||
module.exports = AuthenticationError;
|
||||
22
auth-service/node_modules/passport/lib/framework/connect.js
generated
vendored
Normal file
22
auth-service/node_modules/passport/lib/framework/connect.js
generated
vendored
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
var initialize = require('../middleware/initialize')
|
||||
, authenticate = require('../middleware/authenticate');
|
||||
|
||||
/**
|
||||
* Framework support for Connect/Express.
|
||||
*
|
||||
* This module provides support for using Passport with Express. It exposes
|
||||
* middleware that conform to the `fn(req, res, next)` signature.
|
||||
*
|
||||
* @return {Object}
|
||||
* @api protected
|
||||
*/
|
||||
exports = module.exports = function() {
|
||||
|
||||
return {
|
||||
initialize: initialize,
|
||||
authenticate: authenticate
|
||||
};
|
||||
};
|
||||
92
auth-service/node_modules/passport/lib/http/request.js
generated
vendored
Normal file
92
auth-service/node_modules/passport/lib/http/request.js
generated
vendored
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
var req = exports = module.exports = {};
|
||||
|
||||
/**
|
||||
* Initiate 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 (typeof options == 'function') {
|
||||
done = options;
|
||||
options = {};
|
||||
}
|
||||
options = options || {};
|
||||
|
||||
var property = this._userProperty || 'user';
|
||||
var session = (options.session === undefined) ? true : options.session;
|
||||
|
||||
this[property] = user;
|
||||
if (session && this._sessionManager) {
|
||||
if (typeof done != 'function') { throw new Error('req#login requires a callback function'); }
|
||||
|
||||
var self = this;
|
||||
this._sessionManager.logIn(this, user, options, function(err) {
|
||||
if (err) { self[property] = null; return done(err); }
|
||||
done();
|
||||
});
|
||||
} else {
|
||||
done && done();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Terminate an existing login session.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
req.logout =
|
||||
req.logOut = function(options, done) {
|
||||
if (typeof options == 'function') {
|
||||
done = options;
|
||||
options = {};
|
||||
}
|
||||
options = options || {};
|
||||
|
||||
var property = this._userProperty || 'user';
|
||||
|
||||
this[property] = null;
|
||||
if (this._sessionManager) {
|
||||
if (typeof done != 'function') { throw new Error('req#logout requires a callback function'); }
|
||||
|
||||
this._sessionManager.logOut(this, options, done);
|
||||
} else {
|
||||
done && done();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Test if request is authenticated.
|
||||
*
|
||||
* @return {Boolean}
|
||||
* @api public
|
||||
*/
|
||||
req.isAuthenticated = function() {
|
||||
var property = this._userProperty || 'user';
|
||||
return (this[property]) ? true : false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Test if request is unauthenticated.
|
||||
*
|
||||
* @return {Boolean}
|
||||
* @api public
|
||||
*/
|
||||
req.isUnauthenticated = function() {
|
||||
return !this.isAuthenticated();
|
||||
};
|
||||
24
auth-service/node_modules/passport/lib/index.js
generated
vendored
Normal file
24
auth-service/node_modules/passport/lib/index.js
generated
vendored
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
// Module dependencies.
|
||||
var Passport = require('./authenticator')
|
||||
, SessionStrategy = require('./strategies/session');
|
||||
|
||||
|
||||
/**
|
||||
* Export default singleton.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
exports = module.exports = new Passport();
|
||||
|
||||
/**
|
||||
* Expose constructors.
|
||||
*/
|
||||
exports.Passport =
|
||||
exports.Authenticator = Passport;
|
||||
exports.Strategy = require('passport-strategy');
|
||||
|
||||
/*
|
||||
* Expose strategies.
|
||||
*/
|
||||
exports.strategies = {};
|
||||
exports.strategies.SessionStrategy = SessionStrategy;
|
||||
381
auth-service/node_modules/passport/lib/middleware/authenticate.js
generated
vendored
Normal file
381
auth-service/node_modules/passport/lib/middleware/authenticate.js
generated
vendored
Normal file
|
|
@ -0,0 +1,381 @@
|
|||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
var http = require('http')
|
||||
, IncomingMessageExt = require('../http/request')
|
||||
, AuthenticationError = require('../errors/authenticationerror');
|
||||
|
||||
|
||||
/**
|
||||
* Authenticates requests.
|
||||
*
|
||||
* Applies the `name`ed strategy (or strategies) to the incoming request, in
|
||||
* order to authenticate the request. If authentication is successful, the user
|
||||
* will be logged in and populated at `req.user` and a session will be
|
||||
* established by default. If authentication fails, an unauthorized response
|
||||
* will be sent.
|
||||
*
|
||||
* Options:
|
||||
* - `session` Save login state in session, defaults to _true_
|
||||
* - `successRedirect` After successful login, redirect to given URL
|
||||
* - `successMessage` True to store success message in
|
||||
* req.session.messages, or a string to use as override
|
||||
* message for success.
|
||||
* - `successFlash` True to flash success messages or a string to use as a flash
|
||||
* message for success (overrides any from the strategy itself).
|
||||
* - `failureRedirect` After failed login, redirect to given URL
|
||||
* - `failureMessage` True to store failure message in
|
||||
* req.session.messages, or a string to use as override
|
||||
* message for failure.
|
||||
* - `failureFlash` True to flash failure messages or a string to use as a flash
|
||||
* message for failures (overrides any from the strategy itself).
|
||||
* - `assignProperty` Assign the object provided by the verify callback to given property
|
||||
*
|
||||
* An optional `callback` can be supplied to allow the application to override
|
||||
* the default manner in which authentication attempts are handled. The
|
||||
* callback has the following signature, where `user` will be set to the
|
||||
* authenticated user on a successful authentication attempt, or `false`
|
||||
* otherwise. An optional `info` argument will be passed, containing additional
|
||||
* details provided by the strategy's verify callback - this could be information about
|
||||
* a successful authentication or a challenge message for a failed authentication.
|
||||
* An optional `status` argument will be passed when authentication fails - this could
|
||||
* be a HTTP response code for a remote authentication failure or similar.
|
||||
*
|
||||
* app.get('/protected', function(req, res, next) {
|
||||
* passport.authenticate('local', function(err, user, info, status) {
|
||||
* if (err) { return next(err) }
|
||||
* if (!user) { return res.redirect('/signin') }
|
||||
* res.redirect('/account');
|
||||
* })(req, res, next);
|
||||
* });
|
||||
*
|
||||
* Note that if a callback is supplied, it becomes the application's
|
||||
* responsibility to log-in the user, establish a session, and otherwise perform
|
||||
* the desired operations.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' });
|
||||
*
|
||||
* passport.authenticate('basic', { session: false });
|
||||
*
|
||||
* passport.authenticate('twitter');
|
||||
*
|
||||
* @param {Strategy|String|Array} name
|
||||
* @param {Object} options
|
||||
* @param {Function} callback
|
||||
* @return {Function}
|
||||
* @api public
|
||||
*/
|
||||
module.exports = function authenticate(passport, name, options, callback) {
|
||||
if (typeof options == 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
options = options || {};
|
||||
|
||||
var multi = true;
|
||||
|
||||
// Cast `name` to an array, allowing authentication to pass through a chain of
|
||||
// strategies. The first strategy to succeed, redirect, or error will halt
|
||||
// the chain. Authentication failures will proceed through each strategy in
|
||||
// series, ultimately failing if all strategies fail.
|
||||
//
|
||||
// This is typically used on API endpoints to allow clients to authenticate
|
||||
// using their preferred choice of Basic, Digest, token-based schemes, etc.
|
||||
// It is not feasible to construct a chain of multiple strategies that involve
|
||||
// redirection (for example both Facebook and Twitter), since the first one to
|
||||
// redirect will halt the chain.
|
||||
if (!Array.isArray(name)) {
|
||||
name = [ name ];
|
||||
multi = false;
|
||||
}
|
||||
|
||||
return function authenticate(req, res, next) {
|
||||
req.login =
|
||||
req.logIn = req.logIn || IncomingMessageExt.logIn;
|
||||
req.logout =
|
||||
req.logOut = req.logOut || IncomingMessageExt.logOut;
|
||||
req.isAuthenticated = req.isAuthenticated || IncomingMessageExt.isAuthenticated;
|
||||
req.isUnauthenticated = req.isUnauthenticated || IncomingMessageExt.isUnauthenticated;
|
||||
|
||||
req._sessionManager = passport._sm;
|
||||
|
||||
// accumulator for failures from each strategy in the chain
|
||||
var failures = [];
|
||||
|
||||
function allFailed() {
|
||||
if (callback) {
|
||||
if (!multi) {
|
||||
return callback(null, false, failures[0].challenge, failures[0].status);
|
||||
} else {
|
||||
var challenges = failures.map(function(f) { return f.challenge; });
|
||||
var statuses = failures.map(function(f) { return f.status; });
|
||||
return callback(null, false, challenges, statuses);
|
||||
}
|
||||
}
|
||||
|
||||
// Strategies are ordered by priority. For the purpose of flashing a
|
||||
// message, the first failure will be displayed.
|
||||
var failure = failures[0] || {}
|
||||
, challenge = failure.challenge || {}
|
||||
, msg;
|
||||
|
||||
if (options.failureFlash) {
|
||||
var flash = options.failureFlash;
|
||||
if (typeof flash == 'string') {
|
||||
flash = { type: 'error', message: flash };
|
||||
}
|
||||
flash.type = flash.type || 'error';
|
||||
|
||||
var type = flash.type || challenge.type || 'error';
|
||||
msg = flash.message || challenge.message || challenge;
|
||||
if (typeof msg == 'string') {
|
||||
req.flash(type, msg);
|
||||
}
|
||||
}
|
||||
if (options.failureMessage) {
|
||||
msg = options.failureMessage;
|
||||
if (typeof msg == 'boolean') {
|
||||
msg = challenge.message || challenge;
|
||||
}
|
||||
if (typeof msg == 'string') {
|
||||
req.session.messages = req.session.messages || [];
|
||||
req.session.messages.push(msg);
|
||||
}
|
||||
}
|
||||
if (options.failureRedirect) {
|
||||
return res.redirect(options.failureRedirect);
|
||||
}
|
||||
|
||||
// When failure handling is not delegated to the application, the default
|
||||
// is to respond with 401 Unauthorized. Note that the WWW-Authenticate
|
||||
// header will be set according to the strategies in use (see
|
||||
// actions#fail). If multiple strategies failed, each of their challenges
|
||||
// will be included in the response.
|
||||
var rchallenge = []
|
||||
, rstatus, status;
|
||||
|
||||
for (var j = 0, len = failures.length; j < len; j++) {
|
||||
failure = failures[j];
|
||||
challenge = failure.challenge;
|
||||
status = failure.status;
|
||||
|
||||
rstatus = rstatus || status;
|
||||
if (typeof challenge == 'string') {
|
||||
rchallenge.push(challenge);
|
||||
}
|
||||
}
|
||||
|
||||
res.statusCode = rstatus || 401;
|
||||
if (res.statusCode == 401 && rchallenge.length) {
|
||||
res.setHeader('WWW-Authenticate', rchallenge);
|
||||
}
|
||||
if (options.failWithError) {
|
||||
return next(new AuthenticationError(http.STATUS_CODES[res.statusCode], rstatus));
|
||||
}
|
||||
res.end(http.STATUS_CODES[res.statusCode]);
|
||||
}
|
||||
|
||||
(function attempt(i) {
|
||||
var 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.
|
||||
var strategy, prototype;
|
||||
if (typeof layer.authenticate == 'function') {
|
||||
strategy = layer;
|
||||
} else {
|
||||
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
|
||||
// functions are bound via closure the the request/response pair. The end
|
||||
// goal of the strategy is to invoke *one* of these action methods, in
|
||||
// order to indicate successful or failed authentication, redirect to a
|
||||
// third-party identity provider, etc.
|
||||
|
||||
/**
|
||||
* Authenticate `user`, with optional `info`.
|
||||
*
|
||||
* Strategies should call this function to successfully authenticate a
|
||||
* user. `user` should be an object supplied by the application after it
|
||||
* has been given an opportunity to verify credentials. `info` is an
|
||||
* optional argument containing additional user information. This is
|
||||
* useful for third-party authentication strategies to pass profile
|
||||
* details.
|
||||
*
|
||||
* @param {Object} user
|
||||
* @param {Object} info
|
||||
* @api public
|
||||
*/
|
||||
strategy.success = function(user, info) {
|
||||
if (callback) {
|
||||
return callback(null, user, info);
|
||||
}
|
||||
|
||||
info = info || {};
|
||||
var msg;
|
||||
|
||||
if (options.successFlash) {
|
||||
var flash = options.successFlash;
|
||||
if (typeof flash == 'string') {
|
||||
flash = { type: 'success', message: flash };
|
||||
}
|
||||
flash.type = flash.type || 'success';
|
||||
|
||||
var type = flash.type || info.type || 'success';
|
||||
msg = flash.message || info.message || info;
|
||||
if (typeof msg == 'string') {
|
||||
req.flash(type, msg);
|
||||
}
|
||||
}
|
||||
if (options.successMessage) {
|
||||
msg = options.successMessage;
|
||||
if (typeof msg == 'boolean') {
|
||||
msg = info.message || info;
|
||||
}
|
||||
if (typeof msg == 'string') {
|
||||
req.session.messages = req.session.messages || [];
|
||||
req.session.messages.push(msg);
|
||||
}
|
||||
}
|
||||
if (options.assignProperty) {
|
||||
req[options.assignProperty] = user;
|
||||
if (options.authInfo !== false) {
|
||||
passport.transformAuthInfo(info, req, function(err, tinfo) {
|
||||
if (err) { return next(err); }
|
||||
req.authInfo = tinfo;
|
||||
next();
|
||||
});
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
req.logIn(user, options, function(err) {
|
||||
if (err) { return next(err); }
|
||||
|
||||
function complete() {
|
||||
if (options.successReturnToOrRedirect) {
|
||||
var url = options.successReturnToOrRedirect;
|
||||
if (req.session && req.session.returnTo) {
|
||||
url = req.session.returnTo;
|
||||
delete req.session.returnTo;
|
||||
}
|
||||
return res.redirect(url);
|
||||
}
|
||||
if (options.successRedirect) {
|
||||
return res.redirect(options.successRedirect);
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
if (options.authInfo !== false) {
|
||||
passport.transformAuthInfo(info, req, function(err, tinfo) {
|
||||
if (err) { return next(err); }
|
||||
req.authInfo = tinfo;
|
||||
complete();
|
||||
});
|
||||
} else {
|
||||
complete();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Fail authentication, with optional `challenge` and `status`, defaulting
|
||||
* to 401.
|
||||
*
|
||||
* Strategies should call this function to fail an authentication attempt.
|
||||
*
|
||||
* @param {String} challenge
|
||||
* @param {Number} status
|
||||
* @api public
|
||||
*/
|
||||
strategy.fail = function(challenge, status) {
|
||||
if (typeof challenge == 'number') {
|
||||
status = challenge;
|
||||
challenge = undefined;
|
||||
}
|
||||
|
||||
// push this failure into the accumulator and attempt authentication
|
||||
// using the next strategy
|
||||
failures.push({ challenge: challenge, status: status });
|
||||
attempt(i + 1);
|
||||
};
|
||||
|
||||
/**
|
||||
* Redirect to `url` with optional `status`, defaulting to 302.
|
||||
*
|
||||
* Strategies should call this function to redirect the user (via their
|
||||
* user agent) to a third-party website for authentication.
|
||||
*
|
||||
* @param {String} url
|
||||
* @param {Number} status
|
||||
* @api public
|
||||
*/
|
||||
strategy.redirect = function(url, status) {
|
||||
// NOTE: Do not use `res.redirect` from Express, because it can't decide
|
||||
// what it wants.
|
||||
//
|
||||
// Express 2.x: res.redirect(url, status)
|
||||
// Express 3.x: res.redirect(status, url) -OR- res.redirect(url, status)
|
||||
// - as of 3.14.0, deprecated warnings are issued if res.redirect(url, status)
|
||||
// is used
|
||||
// Express 4.x: res.redirect(status, url)
|
||||
// - all versions (as of 4.8.7) continue to accept res.redirect(url, status)
|
||||
// but issue deprecated versions
|
||||
|
||||
res.statusCode = status || 302;
|
||||
res.setHeader('Location', url);
|
||||
res.setHeader('Content-Length', '0');
|
||||
res.end();
|
||||
};
|
||||
|
||||
/**
|
||||
* Pass without making a success or fail decision.
|
||||
*
|
||||
* Under most circumstances, Strategies should not need to call this
|
||||
* function. It exists primarily to allow previous authentication state
|
||||
* to be restored, for example from an HTTP session.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
strategy.pass = function() {
|
||||
next();
|
||||
};
|
||||
|
||||
/**
|
||||
* Internal error while performing authentication.
|
||||
*
|
||||
* Strategies should call this function when an internal error occurs
|
||||
* during the process of performing authentication; for example, if the
|
||||
* user directory is not available.
|
||||
*
|
||||
* @param {Error} err
|
||||
* @api public
|
||||
*/
|
||||
strategy.error = function(err) {
|
||||
if (callback) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
next(err);
|
||||
};
|
||||
|
||||
// ----- END STRATEGY AUGMENTATION -----
|
||||
|
||||
strategy.authenticate(req, options);
|
||||
})(0); // attempt
|
||||
};
|
||||
};
|
||||
100
auth-service/node_modules/passport/lib/middleware/initialize.js
generated
vendored
Normal file
100
auth-service/node_modules/passport/lib/middleware/initialize.js
generated
vendored
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
var IncomingMessageExt = require('../http/request');
|
||||
|
||||
|
||||
/**
|
||||
* Passport initialization.
|
||||
*
|
||||
* Intializes Passport for incoming requests, allowing authentication strategies
|
||||
* to be applied.
|
||||
*
|
||||
* If sessions are being utilized, applications must set up Passport with
|
||||
* functions to serialize a user into and out of a session. For example, a
|
||||
* common pattern is to serialize just the user ID into the session (due to the
|
||||
* fact that it is desirable to store the minimum amount of data in a session).
|
||||
* When a subsequent request arrives for the session, the full User object can
|
||||
* be loaded from the database by ID.
|
||||
*
|
||||
* Note that additional middleware is required to persist login state, so we
|
||||
* must use the `connect.session()` middleware _before_ `passport.initialize()`.
|
||||
*
|
||||
* If sessions are being used, this middleware must be in use by the
|
||||
* Connect/Express application for Passport to operate. If the application is
|
||||
* entirely stateless (not using sessions), this middleware is not necessary,
|
||||
* but its use will not have any adverse impact.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* app.use(connect.cookieParser());
|
||||
* app.use(connect.session({ secret: 'keyboard cat' }));
|
||||
* app.use(passport.initialize());
|
||||
* app.use(passport.session());
|
||||
*
|
||||
* passport.serializeUser(function(user, done) {
|
||||
* done(null, user.id);
|
||||
* });
|
||||
*
|
||||
* passport.deserializeUser(function(id, done) {
|
||||
* User.findById(id, function (err, user) {
|
||||
* done(err, user);
|
||||
* });
|
||||
* });
|
||||
*
|
||||
* @return {Function}
|
||||
* @api public
|
||||
*/
|
||||
module.exports = function initialize(passport, options) {
|
||||
options = options || {};
|
||||
|
||||
return function initialize(req, res, next) {
|
||||
req.login =
|
||||
req.logIn = req.logIn || IncomingMessageExt.logIn;
|
||||
req.logout =
|
||||
req.logOut = req.logOut || IncomingMessageExt.logOut;
|
||||
req.isAuthenticated = req.isAuthenticated || IncomingMessageExt.isAuthenticated;
|
||||
req.isUnauthenticated = req.isUnauthenticated || IncomingMessageExt.isUnauthenticated;
|
||||
|
||||
req._sessionManager = passport._sm;
|
||||
|
||||
if (options.userProperty) {
|
||||
req._userProperty = options.userProperty;
|
||||
}
|
||||
|
||||
var compat = (options.compat === undefined) ? true : options.compat;
|
||||
if (compat) {
|
||||
// `passport@0.5.1` [removed][1] all internal use of `req._passport`.
|
||||
// From the standpoint of this package, this should have been a
|
||||
// non-breaking change. However, some strategies (such as `passport-azure-ad`)
|
||||
// depend directly on `passport@0.4.x` or earlier. `require`-ing earlier
|
||||
// versions of `passport` has the effect of monkeypatching `http.IncomingMessage`
|
||||
// with `logIn`, `logOut`, `isAuthenticated` and `isUnauthenticated`
|
||||
// functions that [expect][2] the `req._passport` property to exist.
|
||||
// Since pre-existing functions on `req` are given [preference][3], this
|
||||
// results in [issues][4].
|
||||
//
|
||||
// The changes here restore the expected properties needed when earlier
|
||||
// versions of `passport` are `require`-ed. This compatibility mode is
|
||||
// enabled by default, and can be disabld by simply not `use`-ing `passport.initialize()`
|
||||
// middleware or setting `compat: false` as an option to the middleware.
|
||||
//
|
||||
// An alternative approach to addressing this issue would be to not
|
||||
// preferentially use pre-existing functions on `req`, but rather always
|
||||
// overwrite `req.logIn`, etc. with the versions of those functions shiped
|
||||
// with `authenticate()` middleware. This option should be reconsidered
|
||||
// in a future major version release.
|
||||
//
|
||||
// [1]: https://github.com/jaredhanson/passport/pull/875
|
||||
// [2]: https://github.com/jaredhanson/passport/blob/v0.4.1/lib/http/request.js
|
||||
// [3]: https://github.com/jaredhanson/passport/blob/v0.5.1/lib/middleware/authenticate.js#L96
|
||||
// [4]: https://github.com/jaredhanson/passport/issues/877
|
||||
passport._userProperty = options.userProperty || 'user';
|
||||
|
||||
req._passport = {};
|
||||
req._passport.instance = passport;
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
};
|
||||
96
auth-service/node_modules/passport/lib/sessionmanager.js
generated
vendored
Normal file
96
auth-service/node_modules/passport/lib/sessionmanager.js
generated
vendored
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
var merge = require('utils-merge');
|
||||
|
||||
function SessionManager(options, serializeUser) {
|
||||
if (typeof options == 'function') {
|
||||
serializeUser = options;
|
||||
options = undefined;
|
||||
}
|
||||
options = options || {};
|
||||
|
||||
this._key = options.key || 'passport';
|
||||
this._serializeUser = serializeUser;
|
||||
}
|
||||
|
||||
SessionManager.prototype.logIn = function(req, user, options, cb) {
|
||||
if (typeof options == 'function') {
|
||||
cb = options;
|
||||
options = {};
|
||||
}
|
||||
options = options || {};
|
||||
|
||||
if (!req.session) { return cb(new Error('Login sessions require session support. Did you forget to use `express-session` middleware?')); }
|
||||
|
||||
var self = this;
|
||||
var prevSession = req.session;
|
||||
|
||||
// regenerate the session, which is good practice to help
|
||||
// guard against forms of session fixation
|
||||
req.session.regenerate(function(err) {
|
||||
if (err) {
|
||||
return cb(err);
|
||||
}
|
||||
|
||||
self._serializeUser(user, req, function(err, obj) {
|
||||
if (err) {
|
||||
return cb(err);
|
||||
}
|
||||
if (options.keepSessionInfo) {
|
||||
merge(req.session, prevSession);
|
||||
}
|
||||
if (!req.session[self._key]) {
|
||||
req.session[self._key] = {};
|
||||
}
|
||||
// store user information in session, typically a user id
|
||||
req.session[self._key].user = obj;
|
||||
// save the session before redirection to ensure page
|
||||
// load does not happen before session is saved
|
||||
req.session.save(function(err) {
|
||||
if (err) {
|
||||
return cb(err);
|
||||
}
|
||||
cb();
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
SessionManager.prototype.logOut = function(req, options, cb) {
|
||||
if (typeof options == 'function') {
|
||||
cb = options;
|
||||
options = {};
|
||||
}
|
||||
options = options || {};
|
||||
|
||||
if (!req.session) { return cb(new Error('Login sessions require session support. Did you forget to use `express-session` middleware?')); }
|
||||
|
||||
var self = this;
|
||||
|
||||
// clear the user from the session object and save.
|
||||
// this will ensure that re-using the old session id
|
||||
// does not have a logged in user
|
||||
if (req.session[this._key]) {
|
||||
delete req.session[this._key].user;
|
||||
}
|
||||
var prevSession = req.session;
|
||||
|
||||
req.session.save(function(err) {
|
||||
if (err) {
|
||||
return cb(err)
|
||||
}
|
||||
|
||||
// regenerate the session, which is good practice to help
|
||||
// guard against forms of session fixation
|
||||
req.session.regenerate(function(err) {
|
||||
if (err) {
|
||||
return cb(err);
|
||||
}
|
||||
if (options.keepSessionInfo) {
|
||||
merge(req.session, prevSession);
|
||||
}
|
||||
cb();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
module.exports = SessionManager;
|
||||
131
auth-service/node_modules/passport/lib/strategies/session.js
generated
vendored
Normal file
131
auth-service/node_modules/passport/lib/strategies/session.js
generated
vendored
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
// Module dependencies.
|
||||
var pause = require('pause')
|
||||
, util = require('util')
|
||||
, Strategy = require('passport-strategy');
|
||||
|
||||
|
||||
/**
|
||||
* Create a new `SessionStrategy` object.
|
||||
*
|
||||
* An instance of this strategy is automatically used when creating an
|
||||
* `{@link Authenticator}`. As such, it is typically unnecessary to create an
|
||||
* instance using this constructor.
|
||||
*
|
||||
* @classdesc This `Strategy` authenticates HTTP requests based on the contents
|
||||
* of session data.
|
||||
*
|
||||
* The login session must have been previously initiated, typically upon the
|
||||
* user interactively logging in using a HTML form. During session initiation,
|
||||
* the logged-in user's information is persisted to the session so that it can
|
||||
* be restored on subsequent requests.
|
||||
*
|
||||
* Note that this strategy merely restores the authentication state from the
|
||||
* session, it does not authenticate the session itself. Authenticating the
|
||||
* underlying session is assumed to have been done by the middleware
|
||||
* implementing session support. This is typically accomplished by setting a
|
||||
* signed cookie, and verifying the signature of that cookie on incoming
|
||||
* requests.
|
||||
*
|
||||
* In {@link https://expressjs.com/ Express}-based apps, session support is
|
||||
* commonly provided by {@link https://github.com/expressjs/session `express-session`}
|
||||
* or {@link https://github.com/expressjs/cookie-session `cookie-session`}.
|
||||
*
|
||||
* @public
|
||||
* @class
|
||||
* @augments base.Strategy
|
||||
* @param {Object} [options]
|
||||
* @param {string} [options.key='passport'] - Determines what property ("key") on
|
||||
* the session data where login session data is located. The login
|
||||
* session is stored and read from `req.session[key]`.
|
||||
* @param {function} deserializeUser - Function which deserializes user.
|
||||
*/
|
||||
function SessionStrategy(options, deserializeUser) {
|
||||
if (typeof options == 'function') {
|
||||
deserializeUser = options;
|
||||
options = undefined;
|
||||
}
|
||||
options = options || {};
|
||||
|
||||
Strategy.call(this);
|
||||
|
||||
/** The name of the strategy, set to `'session'`.
|
||||
*
|
||||
* @type {string}
|
||||
* @readonly
|
||||
*/
|
||||
this.name = 'session';
|
||||
this._key = options.key || 'passport';
|
||||
this._deserializeUser = deserializeUser;
|
||||
}
|
||||
|
||||
// Inherit from `passport.Strategy`.
|
||||
util.inherits(SessionStrategy, Strategy);
|
||||
|
||||
/**
|
||||
* Authenticate request based on current session data.
|
||||
*
|
||||
* When login session data is present in the session, that data will be used to
|
||||
* restore login state across across requests by calling the deserialize user
|
||||
* function.
|
||||
*
|
||||
* If login session data is not present, the request will be passed to the next
|
||||
* middleware, rather than failing authentication - which is the behavior of
|
||||
* most other strategies. This deviation allows session authentication to be
|
||||
* performed at the application-level, rather than the individual route level,
|
||||
* while allowing both authenticated and unauthenticated requests and rendering
|
||||
* responses accordingly. Routes that require authentication will need to guard
|
||||
* that condition.
|
||||
*
|
||||
* This function is protected, and should not be called directly. Instead,
|
||||
* use `passport.authenticate()` middleware and specify the {@link SessionStrategy#name `name`}
|
||||
* of this strategy and any options.
|
||||
*
|
||||
* @protected
|
||||
* @param {http.IncomingMessage} req - The Node.js {@link https://nodejs.org/api/http.html#class-httpincomingmessage `IncomingMessage`}
|
||||
* object.
|
||||
* @param {Object} [options]
|
||||
* @param {boolean} [options.pauseStream=false] - When `true`, data events on
|
||||
* the request will be paused, and then resumed after the asynchronous
|
||||
* `deserializeUser` function has completed. This is only necessary in
|
||||
* cases where later middleware in the stack are listening for events,
|
||||
* and ensures that those events are not missed.
|
||||
*
|
||||
* @example
|
||||
* passport.authenticate('session');
|
||||
*/
|
||||
SessionStrategy.prototype.authenticate = function(req, options) {
|
||||
if (!req.session) { return this.error(new Error('Login sessions require session support. Did you forget to use `express-session` middleware?')); }
|
||||
options = options || {};
|
||||
|
||||
var self = this,
|
||||
su;
|
||||
if (req.session[this._key]) {
|
||||
su = req.session[this._key].user;
|
||||
}
|
||||
|
||||
if (su || su === 0) {
|
||||
// NOTE: Stream pausing is desirable in the case where later middleware is
|
||||
// listening for events emitted from request. For discussion on the
|
||||
// matter, refer to: https://github.com/jaredhanson/passport/pull/106
|
||||
|
||||
var paused = options.pauseStream ? pause(req) : null;
|
||||
this._deserializeUser(su, req, function(err, user) {
|
||||
if (err) { return self.error(err); }
|
||||
if (!user) {
|
||||
delete req.session[self._key].user;
|
||||
} else {
|
||||
var property = req._userProperty || 'user';
|
||||
req[property] = user;
|
||||
}
|
||||
self.pass();
|
||||
if (paused) {
|
||||
paused.resume();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
self.pass();
|
||||
}
|
||||
};
|
||||
|
||||
// Export `SessionStrategy`.
|
||||
module.exports = SessionStrategy;
|
||||
Loading…
Add table
Add a link
Reference in a new issue