Skip to content

Commit

Permalink
solution 4.22*: bloglist expansion, step10. Add middleware to access …
Browse files Browse the repository at this point in the history
…to username as request.user
  • Loading branch information
patchamama committed Sep 11, 2023
1 parent e3a78c9 commit fdcd8fa
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 8 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](https://github.com/patchamama/fullstackopen-part4-bloglist/commit/530d7c2eab9c8ce3bbfd2220e904290e28f9b262) | [4.19](https://github.com/patchamama/fullstackopen-part4-bloglist/commit/41f1994a2a145dc97b01e4477efb8b689d626c47) | [4.20](https://github.com/patchamama/fullstackopen-part4-bloglist/commit/b2327ebc80681aa98b7e7c0826345872a6fdb647) | [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](https://github.com/patchamama/fullstackopen-part4-bloglist/commit/41f1994a2a145dc97b01e4477efb8b689d626c47) | [4.20](https://github.com/patchamama/fullstackopen-part4-bloglist/commit/b2327ebc80681aa98b7e7c0826345872a6fdb647) | [4.21](https://github.com/patchamama/fullstackopen-part4-bloglist/commit/e3a78c91dcde8dc6c82df469c1f0e83494a81c4c) | [4.22]() | [4.23]()_

# Deploy
3 changes: 2 additions & 1 deletion app.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,11 @@ app.use(express.static('build'))
app.use(express.json())
app.use(middleware.requestLogger)
app.use(middleware.tokenExtractor)
// app.use(middleware.userExtractor)

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

app.use(middleware.unknownEndpoint)
app.use(middleware.errorHandler)
Expand Down
8 changes: 7 additions & 1 deletion controllers/blogs.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,17 @@ blogsRouter.get('/:id', async (request, response) => {
})

blogsRouter.delete('/:id', async (request, response) => {
// get user from request object
// const username = request.user

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

// Check if the user is the creator of the blog
const blog = await Blog.findById(request.params.id)
Expand All @@ -57,6 +61,8 @@ blogsRouter.delete('/:id', async (request, response) => {

blogsRouter.post('/', async (request, response) => {
const body = request.body
// get user from request object
// const username = request.user

// Authentication is required
// const token = getTokenFrom(request)
Expand All @@ -65,13 +71,13 @@ blogsRouter.post('/', async (request, response) => {
if (!request.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(decodedToken.id)
body.user = user._id
const blog = new Blog(body)
const savedBlog = await blog.save()
Expand Down
5 changes: 4 additions & 1 deletion requests/add_new_user.rest
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,7 @@ Content-Type: application/json
}

###
GET http://localhost:3003/api/users/
GET http://localhost:3003/api/users/

###
DELETE http://localhost:3003/api/users/64fe4d59361a6244c230714b
2 changes: 1 addition & 1 deletion requests/delete_note.rest
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
DELETE http://localhost:3003/api/blogs/64fdd3005e8ccd4fa2a5ac24
DELETE http://localhost:3003/api/blogs/64fed629bf85c117393837e8

###

Expand Down
14 changes: 11 additions & 3 deletions requests/login.rest
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,18 @@ Content-Type: application/json
"password": "test"
}

###
GET http://localhost:3003/api/blogs
Authorization: bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InJvb3QiLCJpZCI6IjY0ZmVkMjkyM2EyMDYzZGIyYzAzYmJjNyIsImlhdCI6MTY5NDQyODYzNiwiZXhwIjoxNjk0NDMyMjM2fQ.Z5GHfVEJgYwC_TVS6eBmWYrG6j5etoNpqg4TUkpEfRU

###
GET http://localhost:3003/api/blogs


###
POST http://localhost:3003/api/blogs
Content-Type: application/json
Authorization: bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InJvb3QiLCJpZCI6IjY0ZmVkMjkyM2EyMDYzZGIyYzAzYmJjNyIsImlhdCI6MTY5NDQyNzU1NywiZXhwIjoxNjk0NDMxMTU3fQ.9eLl25wQMCqNQe6nO5iwzl55acVECBxuClcX4pYkvDs
Authorization: bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InJvb3QiLCJpZCI6IjY0ZmVkMjkyM2EyMDYzZGIyYzAzYmJjNyIsImlhdCI6MTY5NDQyODYzNiwiZXhwIjoxNjk0NDMyMjM2fQ.Z5GHfVEJgYwC_TVS6eBmWYrG6j5etoNpqg4TUkpEfRU

{
"title": "Fugas o la ansiedad de sentirse vivo",
Expand All @@ -20,5 +28,5 @@ Authorization: bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InJvb
}

###
DELETE http://localhost:3003/api/blogs/64fed470740222927b47569f
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InJvb3QiLCJpZCI6IjY0ZmVkMjkyM2EyMDYzZGIyYzAzYmJjNyIsImlhdCI6MTY5NDQyNzU1NywiZXhwIjoxNjk0NDMxMTU3fQ.9eLl25wQMCqNQe6nO5iwzl55acVECBxuClcX4pYkvDs
DELETE http://localhost:3003/api/blogs/64feedea0f268b96ab900f3e
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InJvb3QiLCJpZCI6IjY0ZmVkMjkyM2EyMDYzZGIyYzAzYmJjNyIsImlhdCI6MTY5NDQyODYzNiwiZXhwIjoxNjk0NDMyMjM2fQ.Z5GHfVEJgYwC_TVS6eBmWYrG6j5etoNpqg4TUkpEfRU
18 changes: 18 additions & 0 deletions utils/middleware.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const logger = require('./logger')
const jwt = require('jsonwebtoken')

const tokenExtractor = (request, response, next) => {
const authorization = request.get('authorization')
Expand All @@ -12,6 +13,22 @@ const tokenExtractor = (request, response, next) => {
next()
}

const userExtractor = (request, response, next) => {
const authorization = request.get('authorization')
// console.log('authorization:', authorization)
if (authorization && authorization.toLowerCase().startsWith('bearer ')) {
const decodedToken = jwt.verify(
authorization.substring(7),
process.env.SECRET
)
request.user = decodedToken.username
} else {
request.user = null
}
console.log('request.user:', request.user)
next()
}

const requestLogger = (request, response, next) => {
logger.info('Method:', request.method)
logger.info('Path: ', request.path)
Expand Down Expand Up @@ -47,4 +64,5 @@ module.exports = {
unknownEndpoint,
errorHandler,
tokenExtractor,
userExtractor,
}

0 comments on commit fdcd8fa

Please sign in to comment.