-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjwt.js
More file actions
35 lines (27 loc) · 1.21 KB
/
jwt.js
File metadata and controls
35 lines (27 loc) · 1.21 KB
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
const jwt = require("jsonwebtoken");
const jwtAuthMiddleware = (req, res, next) => {
//First check if the request has an authorization header or not
const authorization = req.headers.authorization;
if (!authorization) {
return res.status(401).json({ error: "Authorization header is missing" });
}
//Extract the jwt token from the authorization header
const token = req.headers.authorization.split(" ")[1];
if( !token) return res.status(401).json({ error: "Unauthorized or Authorization header is missing" });
try {
//Verify the token using the secret key
const decoded = jwt.verify(token, process.env.JWT_SECRET);
//Attach the decoded user information to the request object
req.user = decoded;
//Call the next middleware or route handler
next();
} catch (error) {
return res.status(401).json({ error: "Invalid or expired JWT token" });
}
};
// Function to generate a JWT token
const generateToken = (userData) => {
//Gnerate a new JWT token using the user data and secret key
return jwt.sign(userData, process.env.JWT_SECRET, {expiresIn: 36000});
};
module.exports = { jwtAuthMiddleware, generateToken };