Last active
September 18, 2020 12:41
-
-
Save marcelobbfonseca/9e03feb6a017833c98fb4f7200829ece to your computer and use it in GitHub Desktop.
ExpressJS user sign-in route with JWT RSA algorithm example
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
// User sign-in route with JWT RSA algorithm example | |
var User = require('../models/user') | |
var express = require('express'); | |
var router = express.Router(); | |
const mongoose = require('mongoose'); | |
const bcrypt = require('bcrypt'); | |
const jwt = require('jsonwebtoken'); | |
const fs = require('fs'); | |
router.route('/sign-in').post(function(req, res, next){ | |
User.find({ email: req.body.email}).then(user => { | |
if (user.length < 1) | |
return res.status(400).json({message: 'Authentication failed.'}); | |
bcrypt.compare(req.body.password, user[0].passwordHash, (err, success) => { | |
if(success){ | |
let cert = process.env.PRIVATE_KEY; | |
const token = jwt.sign( | |
{ | |
email: user[0].email, | |
//id: user[0]._id, | |
}, | |
cert, | |
{ | |
expiresIn: '1h', | |
algorithm: 'RS256', | |
issuer: user[0].role, | |
} | |
); | |
res.status(200).json({token: token, message: 'Successfully authenticated.'}); | |
}else | |
return res.status(400).json({message: 'Authentication failed.'}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment