Skip to content

Commit

Permalink
changed auth error to 403
Browse files Browse the repository at this point in the history
  • Loading branch information
chiefkarim committed Sep 11, 2023
1 parent 640f355 commit 3213c40
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 1 deletion.
26 changes: 26 additions & 0 deletions controllers/log-inController.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,29 @@ exports.logIn_post = [
}
}),
]

//API handling log in request POST
exports.logIn_post_api = [
body('username','please enter a username')
.trim()
.isLength({min:1})
.escape(),
body('password','please enter a password')
.trim()
.isLength({min:1})
.escape(),asyncHandler(async(req,res,next)=>{
const errors=validationResult(req)
if(!errors.isEmpty()){
console.error(`Validation error ${JSON.stringify(errors)}`)
res.send({title:'Log in',errors:errors.array()})
}else{

passport.authenticate('local', function(err, user, info, status) {
if (err) { return next(err) }
if (!user) { return res.render('log-in',{title:'Log in',errors:[info]}) }
const accessToken = jwt.sign({username:req.body.username}, process.env.ACCESS_TOKEN_SECRET)
res.send({accessToken:accessToken});
})(req, res, next)
}
}),
]
42 changes: 42 additions & 0 deletions controllers/sign-upController.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,46 @@ exports.signUp_post = [

}

})]

exports.signUp_post_api = [
body('username','please enter a username between 3 and 15 characters')
.trim()
.isLength({min:3, max: 15})
.escape(),
body('password','please enter a password of 5 and 15 characters')
.trim()
.isLength({min:5,max:15})
.escape()
,asyncHandler(async(req,res,next)=>{

const errors = validationResult(req)
//checking if user already exists
const userExist = await userModel.findOne({username:req.body.username})
if(userExist){
console.log('already exists')
errors.errors.push({path:'username',msg:'username already exists'})
}
if(!errors.isEmpty()){
res.send({errors:errors.array(),title:"sing up"})
return
}else{
bcrypt.hash(req.body.password,10,async(err,hashedPassword)=>{
try{
console.log(`the name is ${req.body.username}`)
console.log(`the password is ${req.body.password}`)
const user = new userModel({
username:req.body.username,
password:hashedPassword
})
result = await user.save()
const accessToken = jwt.sign({username:req.body.username}, process.env.ACCESS_TOKEN_SECRET)
res.send({accessToken:accessToken});
}catch(err){
return next(err)
}
})

}

})]
2 changes: 1 addition & 1 deletion helpers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ module.exports=function authenticate(req, res, next) {
next();
});
} else {
res.sendStatus(400);
res.sendStatus(403);
}
}

0 comments on commit 3213c40

Please sign in to comment.