-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
40 lines (32 loc) · 838 Bytes
/
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
const db = require('./db/models');
const { User } = db;
const loginUser = (req, res, user) => {
req.session.auth = { userId: user.id };
}
const logoutUser = (req, res) => {
delete req.session.auth;
}
const restoreUser = async (req, res, next) => {
console.log(req.session);
if (req.session.auth) {
const { userId } = req.session.auth;
const user = await User.findByPk(userId);
if (user) {
res.locals.authenticated = true;
res.locals.user = user;
next();
} else {
res.locals.authenticated = false;
const err = new Error('Cannot login user.');
next(err);
}
} else {
res.locals.authenticated = false;
next();
}
}
module.exports = {
loginUser,
restoreUser,
logoutUser
};