-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
44 lines (37 loc) · 934 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
41
42
43
44
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const SALT_ROUNDS = 11;
const TOKEN_KEY = 'areallylonggoodkey';
const hashPassword = async (password) => {
const digest = await bcrypt.hash(password, SALT_ROUNDS);
return digest;
}
const checkPassword = async (password, password_digest) => {
return await bcrypt.compare(password, password_digest);
}
const genToken = async (user) => {
const tokenData = {
id: user.id,
name: user.name,
email: user.email
};
const token = await jwt.sign(tokenData, TOKEN_KEY);
return token;
};
const restrict = (req, res, next) => {
try {
const token = req.headers.authorization.split(" ")[1];
const data = jwt.verify(token, TOKEN_KEY);
res.locals.user = data;
next();
} catch (e) {
console.log(e);
res.status(403).send('Unauthorized');
}
}
module.exports = {
hashPassword,
checkPassword,
genToken,
restrict,
};