Last active
September 8, 2021 04:00
-
-
Save FermiDirak/3f508d75286ad111c3a6558f53a60e46 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 express = require('express'); | |
const passport = require('passport'); | |
const bcrypt = require('bcrypt'); | |
const jwt = require('jsonwebtoken'); | |
const keys = require('../keys'); | |
const UserModel = require('../models/user'); | |
const router = express.Router(); | |
router.post('/register', async (req, res) => { | |
const { username, password } = req.body; | |
// authentication will take approximately 13 seconds | |
// https://pthree.org/wp-content/uploads/2016/06/bcrypt.png | |
const hashCost = 10; | |
try { | |
const passwordHash = await bcrypt.hash(password, hashCost); | |
const userDocument = new UserModel({ username, passwordHash }); | |
await userDocument.save(); | |
res.status(200).send({ username }); | |
} catch (error) { | |
res.status(400).send({ | |
error: 'req body should take the form { username, password }', | |
}); | |
} | |
}); | |
router.post('/login', (req, res) => { | |
passport.authenticate( | |
'local', | |
{ session: false }, | |
(error, user) => { | |
if (error || !user) { | |
res.status(400).json({ error }); | |
} | |
/** This is what ends up in our JWT */ | |
const payload = { | |
username: user.username, | |
expires: Date.now() + parseInt(process.env.JWT_EXPIRATION_MS), | |
}; | |
/** assigns payload to req.user */ | |
req.login(payload, {session: false}, (error) => { | |
if (error) { | |
res.status(400).send({ error }); | |
} | |
/** generate a signed json web token and return it in the response */ | |
const token = jwt.sign(JSON.stringify(payload), keys.secret); | |
/** assign our jwt to the cookie */ | |
res.cookie('jwt', jwt, { httpOnly: true, secure: true }); | |
res.status(200).send({ username }); | |
}); | |
}, | |
)(req, res); | |
}); | |
module.exports = router; |
How can passport.authenticate('local') will identify passortSetup?config we have set
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 57
might need thetoken
variable you signed if I am reading this right.