Skip to content

Commit

Permalink
TST - Change password
Browse files Browse the repository at this point in the history
  • Loading branch information
juliecoust committed Dec 4, 2023
1 parent 99afd41 commit 4152ffa
Show file tree
Hide file tree
Showing 8 changed files with 650 additions and 11 deletions.
8 changes: 4 additions & 4 deletions src/domain/use-cases/auth/changePassword.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,19 @@ export class ChangePassword implements ChangePasswordUseCase {
async execute(current_user: DecodedToken, credentials: ChangeCredentialsModel): Promise<void> {
let nb_of_updated_user: number = 0

// Check if new password is different from old password
if (credentials.password === credentials.new_password) throw new Error("New password must be different from old password");

// admin can update anyone password without old password
if (await this.userRepository.isAdmin(current_user.user_id)) {
nb_of_updated_user = await this.userRepository.changePassword(credentials)
if (nb_of_updated_user == 0) throw new Error("Can't update user");
if (nb_of_updated_user == 0) throw new Error("Can't change password");
} else if (current_user.user_id == credentials.user_id) {
// Check if new password is different from old password
if (credentials.password === credentials.new_password) throw new Error("New password must be different from old password");
// Check if old password is correct
const verifyed = await this.userRepository.verifyUserLogin({ email: current_user.email, password: credentials.password })
if (verifyed) {
nb_of_updated_user = await this.userRepository.changePassword(credentials)
if (nb_of_updated_user == 0) throw new Error("Can't update user");
if (nb_of_updated_user == 0) throw new Error("Can't change password");
} else {
throw new Error("Invalid credentials");
}
Expand Down
6 changes: 3 additions & 3 deletions src/presentation/middleware/auth_validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export class MiddlewareAuthValidation implements IMiddlewareAuthValidation {
.matches(/[a-z]/)
.matches(/[A-Z]/)
.matches(/[@!#$%^&*()_+.,;:]/)
.bail(),
.withMessage('Invalid credentials'),

// New password Validation
check('new_password')
Expand All @@ -26,7 +26,7 @@ export class MiddlewareAuthValidation implements IMiddlewareAuthValidation {
.matches(/[a-z]/)
.matches(/[A-Z]/)
.matches(/[@!#$%^&*()_+.,;:]/)
.bail(),
.withMessage('New password must be at least 8 characters long, contain at least a number, a lowercase letter, an uppercase letter and a special character.'),

//check that password_hash is not defined
check('password_hash')
Expand All @@ -37,7 +37,7 @@ export class MiddlewareAuthValidation implements IMiddlewareAuthValidation {
const errors = validationResult(req);
if (!errors.isEmpty()) {
// Centralized error handling for validation errors
return res.status(401).json({ errors: ["Invalid credentials"] });
return res.status(422).json({ errors: ["Invalid credentials or missing user id"] });
}
next();
},
Expand Down
2 changes: 1 addition & 1 deletion src/presentation/routers/auth-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export default function AuthRouter(
.json({ response: "Password sucessfully changed" });
} catch (err) {
console.log(err)
if (err.message === "New password must be different from old password") res.status(500).send({ errors: ["New password must be different from old password"] })
if (err.message === "New password must be different from old password") res.status(401).send({ errors: ["New password must be different from old password"] })
else res.status(500).send({ errors: ["Can't change password"] })
}
})
Expand Down
39 changes: 38 additions & 1 deletion test/domain/repositories/user-repository.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//test/domain/repositories/user-repository.test.ts
import { UserDataSource } from "../../../src/data/interfaces/data-sources/user-data-source";
import { AuthUserCredentialsModel, DecodedToken } from "../../../src/domain/entities/auth";
import { AuthUserCredentialsModel, ChangeCredentialsModel, DecodedToken } from "../../../src/domain/entities/auth";
import { UserRequesCreationtModel, UserRequestModel, UserResponseModel, UserUpdateModel } from "../../../src/domain/entities/user";
import { UserRepository } from "../../../src/domain/interfaces/repositories/user-repository";
import { UserRepositoryImpl } from "../../../src/domain/repositories/user-repository";
Expand Down Expand Up @@ -498,4 +498,41 @@ describe("User Repository", () => {
});
});

describe("changePassword", () => {
test("Should return 1 in nominal case", async () => {

const credentials: ChangeCredentialsModel = {
user_id: 1,
password: "current_password",
new_password: "new_password"
}

jest.spyOn(mockBcryptAdapter, "hash").mockImplementation(() => Promise.resolve("$2b$12$mMHjmPmUFsTrYFa3WUEVs.T1vaMz4q55FTfgpB.rNiL4GTt85BRkW"))
jest.spyOn(mockUserDataSource, "updateOne").mockImplementation(() => Promise.resolve(1))
const result = await userRepository.changePassword(credentials);

expect(mockBcryptAdapter.hash).toHaveBeenCalledWith("new_password")
expect(mockUserDataSource.updateOne).toHaveBeenCalledWith({ user_id: 1, password_hash: "$2b$12$mMHjmPmUFsTrYFa3WUEVs.T1vaMz4q55FTfgpB.rNiL4GTt85BRkW" })
expect(result).toBe(1)

});

test("Should return 0 if no user updated", async () => {
const credentials: ChangeCredentialsModel = {
user_id: 1,
password: "current_password",
new_password: "new_password"
}

jest.spyOn(mockBcryptAdapter, "hash").mockImplementation(() => Promise.resolve("$2b$12$mMHjmPmUFsTrYFa3WUEVs.T1vaMz4q55FTfgpB.rNiL4GTt85BRkW"))
jest.spyOn(mockUserDataSource, "updateOne").mockImplementation(() => Promise.resolve(0))
const result = await userRepository.changePassword(credentials);

expect(mockBcryptAdapter.hash).toHaveBeenCalledWith("new_password")
expect(mockUserDataSource.updateOne).toHaveBeenCalledWith({ user_id: 1, password_hash: "$2b$12$mMHjmPmUFsTrYFa3WUEVs.T1vaMz4q55FTfgpB.rNiL4GTt85BRkW" })
expect(result).toBe(0)

});
});

})
Loading

0 comments on commit 4152ffa

Please sign in to comment.