Skip to content

Instantly share code, notes, and snippets.

@pravin772
Last active July 11, 2020 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pravin772/cf4b73f2114607ebad25a1445914937a to your computer and use it in GitHub Desktop.
Save pravin772/cf4b73f2114607ebad25a1445914937a to your computer and use it in GitHub Desktop.
Auth middleware using JWT
const jwt = require('jsonwebtoken')
const verifyToken = (req, res, next) => {
const token = req.headers['x-access-token'] || req.headers['authorization']
if(token){
jwt.verify(token, "chor", (err, decoded) => {
if(err){
res.status(403).json({ err })
}
if(decoded){
req.decoded = decoded
next()
}
})
}
else{
res.status(403).json({ msg: "Token not provided"})
}
}
const signToken = (req, res, next) => {
const { email, password } = req.body
// Below info should be fetched from DB
let checkEmail = "admin@domain.com"
let checkPassword = "123"
if(email && password) {
if(email === checkEmail && password === checkPassword){
let token = jwt.sign({email: email}, "chor", { expiresIn: "1h"}) // expires in 1 hour
res.status(400).json({ msg: "Authentication successful", token: token})
}
else{
res.status(403).json({ msg: "Credentials not correct"})
}
}
else{
res.status(403).json({ msg: "No email and password provided"})
}
}
module.exports = { verifyToken, signToken }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment