-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.js
56 lines (49 loc) · 1.5 KB
/
util.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
function loadUser(req, res, next) {
if (req.session.user) {
models.User.findById(req.session.user._id, function(err, user) {
if (user) {
req.currentUser = user;
next();
} else {
res.redirect('/sessions/new');
}
});
} else if (req.cookies.logintoken) {
authenticateFromLoginToken(req, res, next);
} else {
res.redirect('/sessions/new');
}
}
function authenticateFromLoginToken(req, res, next) {
var cookie = JSON.parse(req.cookies.logintoken);
LoginToken = app.mongoose.model('LoginToken');
LoginToken.findOne({ email: cookie.email,
series: cookie.series,
token: cookie.token }, (function(err, token) {
if (!token) {
res.redirect('/sessions/new');
return;
}
models.User.findOne({ email: token.email }, function(err, user) {
if (user) {
req.session.user_id = user.id;
req.currentUser = user;
token.token = token.randomToken();
token.save(function() {
res.cookie('logintoken', token.cookieValue, { expires: new Date(Date.now() + 2 * 604800000), path: '/' });
next();
});
} else {
res.redirect('/sessions/new');
}
});
}));
}
function NotFound(msg) {
this.name = 'NotFound';
Error.call(this, msg);
Error.captureStackTrace(this, arguments.callee);
}
module.exports.loadUser = loadUser;
module.exports.authenticateFromLoginToken = authenticateFromLoginToken;
module.exports.NotFound = NotFound