Skip to content

Commit

Permalink
solution 4.19: bloglist expansion, step7. Add new blogs only with val…
Browse files Browse the repository at this point in the history
…id token
  • Loading branch information
patchamama committed Sep 11, 2023
1 parent 530d7c2 commit 41f1994
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 10 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,6 @@ npm test
## d. Token authentication

- [Exercises 4.15.-4.23.](https://fullstackopen.com/en/part4/token_authentication#exercises-4-15-4-23)
_Solution details: [4.15](https://github.com/patchamama/fullstackopen-part4-bloglist/commit/5ec001cec3b44f41a111681af2ae785289d76b6d) | [4.16](https://github.com/patchamama/fullstackopen-part4-bloglist/commit/7839750f9aa7d52deaa62b6d8a8eafa46dd98ca1) | [4.17](https://github.com/patchamama/fullstackopen-part4-bloglist/commit/fd871d2de79352ff62c26c6aeec438fe43f7167a) | [4.18]() | [4.19]() | [4.20]() | [4.21]() | [4.22]() | [4.23]()_
_Solution details: [4.15](https://github.com/patchamama/fullstackopen-part4-bloglist/commit/5ec001cec3b44f41a111681af2ae785289d76b6d) | [4.16](https://github.com/patchamama/fullstackopen-part4-bloglist/commit/7839750f9aa7d52deaa62b6d8a8eafa46dd98ca1) | [4.17](https://github.com/patchamama/fullstackopen-part4-bloglist/commit/fd871d2de79352ff62c26c6aeec438fe43f7167a) | [4.18](https://github.com/patchamama/fullstackopen-part4-bloglist/commit/530d7c2eab9c8ce3bbfd2220e904290e28f9b262) | [4.19]() | [4.20]() | [4.21]() | [4.22]() | [4.23]()_

# Deploy
29 changes: 21 additions & 8 deletions controllers/blogs.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
const blogsRouter = require('express').Router()
const Blog = require('../models/blog')
const User = require('../models/user')
const jwt = require('jsonwebtoken')
require('express-async-errors')

const getTokenFrom = (request) => {
const authorization = request.get('authorization')
if (authorization && authorization.toLowerCase().startsWith('bearer ')) {
return authorization.substring(7)
}
return null
}

blogsRouter.get('/', async (request, response) => {
const blogs = await Blog.find({}).populate('user', { username: 1, name: 1 })
response.json(blogs)
Expand All @@ -24,22 +33,26 @@ blogsRouter.delete('/:id', async (request, response) => {

blogsRouter.post('/', async (request, response) => {
const body = request.body

// Authentication is required
const token = getTokenFrom(request)
const decodedToken = jwt.verify(token, process.env.SECRET)
if (!token || !decodedToken.id) {
return response.status(401).json({ error: 'token missing or invalid' })
}
const user = await User.findById(decodedToken.id)

body.likes = body.likes || 0

if (!body.title || !body.url) {
response.status(400).end()
} else {
const user = await User.findById(body.userId)

if (body.user) body.user = user._id // to pass the test
body.user = user._id
const blog = new Blog(body)
const savedBlog = await blog.save()

// to pass the test
if (body.user) {
user.blogs = user.blogs.concat(savedBlog._id)
await user.save()
}
user.blogs = user.blogs.concat(savedBlog._id)
await user.save()

response.status(201).json(savedBlog)
}
Expand Down
6 changes: 5 additions & 1 deletion controllers/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ loginRouter.post('/', async (request, response) => {
id: user._id,
}

const token = jwt.sign(userForToken, process.env.SECRET)
// token expires in 60*60 seconds, that is, in one hour
const token = jwt.sign(userForToken, process.env.SECRET, {
expiresIn: 60 * 60,
})
// const token = jwt.sign(userForToken, process.env.SECRET)

response.status(200).send({ token, username: user.username, name: user.name })
})
Expand Down
13 changes: 13 additions & 0 deletions requests/login.rest
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,17 @@ Content-Type: application/json
{
"username": "root",
"password": "test"
}

###
POST http://localhost:3003/api/blogs
Content-Type: application/json
Authorization: bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InJvb3QiLCJpZCI6IjY0ZmVkMjkyM2EyMDYzZGIyYzAzYmJjNyIsImlhdCI6MTY5NDQyNTEwNX0.J1lyBzrEizM3tZTm_Ah2-GJlvk9XK8nPn-c15_UBvCU

{
"title": "Fugas o la ansiedad de sentirse vivo",
"author": "A. Pacheco",
"url": "https://unlibroenmimochila.blogspot.com/2017/12/fugas-o-la-ansiedad-de-sentirse-vivo.html",
"likes": 4,
"userId": "64fed2923a2063db2c03bbc7"
}
6 changes: 6 additions & 0 deletions utils/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ const errorHandler = (error, request, response, next) => {
return response.status(400).send({ error: 'malformatted id' })
} else if (error.name === 'ValidationError') {
return response.status(400).json({ error: error.message })
} else if (error.name === 'JsonWebTokenError') {
return response.status(400).json({ error: error.message })
} else if (error.name === 'TokenExpiredError') {
return response.status(401).json({
error: 'token expired',
})
}

next(error)
Expand Down

0 comments on commit 41f1994

Please sign in to comment.