Skip to content

Instantly share code, notes, and snippets.

@moaoa
Last active July 3, 2020 10:48
Show Gist options
  • Save moaoa/6c024d2b2120807d37dbe146e5e312e1 to your computer and use it in GitHub Desktop.
Save moaoa/6c024d2b2120807d37dbe146e5e312e1 to your computer and use it in GitHub Desktop.
// gnerate token function
const jwt = require('jsonwebtoken');
const jwtSecret = process.env.JWT_SECRET;
module.exports = (obj) => {
return jwt.sign(obj, jwtSecret, {
expiresIn: '1day',
});
};
// ==================
// auth middelware
const jwt = require('jsonwebtoken');
const jwtSecret = process.env.JWT_SECRET;
module.exports = (req, res, next) => {
let token = req.header('authorization');
if (!token)
return res.status(401).json({ msg: 'No Token autorization denied' });
token = token.replace('Bearer ', '');
try {
const decoded = jwt.verify(token, jwtSecret);
req.user = decoded;
} catch (error) {
res.status(400).json({ msg: 'Token is Not valid' });
console.log(error);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment