-
Notifications
You must be signed in to change notification settings - Fork 2
/
authenticate.js
38 lines (35 loc) · 1.11 KB
/
authenticate.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
const jwt = require('jsonwebtoken');
const config = require('./config/config');
const mongoose = require('mongoose');
const Users = mongoose.model("User");
exports.verifyUser = (req, res, next) => {
const{authorization} = req.headers;
if (!authorization) {
res.statusCode = 401;
res.setHeader('Content-Type', 'application/json');
res.json({error: "You must be logged in"});
return;
}
const token = authorization.replace("Bearer ", "");
jwt.verify(token, config.secretKey, (err, payload) => {
if (err) {
res.statusCode = 401;
res.setHeader('Content-Type', 'application/json');
res.json({error: "You must be logged in"});
return;
}
const {_id} = payload;
Users.findById(_id).then((user) => {
if (!user) {
res.statusCode = 401;
res.setHeader('Content-Type', 'application/json');
res.json({error: "Invalid token"});
return;
}
req.user = user;
req.user.password = undefined;
req.user.createdAt = undefined; req.user.updatedAt = undefined;
next();
}, (err) => next(err)).catch((err) => next(err));
});
}