I'm struggling to implement a logic where I need to compare the user's password to a given password and handle different scenarios based on the comparison result. Here's what I need to achieve:
- If the user doesn't exist, return
undefined
(HTTP 404) - If the password is incorrect, throw a
ForbiddenError
(HTTP 403) - If the user exists and the password matches, return the
user
(HTTP 200)
My first attempt at implementing this logic is messy and hard to read:
@Post()
login(
@BodyParam('username', { required: true }) username: string,
@BodyParam('password', { required: true }) plainPassword: string,
) {
return this.userRepository.findOne({ username: username, enable: true })
.then ((user: User | undefined) => {
if (!user) {
return undefined; // 404
}
return bcrypt.compare(plainPassword, user.password)
.then(passwordMatch => {
if (!passwordMatch) {
throw new ForbiddenError('Authentication failed.'); // 403
}
return user; // 200
});
});
}
In my second attempt, the implementation is not working as expected and always returns 'ok'
:
return this.userRepository.findOne({ username: username, enable: true })
.then((user: User | undefined) => {
if (!user) {
return undefined; // 404
}
return bcrypt.compare(password, user.password);
})
.then(passwordMatch => {
// This code block is always executed, even when the user is undefined.
return 'ok';
});