I have a service method which does the following:
- Finds the user from the Database by their ID
- Checks if a user has been found
- Uses bcrypt to compare the password stored in the DB against a password provided as a parameter
- Throws an UnauthorizedException if the password was incorrect, returns the user if correct.
I'm just trying to find out if there's a better way of using RxJS operators to do this because I don't like having to pipe from the bcrypt.compare:
public validateUser(email: string, pass: string): Promise<UserDto> {
return this.userService
.findOne({ email })
.pipe(
map((user: UserDto) => {
if (!user || !user.password) {
return throwError(new UnauthorizedException());
}
return user;
}),
switchMap((user: UserDto) => {
return from(
bcrypt.compare(pass, user.password) as Promise<boolean>
).pipe(
map((passwordIsCorrect) => ({
passwordIsCorrect,
user
}))
);
}),
switchMap((res) => {
if (!res.passwordIsCorrect) {
return throwError(new UnauthorizedException());
}
return of(res.user);
})
)
.toPromise();
}