forked from rojo2/passport-cookie
-
Notifications
You must be signed in to change notification settings - Fork 1
/
strategy.js
97 lines (87 loc) · 1.99 KB
/
strategy.js
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
/**
* Module dependencies.
*/
var passport = require("passport-strategy");
var util = require("util");
/**
* Creates an instance of `Strategy`.
*
* Options:
*
* - `cookieName` Cookie name (defaults to "token")
* - `passReqToCallback` when `true`, `req` is the first argument to the verify callback (default: `false`)
*
* Examples:
*
* passport.use(new CookieStrategy(
* function(token, done) {
* User.findByToken({ token: token }, function(err, user) {
* if (err) { return done(err); }
* if (!user) { return done(null, false); }
* return done(null, user);
* });
* }
* ));
*
* @constructor
* @param {Object} [options]
* @param {Function} verify
* @api public
*/
function Strategy(options, verify) {
if (typeof options === "function") {
verify = options;
options = {};
}
if (!verify) {
throw new TypeError("CookieStrategy requires a verify callback");
}
passport.Strategy.call(this);
this.name = "cookie";
this._cookieName = options.cookieName || "token";
this._verify = verify;
this._passReqToCallback = options.passReqToCallback;
}
/**
* Inherits from `passport.Strategy`
*/
util.inherits(Strategy, passport.Strategy);
/**
* Authenticate request based on cookie.
*
* @param {Object} req
* @api protected
*/
Strategy.prototype.authenticate = function(req) {
if (!req.cookies) {
throw new TypeError("Maybe you forgot to use cookie-parser?");
}
var token;
if (req.cookies[this._cookieName]) {
token = req.cookies[this._cookieName];
}
if (!token) {
return this.fail(401);
}
var self = this;
function verified(err, user) {
if (err) { return self.error(err); }
if (!user) {
return self.fail(401);
}
self.success(user);
}
try {
if (self._passReqToCallback) {
this._verify(req, token, verified);
} else {
this._verify(token,verified);
}
} catch (ex) {
return self.error(ex);
}
};
/**
* Expose `Strategy`
*/
module.exports = Strategy;