Skip to content

Instantly share code, notes, and snippets.

@eoguvo
Last active March 19, 2024 12:42
Show Gist options
  • Save eoguvo/d0cd75b59c7c8ea4ef263e773c549e29 to your computer and use it in GitHub Desktop.
Save eoguvo/d0cd75b59c7c8ea4ef263e773c549e29 to your computer and use it in GitHub Desktop.
const jwt = require('jsonwebtoken')
const dotenv = require('dotenv').config();
const authConfig = process.env.AUTH
module.exports = (req, res, next) => {
const authHeader = req.headers.authorization
if (!authHeader){
return res.status(401).send({error: 'No token provided'})
}
// Bearer hash
const parts = authHeader.split(' ');
if (!parts.length === 2) {
return res.status(401).send({error: 'token error'})
}
const [ scheme, token ] = parts
if (! /^Bearer$/i.test(scheme)) {
return res.status(401).send({ error: 'token malformated' })
}
jwt.verify(token, authConfig, (err, decoded)=>{
if (err) return res.status(401).send({ error: 'invalid Token' })
req.userId = decoded.id;
return next();
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment