-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
69 lines (64 loc) · 1.99 KB
/
utils.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
65
66
67
68
69
const jwt = require('jsonwebtoken');
const config = require('./config.json');
var { users, products } = require('./db');
// UTILS
const getProduct = (productId) => {
return new Promise((resolve, reject) => {
products.findOne({ _id: productId }, (err, docs) => {
if (err) {
reject(err);
}
resolve(docs);
});
});
};
const verifyAuth = (req, res, next) => {
if (
req.headers.authorization &&
req.headers.authorization.split(' ').length > 1 &&
req.headers.authorization.split(' ')[0] === 'Bearer'
) {
jwt.verify(
req.headers.authorization.split(' ')[1],
config.jwtSecret,
{},
(err, payload) => {
if (err) {
return res.status(400).json({
success: false,
message: 'Bad or expired token'
});
}
users.findOne({ username: payload.username }, (err, user) => {
if (err) {
return handleError(res, err);
}
if (!user) {
return res.status(400).json({
success: false,
message: 'Bad token or user no longer exists'
});
}
req.user = user;
next();
});
}
);
} else {
return res.status(401).json({
success: false,
message: 'Protected route, Oauth2 Bearer token not found'
});
}
};
const handleError = (res, err) => {
console.log(err);
return res.status(500).json({
success: false,
message:
'Something went wrong. Check the backend console for more details'
});
};
module.exports.handleError = handleError;
module.exports.verifyAuth = verifyAuth;
module.exports.getProduct = getProduct;