Last active
September 3, 2019 10:10
-
-
Save techtocore/874bdf0c295b5a81c734f43361e1f8e0 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
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens | |
var config = require('../../config'); // get our config file | |
var User = require('./../user/User'); | |
async function check(req) { | |
var token = req.headers['authorization']; | |
if (!token || !token.split(' ')[1]) | |
throw new Error('No token provided'); | |
var decoded = await jwt.verify(token.split(' ')[1], config.secret); | |
req.username = decoded.username; | |
var obj = await User.findOne({ username: req.username }) | |
if (!obj) | |
throw new Error('Failed to find user'); | |
return true; | |
} | |
function verifyToken(req, res, next) { | |
check(req).then((obj) => { | |
next(); | |
}).catch((err) => { | |
res.status(401).send({ auth: false, message: err.toString() }); | |
}); | |
} | |
module.exports = verifyToken; |
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
router.post('/login', function (req, res) { | |
User.findOne({ username: req.body.username }, async function (err, user) { | |
if (err) return res.status(500).send({ message: err.toString() }); | |
if (!user) return res.status(400).send({ message: 'Invalid Credentials' }); | |
if (user.password === req.body.password) | |
var passwordIsValid = true; | |
if (!passwordIsValid) return res.status(400).send({ auth: false, token: null, message: 'Invalid Credentials' }); | |
var token = jwt.sign({ username: user.username }, config.secret, { | |
expiresIn: 86400 // expires in 24 hours | |
}); | |
res.status(200).send({ auth: true, token: token }); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment