-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsessions.js
85 lines (72 loc) · 2.19 KB
/
sessions.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
const db = require('../models');
const util = require('../utilities');
async function create(req, res) {
try {
// Get the token
const { token } = req.body;
util.Error.validateUUID(token);
// Load the token from the database, and make sure it's not missing or expired
const foundToken = await db.Token.findById(token);
util.Error.validateExists(foundToken);
util.Error.validateNotExpired(foundToken);
// Delete the token, since it's being used
db.Token.findByIdAndDelete(token);
// Create a new session for the user
const session = await db.Session.create({ account: foundToken.account });
// Get the account for this session
const account = await db.Account
.findById(session.account)
.select('email name picUrl model');
// Return the session ID and account info
const data = {
id: session.id,
account,
};
res.status(201).json(data);
} catch (err) {
await db.Token.findByIdAndDelete(err.itemId);
util.Error.handleErrors(err, res);
}
}
async function validate(req, res) {
try {
// Get the session id
const sessionId = req.params.id;
util.Error.validateUUID(sessionId);
// Try to find the session in the database
const session = await db.Session.findById(sessionId)
.populate('account');
// Check if it exists, and if it's not expired
util.Error.validateExists(session);
util.Error.validateNotExpired(session);
// Refresh with a new expiration
session.refresh();
await session.save();
// Return the session ID and account info
const data = {
id: session.id,
account: util.Account.trimAccount(session.account),
};
res.status(200).json(data);
} catch (err) {
util.Error.handleErrors(err, res);
}
}
async function remove(req, res) {
try {
const sessionId = req.params.id;
util.Error.validateUUID(sessionId);
const session = await db.Session.findById(sessionId)
.populate('account');
util.Error.validateExists(session);
await db.Session.findByIdAndDelete(session.id);
res.sendStatus(200);
} catch (err) {
util.Error.handleErrors(err, res);
}
}
module.exports = {
create,
validate,
remove,
};