-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
solution 4.18: bloglist expansion, step6. Add token-based auth.
- Loading branch information
1 parent
9e5dee6
commit 530d7c2
Showing
5 changed files
with
137 additions
and
2 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
const jwt = require('jsonwebtoken') | ||
const bcrypt = require('bcrypt') | ||
const loginRouter = require('express').Router() | ||
const User = require('../models/user') | ||
|
||
loginRouter.post('/', async (request, response) => { | ||
const body = request.body | ||
|
||
const user = await User.findOne({ username: body.username }) | ||
const passwordCorrect = | ||
user === null | ||
? false | ||
: await bcrypt.compare(body.password, user.passwordHash) | ||
|
||
if (!(user && passwordCorrect)) { | ||
return response.status(401).json({ | ||
error: 'invalid username or password', | ||
}) | ||
} | ||
|
||
const userForToken = { | ||
username: user.username, | ||
id: user._id, | ||
} | ||
|
||
const token = jwt.sign(userForToken, process.env.SECRET) | ||
|
||
response.status(200).send({ token, username: user.username, name: user.name }) | ||
}) | ||
|
||
module.exports = loginRouter |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
POST http://localhost:3003/api/login | ||
Content-Type: application/json | ||
|
||
{ | ||
"username": "root", | ||
"password": "test" | ||
} |