-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathauth.js
64 lines (52 loc) · 1.69 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
62
63
64
const jwt = require('jsonwebtoken');
const userModel = require('./models/user_model');
const authRegex = /Bearer (.+)/;
const extractToken = (authHeader) => authRegex.exec(authHeader)[1];
module.exports.extractToken = extractToken;
module.exports.generateToken = (email) => {
return new Promise((resolve, reject) => {
jwt.sign({ email }, process.env.SECRET_KEY, { expiresIn: '1h' }, (err, token) => {
if (!err) resolve(token);
else reject(err);
});
});
};
const validateToken = (req, res, next) => {
const { headers: { authorization } } = req;
const token = extractToken(authorization);
jwt.verify(token, process.env.SECRET_KEY, (err, decoded) => {
if (!err) {
req.auth = decoded;
next();
}
else {
console.error('Invalid token', err);
res.status(401).send(null);
}
});
};
module.exports.validateToken = validateToken;
const validateUser = async (email, res, next) => {
const isValidUser = await userModel.isValidUser(email);
if (!isValidUser) {
console.log(`Invalid user ${email}`);
return res.status(403).send(null);
}
const hasVoted = await userModel.hasUserVoted(email);
if (hasVoted) {
console.log(`User ${email} has already voted!`);
return res.status(409).send(null);
}
next();
};
module.exports.verifyUser = async (req, res, next) => {
const { body: { email } } = req;
if (!email) {
validateToken(req, res, async () => {
const { auth: { email } } = req;
await validateUser(email, res, next);
});
} else {
await validateUser(email, res, next);
}
};