-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjwt.js
More file actions
26 lines (24 loc) · 963 Bytes
/
jwt.js
File metadata and controls
26 lines (24 loc) · 963 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
const jwt = require("jsonwebtoken");
const jwtAuthMiddleware = (req, res, next) => {
//First check request header has authorization or not
const authorization = req.headers.authorization;
if(!authorization) return res.status(401).json({error :"Token not found"})
//Extract the jws token from the request header
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.SECRET_KEY);
req.user = decoded;
next();
} catch (error) {
console.log(error);
res.status(401).json({ error: "Internal server" });
}
};
//Function the generate token
const generateToken = (userData) => {
//Generate a new jwt token using user data
return jwt.sign( userData , process.env.SECRET_KEY , {expiresIn: 9000})
}
module.exports = {jwtAuthMiddleware,generateToken};