Last active
July 26, 2021 07:01
-
-
Save charliemerrell/0507ef05e81945e4a8bd1114d5183343 to your computer and use it in GitHub Desktop.
JWT Auth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const jwt = require("jsonwebtoken"); | |
function generateAccessToken(userId) { | |
return new Promise((resolve, reject) => { | |
jwt.sign( | |
{ | |
userId, | |
}, | |
process.env.JWT_SECRET, | |
{ expiresIn: "1h" }, | |
(err, token) => { | |
if (err) { | |
reject(err); | |
} else { | |
resolve(token); | |
} | |
} | |
); | |
}); | |
} | |
function verifyToken(req, res, next) { | |
const authHeader = req.headers.authorization; | |
if (authHeader) { | |
const token = authHeader.split(" ")[1]; // "Bearer kjhkf9s979fshjfa..." | |
console.log(authHeader); | |
jwt.verify(token, SECRET, (err, token) => { | |
if (err) { | |
return res.sendStatus(403); | |
} | |
req.userId = token.userId; | |
next(); | |
}); | |
} else { | |
res.sendStatus(401); | |
} | |
} | |
module.exports = { generateAccessToken, verifyToken }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment