-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjwt.js
39 lines (32 loc) · 1.07 KB
/
jwt.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
const jwt = require('jsonwebtoken')
//Decode JWT -> user data payload
const jwtAuthMiddleware = (req, res, next) => {
//first checking request header has authorization or not
const authorization = req.headers.authorization
if (!authorization) return res.status(401).json({
error: 'Token Not found'
})
//extract jwt token from request
const token = req.headers.authorization.split(' ')[1]
if (!token) return res.status(401).json({
error: 'UnAuthorized'
})
try {
//verify the JWT token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
//Attach user information to the request object
req.user = decoded
next();
} catch (error) {
console.log(error);
res.status(401).json({
error: 'Invalid token'
})
}
}
//Funtion to generate JWT token
const generateToken = (userData) => {
//generate a new JWT token using user data
return jwt.sign(userData, process.env.JWT_SECRET, { expiresIn: 30000 })
}
module.exports = { jwtAuthMiddleware, generateToken }