Skip to content

Commit

Permalink
solution 4.18: bloglist expansion, step6. Add token-based auth.
Browse files Browse the repository at this point in the history
  • Loading branch information
patchamama committed Sep 11, 2023
1 parent 9e5dee6 commit 530d7c2
Show file tree
Hide file tree
Showing 5 changed files with 137 additions and 2 deletions.
6 changes: 4 additions & 2 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ const config = require('./utils/config')
const express = require('express')
const app = express()
const cors = require('cors')
const BlogsRouter = require('./controllers/blogs')
const loginRouter = require('./controllers/login')
const usersRouter = require('./controllers/users')
const BlogsRouter = require('./controllers/blogs')
const middleware = require('./utils/middleware')
const logger = require('./utils/logger')
const mongoose = require('mongoose')
Expand All @@ -26,8 +27,9 @@ app.use(express.static('build'))
app.use(express.json())
app.use(middleware.requestLogger)

app.use('/api/blogs', BlogsRouter)
app.use('/api/login', loginRouter)
app.use('/api/users', usersRouter)
app.use('/api/blogs', BlogsRouter)

app.use(middleware.unknownEndpoint)
app.use(middleware.errorHandler)
Expand Down
31 changes: 31 additions & 0 deletions controllers/login.js
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
94 changes: 94 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"dotenv": "16.3.1",
"express": "4.18.2",
"express-async-errors": "3.1.1",
"jsonwebtoken": "^9.0.2",
"lodash": "4.17.21",
"mongoose": "7.5.0",
"mongoose-unique-validator": "^4.0.0"
Expand Down
7 changes: 7 additions & 0 deletions requests/login.rest
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"
}

0 comments on commit 530d7c2

Please sign in to comment.