forked from mdrcode/node-chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
61 lines (58 loc) · 1.58 KB
/
auth.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
exports.AuthHelper = {
/**
* Authenticates a request using the login token
*
* @param express request
* @param express response
* @param express next function
*/
authFromLoginToken: function(req, res, next) {
var cookie = JSON.parse(req.cookies.logintoken);
LoginToken.findOne({ email: cookie.email, token: cookie.token, series: cookie.series }, function(err, token) {
if (!token) {
res.redirect('/');
return;
}
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('/login');
}
});
});
},
/**
* Loads the used for a request
*
* @param express request
* @param express response
* @param express next function
*/
loadUser: function(req, res, next) {
if (app.set('disableAuthentication') === true)
next();
else {
if (req.session.user_id) {
User.findById(req.session.user_id, function(err, user) {
if (user) {
req.currentUser = user;
next();
} else {
res.redirect('/');
}
});
} else if (req.cookies.logintoken) {
authFromLoginToken(req, res, next);
} else {
res.redirect('/');
}
}
}
};