-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
33 lines (29 loc) · 749 Bytes
/
auth.js
File metadata and controls
33 lines (29 loc) · 749 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
31
32
33
require("dotenv").config();
const jwt = require("jsonwebtoken");
async function generateAccessToken(user) {
return jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn: "1h" });
}
async function authenticateToken(req, res, next) {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({
status: 401,
error: "Unauthorized"
});
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) {
return res.status(403).json({
status: 403,
error: "Forbidden"
});
}
req.user = user;
next();
})
}
module.exports = {
generateAccessToken,
authenticateToken
};