Last active
July 11, 2020 09:28
-
-
Save pravin772/cf4b73f2114607ebad25a1445914937a to your computer and use it in GitHub Desktop.
Auth middleware using JWT
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 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