request.js
2.25 KB
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
98
99
100
/**
* Module dependencies.
*/
//var http = require('http')
// , req = http.IncomingMessage.prototype;
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 = 'user';
if (this._passport && this._passport.instance) {
property = this._passport.instance._userProperty || 'user';
}
var session = (options.session === undefined) ? true : options.session;
this[property] = user;
if (session) {
if (!this._passport) { throw new Error('passport.initialize() middleware not in use'); }
if (typeof done != 'function') { throw new Error('req#login requires a callback function'); }
var self = this;
this._passport.instance._sm.logIn(this, user, 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() {
var property = 'user';
if (this._passport && this._passport.instance) {
property = this._passport.instance._userProperty || 'user';
}
this[property] = null;
if (this._passport) {
this._passport.instance._sm.logOut(this);
}
};
/**
* Test if request is authenticated.
*
* @return {Boolean}
* @api public
*/
req.isAuthenticated = function() {
var property = 'user';
if (this._passport && this._passport.instance) {
property = this._passport.instance._userProperty || 'user';
}
return (this[property]) ? true : false;
};
/**
* Test if request is unauthenticated.
*
* @return {Boolean}
* @api public
*/
req.isUnauthenticated = function() {
return !this.isAuthenticated();
};