This repository has been archived by the owner on Apr 5, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 58
/
session.js
49 lines (40 loc) · 1.31 KB
/
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
const {Router} = require('express');
const bcrypt = require('bcrypt');
const User = require('../persistence/users');
const Session = require('../persistence/sessions');
const sessionMiddleware = require('../middleware/session-middleware');
const router = new Router();
router.post('/', async (request, response) => {
try {
const {email, password} = request.body;
// eslint-disable-next-line unicorn/no-fn-reference-in-iterator
const user = await User.find(email);
if (!user || !(await bcrypt.compare(password, user.password))) {
return response.status(403).json({});
}
const sessionId = await Session.create(user.id);
request.session.id = sessionId;
response.status(201).json();
} catch (error) {
console.error(
`POST session ({ email: ${request.body.email} }) >> ${error.stack})`
);
response.status(500).json();
}
});
router.get('/', sessionMiddleware, (request, response) => {
response.json({userId: request.userId});
});
router.delete('/', async (request, response) => {
try {
if (request.session.id) {
await Session.delete(request.session.id);
}
request.session.id = null;
response.status(200).json();
} catch (error) {
console.error(`DELETE session >> ${error.stack}`);
response.status(500).json();
}
});
module.exports = router;