Using Node.js, I am able to create a user an assign a token via jwt.sign(). This seems to be working. The error is when I try to validate that the user is logged in. I try to verify that the header exist but req.headers.authorization gives me undefined.
//login, this seems to work fine.
module.exports.login = function(req, res) {
console.log('logging in a Auth_user')
console.log(req.body)
models.Auth_user.findOne({
where: {email: req.body.email}
}).then(function(user) {
// console.log(user)
console.log(user.email)
console.log(user.first_name)
console.log(user.password)
if (user == null){
console.log('no user found with email')
// res.redirect('/users/sign-in')
}
bcrypt.compare(req.body.password, user.password, function(err, result) {
if (result == true){
console.log('password is valid')
var token = jwt.sign({ username: user.email }, 'passwordgoeshere', { expiresIn: 600 });
return res.send()
res.status(200).json({success: true, token: token});
res.redirect('/holders')
}
else{
console.log('password incorrect')
res.redirect('/home')
}
});
})
};
//authenticate, this is where I cannot verify header
module.exports.authenticate = function(req, res, next) {
console.log('authenticating')
console.log(req.headers.authorization)
var headerExists = req.headers.authorization;
if (headerExists) {
var token = req.headers.authorization.split(' ')[1]; //--> Authorization Bearer xxx
jwt.verify(token, 'passwordgoeshere', function(error, decoded) {
if (error) {
console.log(error);
res.status(401).json('Unauthorized');
} else {
req.user = decoded.username;
var authenticated = true;
next();
}
});
} else {
res.status(403).json('No token provided');
}
};
via Edwin Rodriguez
No comments:
Post a Comment