-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
30 lines (25 loc) · 847 Bytes
/
auth.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
const jwt = require('jsonwebtoken');
const dotenv = require("dotenv")
dotenv.config();
function generateAccessToken(id) {
return jwt.sign({sub: id}, process.env.JWT_SECRET, {expiresIn: '3d'});
}
function verifyJWT(req, res, next) { // supports authentication through httpOnly cookie or token bearer
const cookies = req.cookies;
const bearer = req.headers.authorization
const token = bearer ? bearer.split(' ')[1] : cookies.access_token; // if no bearer present then check for cookie
if (token) {
jwt.verify(token, process.env.JWT_SECRET, (err, payload) => {
if (err) return res.sendStatus(403);
console.log(payload);
req.id = payload.sub;
next();
})
} else {
res.sendStatus(401)
}
}
module.exports = {
generateAccessToken,
verifyJWT
}