-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
isLoggedIn.js
74 lines (55 loc) · 2.67 KB
/
isLoggedIn.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
const moment = require('moment-timezone');
// Standardize messages; not just for ease of change...
const invalid = 'Invalid credentials.';
const notLoggedIn = 'You are not logged in';
module.exports = async function(req, res, next) {
const sessionId = req.signedCookies[sails.config.session.name] || null; // signed cookies: https://sailsjs.com/documentation/reference/request-req/req-signed-cookies
// Do we have a signed cookie?
if (sessionId) {
const foundSession = await sails.models.session.findOne({id: sessionId}).decrypt().populate('user');
// Has the session expired?
if (moment(foundSession.expiresAt).isBefore(moment(new Date()))) {
res.clearCookie(sails.config.session.name, {signed: true, secure: sails.config.session.cookie.secure});
await sails.models.session.destroy({id: sessionId});
return res.forbidden(notLoggedIn);
}
// If the session was found...
if (foundSession && foundSession.user) {
req.session = {id: sessionId, user: foundSession.user, data: foundSession.data};
if (req.method !== 'GET') {
const csrf = req.headers['x-csrf-token'];
// verify the CSRF token is still valid
if (csrf && sails.helpers.verifyCsrfToken.with({token: csrf, secret: foundSession.csrfSecret})) {
return next();
}
} else {
return next();
}
}
// Doesn't look like this session is valid, remove the cookie.
/* istanbul ignore next */
res.clearCookie(sails.config.session.name, {signed: true, secure: sails.config.session.cookie.secure});
} else {
// We couldn't find a session via cookies, let's check headers...
let token = req.headers['authorization'] || null;
if (token) {
if (token.includes('Bearer ')) {
token = token.substring(7);
}
if (!token.includes(':')) {
return res.forbidden(invalid);
}
token = token.split(':');
const foundToken = await sails.models.apitoken.findOne({id: token[0]}).decrypt().populate('user');
if (!foundToken || token[1] !== foundToken.token) {
return res.forbidden(invalid);
}
if (foundToken) {
await sails.models.apitoken.updateOne({id: foundToken.id}).set({updatedAt: new Date()});
req.session = {id: foundToken.id, user: foundToken.user, data: foundToken.data, isAPIToken: true};
return next();
}
}
}
return res.forbidden(notLoggedIn);
};