Skip to content

Commit

Permalink
changes
Browse files Browse the repository at this point in the history
  • Loading branch information
pemba1s1 committed Feb 13, 2024
1 parent 78d3989 commit a5fbb6c
Show file tree
Hide file tree
Showing 5 changed files with 2,627 additions and 1,411 deletions.
7 changes: 7 additions & 0 deletions controllers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const { StatusCodes } = require('http-status-codes')
const signup = async (req,res) => {
const user = await User.create({...req.body}).catch(err=>{
res.status(StatusCodes.BAD_REQUEST).json({msg:"Username or email already taken"})
return
})
const token = user.createJWT()
res.status(201).json({user : { username: user.username, name:user.name},token})
Expand All @@ -13,14 +14,17 @@ const login = async (req,res) => {
const {username,password} = req.body
if(!username || !password){
res.status(StatusCodes.BAD_REQUEST).json({msg:"Bad Request"})
return
}
const user = await User.findOne({username})
if(!user){
res.status(StatusCodes.UNAUTHORIZED).json({msg:"User doesnt exist"})
return
}
const isPasswordCorrect = await user.comparePassword(password)
if(!isPasswordCorrect){
res.status(StatusCodes.UNAUTHORIZED).json({msg:"Password Incorrect"})
return
}
const token = user.createJWT()
res.status(StatusCodes.OK).json({user : { username:user.username , name:user.name,userId:user._id,avatar:user.avatar } , token})
Expand All @@ -31,6 +35,7 @@ const getUser = async (req,res) => {
const user = await User.findOne({username})
if(!user){
res.status(StatusCodes.NOT_FOUND).json({msg:"User doesnt exist"})
return
}
res.status(StatusCodes.OK).json({user : { username:user.username , name:user.name,userId:user._id,email:user.email,avatar:user.avatar }})
}
Expand All @@ -42,9 +47,11 @@ const updateUser = async (req,res) => {
runValidators:true,
}).catch(err=>{
res.status(StatusCodes.BAD_REQUEST).json({msg:"Username or email already taken"})
return
})
if(!user){
return res.status(404).json({msg: `User not found`})
return
}
res.status(200).json({user})
}
Expand Down
2 changes: 2 additions & 0 deletions middleware/authentication.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const {StatusCodes} = require('http-status-codes')
const auth = async (req,res,next) => {
const authHeader = req.headers.authorization
if(!authHeader || !authHeader.startsWith('Bearer')){
console.log('here')
res.status(StatusCodes.UNAUTHORIZED).json({msg:"Authentication invalid"})
}
const token = authHeader.split(' ')[1]
Expand All @@ -13,6 +14,7 @@ const auth = async (req,res,next) => {
req.user = {userId : payload.userId, username : payload.username}
next()
}catch(err){
console.log('there')
res.status(StatusCodes.UNAUTHORIZED).json({msg:"Authentication invalid"})
}
}
Expand Down
Loading

0 comments on commit a5fbb6c

Please sign in to comment.