Implement auth with jwt and add endpoints
This commit is contained in:
36
helpers/authJwt.js
Normal file
36
helpers/authJwt.js
Normal file
@@ -0,0 +1,36 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { jwt_secret } = require('../config/config');
|
||||
|
||||
module.exports = {
|
||||
authenticate,
|
||||
generateToken,
|
||||
};
|
||||
|
||||
function generateToken(user) {
|
||||
const payload = {
|
||||
username: user.username,
|
||||
email: user.email
|
||||
};
|
||||
|
||||
const options = {
|
||||
expiresIn: '30d',
|
||||
};
|
||||
|
||||
return jwt.sign(payload, jwt_secret, options);
|
||||
}
|
||||
|
||||
function authenticate(req, res, next) {
|
||||
const token = req.get('Authorization');
|
||||
|
||||
if (token) {
|
||||
jwt.verify(token, jwt_secret, (err, decoded) => {
|
||||
if (err) return res.status(401).json(err);
|
||||
req.decoded = decoded;
|
||||
next();
|
||||
});
|
||||
} else {
|
||||
return res.status(401).json({
|
||||
error: 'No token provided, must be set on the Authorization Header',
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user