-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmiddleware.js
More file actions
30 lines (21 loc) · 778 Bytes
/
middleware.js
File metadata and controls
30 lines (21 loc) · 778 Bytes
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
const JWT = require('jsonwebtoken');
const jwtSecret = process.env.JWT_SECRET
const {User } = require('./models')
exports.auth = async (req, res, next) => {
try {
//get token from header: Bearer <token>
const token = req.headers.authorization.split(' ')[1];
//verify this token was signed by your server
const decodedToken = JWT.verify(token, jwtSecret);
///Get your details
let user = await User.findById(decodedToken.userId)
if(!user) throw Error("Unauthenticated")
//put user in req object; so the controller can access current user
req.user = user
next();
} catch {
return res.status(401).json({
message: "Unauthenticated"
});
}
}