Last active
March 19, 2024 12:42
-
-
Save eoguvo/d0cd75b59c7c8ea4ef263e773c549e29 to your computer and use it in GitHub Desktop.
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') | |
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