-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
61 lines (54 loc) · 1.36 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
const db = require('./db/models');
const loginUser = (req, res, user) => {
req.session.auth = {
userId: user.id,
};
};
const logoutUser = (req, res) => {
delete req.session.auth;
};
const requireAuth = async (req, res, next) => {
if (!res.locals.authenticated) {
return res.redirect('/users/login');
}
let userId = parseInt(req.url.split('/')[1], 10);
if (req.session.auth.userId !== userId) {
return res.redirect(`/user`);
}
const groupId = parseInt(req.url.split('/')[2], 10);
if (!isNaN(groupId)) {
const group = await db.group.findByPk(groupId);
if (!group && !undefined) return res.redirect(`/user`);
}
const taskId = parseInt(req.url.split('/')[3], 10);
if (!isNaN(taskId)) {
const task = await db.task.findByPk(taskId);
if (!task && !undefined) return res.redirect(`/user`);
}
return next();
};
const restoreUser = async (req, res, next) => {
if (req.session.auth) {
const { userId } = req.session.auth;
try {
const user = await db.user.findByPk(userId);
if (user) {
res.locals.authenticated = true;
res.locals.user = user;
next();
}
} catch (err) {
res.locals.authenticated = false;
next(err);
}
} else {
res.locals.authenticated = false;
next();
}
};
module.exports = {
loginUser,
logoutUser,
restoreUser,
requireAuth,
};