Skip to content

Commit

Permalink
fix(validation):joi validation for login
Browse files Browse the repository at this point in the history
-login data from request.body are validated by joi

[Fixes #187419169]
  • Loading branch information
niyobertin committed Apr 23, 2024
1 parent b9bd13e commit 304e8e1
Show file tree
Hide file tree
Showing 6 changed files with 43 additions and 8 deletions.
2 changes: 1 addition & 1 deletion __test__/user.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ test('should return 500 when registering with an invalid credential', async () =
test("Should return status 401 to indicate Unauthorized user",async() =>{
const loggedInUser ={
email:userData.email,
password:"test",
password:"test12345",
};
const spyonOne = jest.spyOn(User,"findOne").mockResolvedValueOnce({
//@ts-ignore
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@
"cross-env": "^7.0.3",
"cryptr": "^6.3.0",
"dotenv": "^16.4.5",
"email-validator": "^2.0.4",
"express": "^4.19.2",
"joi": "^17.12.3",
"jsonwebtoken": "^9.0.2",
"path": "^0.12.7",
"pg": "^8.11.5",
Expand Down
9 changes: 5 additions & 4 deletions src/controllers/userControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,17 @@ export const userLogin = async(req:Request,res:Response) =>{
const user = await loggedInUser(email);
const accessToken = await generateToken(user);
if(!user){
res.status(404).json({
status:404,
message:'User Not Found ! Please Register new ancount'

res.status(401).json({
status:401,
message:'Invalid credentials'
});
}else{
const match = await comparePasswords(password,user.password);
if(!match){
res.status(401).json({
status:401,
message:' User email or password is incorrect!'
message:' Invalid credentials'
});
}else{
res.status(200).json({
Expand Down
21 changes: 21 additions & 0 deletions src/helpers/validation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Request,Response,NextFunction } from "express";
export const dataValidation = async(req:Request,res:Response,next:NextFunction,data:any) => {
const {error} = data.validate(req.body);
if(error){
return res.status(406)
.json({
status:406,
mesage:`Error in User Data : ${error.message}`
})
}
const allowedFields = Object.keys(data.describe().keys);
const unknownFields = Object.keys(req.body).filter(field => !allowedFields.includes(field));
if (unknownFields.length > 0) {
return res.status(406).json({
status: 406,
message: `Unknown fields: ${unknownFields.join(", ")}`
});
}else{
next();
}
}
11 changes: 11 additions & 0 deletions src/middlewares/joiValidation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import Joi from "joi";
import { Request,Response,NextFunction } from "express";
import { dataValidation } from "../helpers/validation";
const loginValidation:any = Joi.object({
email:Joi.string().email().trim(true).required(),
password:Joi.string().min(8).trim(true).required(),
}).options({ abortEarly: false });

export const loginDataValidation = async(req:Request,res:Response,next:NextFunction) =>{
await dataValidation(req,res,next,loginValidation);
};
6 changes: 3 additions & 3 deletions src/routes/userRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import {
createUserController,
userLogin }
from "../controllers/userControllers";

import { loginDataValidation } from "../middlewares/joiValidation";
const userRoutes = Router();

userRoutes.get("/", fetchAllUsers);
userRoutes.post('/login',userLogin);
userRoutes.post("/register", createUserController)
userRoutes.post('/login',loginDataValidation,userLogin);
userRoutes.post("/register", createUserController);


export default userRoutes;

0 comments on commit 304e8e1

Please sign in to comment.