Skip to content
This repository has been archived by the owner on Mar 31, 2024. It is now read-only.

Commit

Permalink
!refactor: pass user object from database on JWT auth
Browse files Browse the repository at this point in the history
  • Loading branch information
Dwigoric committed Aug 6, 2023
1 parent cb39cde commit 8df9f85
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 42 deletions.
3 changes: 2 additions & 1 deletion src/auth/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,8 @@ passport.use(

if (!user) return done(null, false, { message: 'User not found' })

return done(null, token.id)
delete user._id
return done(null, user)
} catch (error) {
return done(error)
}
Expand Down
38 changes: 19 additions & 19 deletions src/routes/comments.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ router.put('/:postId', async (req, res) => {
passport.authenticate('jwt', { session: false }, async (err, user, info) => {
if (err) return res.status(500).json({ error: true, message: 'Internal server error' })
if (info) return res.status(401).json({ error: true, message: info.message })
delete user.password

const { body, postId, parentCommentId } = req.body

Expand Down Expand Up @@ -40,27 +41,24 @@ router.put('/:postId', async (req, res) => {

const generatedId = uuidV5(Date.now().toString(), uuidV5.URL)

const newComment = {
body,
user: user.id,
postId,
deleted: false,
parentCommentId: parentCommentId || null,
date: Date.now()
}

try {
await mongo.create('comments', generatedId, {
body,
user,
postId,
deleted: false,
parentCommentId: parentCommentId || null,
date: Date.now()
})
await mongo.create('comments', generatedId, newComment)
} catch (err) {
return res.status(500).json({ error: true, message: err.message })
}

const comment = await mongo.get('comments', generatedId)
delete comment._id
newComment.user = user

comment.user = await mongo.get('users', comment.user)
delete comment.user._id
delete comment.user.password

return res.status(201).json({ comment, message: 'Comment created' })
return res.status(201).json({ comment: newComment, message: 'Comment created' })
})(req, res)
})

Expand Down Expand Up @@ -119,9 +117,10 @@ router.get('/:postId', async (req, res) => {
})

router.patch('/:id', async (req, res) => {
passport.authenticate('jwt', { session: false }, async (err, userId, info) => {
passport.authenticate('jwt', { session: false }, async (err, user, info) => {
if (err) return res.status(500).json({ error: true, message: 'Internal server error' })
if (info) return res.status(401).json({ error: true, message: info.message })
delete user.password

const { id } = req.params

Expand All @@ -137,7 +136,7 @@ router.patch('/:id', async (req, res) => {
if (!comment) return res.status(404).json({ error: true, message: 'Comment not found' })

// Check if user is trying to update their own comment
if (userId !== comment.user)
if (user.id !== comment.user)
return res.status(403).json({ error: true, message: 'Forbidden' })

const updatedComment = {
Expand All @@ -158,17 +157,18 @@ router.patch('/:id', async (req, res) => {
})

router.delete('/:id', async (req, res) => {
passport.authenticate('jwt', { session: false }, async (err, userId, info) => {
passport.authenticate('jwt', { session: false }, async (err, user, info) => {
if (err) return res.status(500).json({ error: true, message: 'Internal server error' })
if (info) return res.status(401).json({ error: true, message: info.message })
delete user.password

const { id } = req.params

const comment = await mongo.get('comments', id)
if (!comment) return res.status(404).json({ error: true, message: 'Comment not found' })

// Check if user is trying to delete their own comment
if (userId !== comment.user)
if (user.id !== comment.user)
return res.status(403).json({ error: true, message: 'Forbidden' })

try {
Expand Down
21 changes: 11 additions & 10 deletions src/routes/posts.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ const storage = multer.diskStorage({
const upload = multer({ storage })

router.put('/', upload.single('image'), async (req, res) => {
passport.authenticate('jwt', { session: false }, async (err, userId, info) => {
passport.authenticate('jwt', { session: false }, async (err, user, info) => {
if (err) return res.status(500).json({ error: true, message: 'Internal server error' })
if (info) return res.status(401).json({ error: true, message: info.message })
delete user.password

// Get fields
const { title, body } = req.body
Expand Down Expand Up @@ -51,10 +52,6 @@ router.put('/', upload.single('image'), async (req, res) => {
await mongo.db.createIndex('posts', { date: -1 }, { name: 'Date descending' })
}

const user = await mongo.get('users', userId)
delete user._id
delete user.password

// Generate UUID v5 for post ID
const generatedId = uuidV5(Date.now().toString(), uuidV5.URL)

Expand All @@ -65,7 +62,7 @@ router.put('/', upload.single('image'), async (req, res) => {
// Create post
try {
await mongo.create('posts', generatedId, {
user: userId,
user: user.id,
title,
body,
image: imagePath,
Expand Down Expand Up @@ -187,9 +184,10 @@ router.get('/:id', async (req, res) => {
})

router.patch('/:id', async (req, res) => {
passport.authenticate('jwt', { session: false }, async (err, userId, info) => {
passport.authenticate('jwt', { session: false }, async (err, user, info) => {
if (err) return res.status(500).json({ error: true, message: 'Internal server error' })
if (info) return res.status(401).json({ error: true, message: info.message })
delete user.password

const { id } = req.params

Expand All @@ -199,7 +197,8 @@ router.patch('/:id', async (req, res) => {
if (!post) return res.status(404).json({ error: true, message: 'Post not found' })

// Check if user is trying to update their own post
if (userId !== post.user) return res.status(403).json({ error: true, message: 'Forbidden' })
if (user.id !== post.user)
return res.status(403).json({ error: true, message: 'Forbidden' })

if (title && title.length > 100)
return res
Expand All @@ -223,17 +222,19 @@ router.patch('/:id', async (req, res) => {
})

router.delete('/:id', async (req, res) => {
passport.authenticate('jwt', { session: false }, async (err, userId, info) => {
passport.authenticate('jwt', { session: false }, async (err, user, info) => {
if (err) return res.status(500).json({ error: true, message: 'Internal server error' })
if (info) return res.status(401).json({ error: true, message: info.message })
delete user.password

const { id } = req.params

const post = await mongo.get('posts', id)
if (!post) return res.status(404).json({ error: true, message: 'Post not found' })

// Check if user is trying to delete their own post
if (userId !== post.user) return res.status(403).json({ error: true, message: 'Forbidden' })
if (user.id !== post.user)
return res.status(403).json({ error: true, message: 'Forbidden' })

try {
await mongo.update('posts', id, {
Expand Down
14 changes: 5 additions & 9 deletions src/routes/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,14 @@ router.get('/username/:username', async (req, res) => {
})

router.patch('/:id', upload.single('avatar'), async (req, res) => {
passport.authenticate('jwt', { session: false }, async (err, id, info) => {
passport.authenticate('jwt', { session: false }, async (err, user, info) => {
if (err) return res.status(500).json({ error: true, message: 'Internal server error' })
if (info) return res.status(401).json({ error: true, message: info.message })

const { id: userId } = req.params

// Check if user is trying to update their own profile
if (userId !== id) return res.status(403).json({ error: true, message: 'Forbidden' })
if (userId !== user.id) return res.status(403).json({ error: true, message: 'Forbidden' })

const { username, description, currentPassword, newPassword } = req.body
const regEx = /^[0-9A-Za-z]{1,20}$/
Expand All @@ -61,18 +61,14 @@ router.patch('/:id', upload.single('avatar'), async (req, res) => {
return res.status(400).json({ error: true, message: 'Username is invalid' })
}

if (!(await mongo.has('users', id)))
if (!(await mongo.has('users', user.id)))
return res.status(404).json({ error: true, message: 'User not found' })

// Check duplicate username
const exists = await mongo.findOne('users', { username })
if (exists && exists.id !== id)
if (exists && exists.id !== user.id)
return res.status(400).json({ error: true, message: 'Username already exists' })

// Retrieve user from database
const user = await mongo.get('users', id)
delete user._id

// Store updated user data
const updatedUser = {}

Expand Down Expand Up @@ -104,7 +100,7 @@ router.patch('/:id', upload.single('avatar'), async (req, res) => {
delete user.password

// Update user in database
await mongo.update('users', id, updatedUser)
await mongo.update('users', user.id, updatedUser)
delete updatedUser.password

// Send a JSON response with 200 OK
Expand Down
7 changes: 4 additions & 3 deletions src/routes/votes.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ import passport from 'passport'
const router = express.Router()

router.post('/:id', async (req, res) => {
passport.authenticate('jwt', { session: false }, async (err, userId, info) => {
passport.authenticate('jwt', { session: false }, async (err, user, info) => {
if (err) return res.status(500).json({ error: true, message: 'Internal server error' })
if (info) return res.status(401).json({ error: true, message: info.message })
delete user.password

// Create `votes` collection if it doesn't exist
if (!(await mongo.hasTable('votes'))) {
Expand Down Expand Up @@ -37,11 +38,11 @@ router.post('/:id', async (req, res) => {
await mongo.createTable('votes')
}

const votesIndex = { postId, userId }
const votesIndex = { postId, userId: user.id }

const updatedVote = {
postId,
userId,
userId: user.id,
vote
}

Expand Down

0 comments on commit 8df9f85

Please sign in to comment.