-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsession.js
32 lines (29 loc) · 864 Bytes
/
session.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
'use strict';
const cookie = require('cookie');
const users = require('./users');
const cookieKey = 'SID';
const cookiePrefix = 'Session::';
module.exports = {
getSession: (headers) => {
const cookieStr = headers ? (headers.Cookie || '') : '';
const cookies = cookie.parse(cookieStr);
if (!cookies[cookieKey]) {
return { valid: false };
}
const username = cookies[cookieKey].replace(cookiePrefix, '');
const user = users[username];
return {
valid: !!user,
user: user
};
},
setSession: (user) => {
const sessionId = `${cookiePrefix}${user.username}`;
const newCookie = cookie.serialize(cookieKey, sessionId);
return { Cookie: newCookie };
},
destroySession: (user) => {
const clearCookie = cookie.serialize(cookieKey, 'empty', { maxAge: 0 });
return { Cookie: clearCookie };
}
};