Skip to content

Commit

Permalink
TST - convergeance and reset password
Browse files Browse the repository at this point in the history
  • Loading branch information
juliecoust committed Jan 29, 2024
1 parent 61350f0 commit ab728a1
Show file tree
Hide file tree
Showing 7 changed files with 47 additions and 31 deletions.
2 changes: 1 addition & 1 deletion src/domain/use-cases/auth/reset-password.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class ResetPassword implements ResetPasswordUseCase {
}
)
// if the user does not exist or the reset_password_code is not valid
if (!preexistant_user) throw new Error("User does not exist or token is not valid");
if (!preexistant_user) throw new Error("User does not exist or reset_password_code is not valid");

// is the user validated ?
if (!preexistant_user.valid_email) throw new Error("User email is not validated");
Expand Down
1 change: 1 addition & 0 deletions src/presentation/interfaces/middleware/auth-validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export interface IMiddlewareAuthValidation {
rulesPassword: (ValidationChain | ((req: Request, res: Response, next: NextFunction) => Response | undefined))[]
rulesAuthUserCredentialsModel: (ValidationChain | ((req: Request, res: Response, next: NextFunction) => Response | undefined))[]
rulesRequestResetPassword: (ValidationChain | ((req: Request, res: Response, next: NextFunction) => Response | undefined))[]
rulesResetPassword: (ValidationChain | ((req: Request, res: Response, next: NextFunction) => Response | undefined))[]
}


19 changes: 19 additions & 0 deletions src/presentation/middleware/auth-validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,4 +90,23 @@ export class MiddlewareAuthValidation implements IMiddlewareAuthValidation {
},
];

rulesResetPassword = [
// New password Validation
check('new_password')
.isLength({ min: 8 }).withMessage('Password must be at least 8 characters long.')
.matches(/\d/).withMessage('Password must contain a number.')
.matches(/[a-z]/).withMessage('Password must contain a lowercase letter.')
.matches(/[A-Z]/).withMessage('Password must contain an uppercase letter.')
.matches(/[@!#$%^&*()_+.,;:]/).withMessage('Password must contain a special character.')
.bail(),
// Error Handling Middleware
(req: Request, res: Response, next: NextFunction) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
// Centralized error handling for validation errors
return res.status(422).json({ errors: errors.array() });
}
next();
},
];
}
8 changes: 4 additions & 4 deletions src/presentation/routers/auth-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export default function AuthRouter(
})

// reset password confirm
router.put('/password/reset', async (req: Request, res: Response) => {
router.put('/password/reset', middlewareAuthValidation.rulesResetPassword, async (req: Request, res: Response) => {
try {
await resetPasswordUseCase.execute(req.body)
res
Expand All @@ -128,9 +128,9 @@ export default function AuthRouter(
} catch (err) {
console.log(err)
if (err.message === "Token is not valid") res.status(401).send({ errors: ["Can't reset password"] })
if (err.message === "No token provided") res.status(401).send({ errors: ["Can't reset password"] })
if (err.message === "User does not exist or token is not valid") res.status(404).send({ errors: ["Can't reset password"] })
if (err.message === "User email is not validated") res.status(403).send({ errors: ["Can't reset password"] })
else if (err.message === "No token provided") res.status(401).send({ errors: ["Can't reset password"] })
else if (err.message === "User does not exist or reset_password_code is not valid") res.status(404).send({ errors: ["Can't reset password"] })
else if (err.message === "User email is not validated") res.status(403).send({ errors: ["Can't reset password"] })
else res.status(500).send({ errors: ["Can't reset password"] })
}
})
Expand Down
43 changes: 19 additions & 24 deletions test/data/data-sources/sqlite/sqlite-user-data-source.test.todo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,31 +53,26 @@ describe("PG DataSource", () => {
expect(result).toStrictEqual([OutputData])
})

// TODO
test("create", async () => {
const InputData: UserRequesCreationtModel = {
last_name: "Smith",
first_name: "John",
email: "[email protected]",
password: "test123!",
organisation: "LOV",
country: "France",
user_planned_usage: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
}

const ds = new SQLiteUserDataSource(mockDatabase);
const inputData: UserRequesCreationtModel = {
last_name: "Smith",
first_name: "John",
email: "[email protected]",
password: "123test!",
organisation: "LOV",
country: "France",
user_planned_usage: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
}
await ds.create(inputData);
expect(mockDatabase.run).toHaveBeenCalledWith("INSERT INTO user (name) VALUES ($1)", ["Smith"])
})
describe('create method', () => {
test('should insert a user into the database', async () => {
const ds = new SQLiteUserDataSource(mockDatabase);
const inputData: UserRequesCreationtModel = {
last_name: "Smith",
first_name: "John",
email: "[email protected]",
password: "123test!",
organisation: "LOV",
country: "France",
user_planned_usage: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
}
await ds.create(inputData);
expect(mockDatabase.run).toHaveBeenCalledWith("INSERT INTO user (name) VALUES ($1)", ["Smith"])
});


});


// test("deleteOne", async () => {
// const ds = new SQLiteUserDataSource(mockDatabase);
Expand Down
2 changes: 1 addition & 1 deletion test/domain/use-cases/auth/reset-password.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ describe("Change password Use Case", () => {
await reset_password.execute(InputData);
}
catch (error) {
expect(error.message).toBe("User does not exist or token is not valid");
expect(error.message).toBe("User does not exist or reset_password_code is not valid");
}

expect(mockUserRepository.verifyResetPasswordToken).toHaveBeenCalledWith(InputData.reset_password_token);
Expand Down
3 changes: 2 additions & 1 deletion test/presentation/routes/auth-router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ class MockRefreshTokenUseCase implements RefreshTokenUseCase {
}
}
class MockMiddlewareAuthValidation implements IMiddlewareAuthValidation {
rulesResetPassword = [];
rulesRequestResetPassword = [];
rulesPassword = []
rulesAuthUserCredentialsModel = [];
Expand Down Expand Up @@ -488,7 +489,7 @@ describe("User Router", () => {
new_password: "test123!!!!!!!",
reset_password_token: "reset_password_token",
}
const error_message = "User does not exist or token is not valid"
const error_message = "User does not exist or reset_password_code is not valid"
const expectedResponse = { errors: ["Can't reset password"] }

jest.spyOn(mockResetPasswordUseCase, "execute").mockImplementation(() => Promise.reject(new Error(error_message)))
Expand Down

0 comments on commit ab728a1

Please sign in to comment.