I am currently experiencing a problem with my login code, where it is supposed to take a username and password, find the corresponding hash in the database, compare them, sign a JWT and return it so that it can be sent back to the user:
async login(username, password): Promise<boolean | void> {
// TODO: Fix typing.
// Types the return as void currently - should return object.
// No return at all either, however console.log prints result - check SO when you have time
const dbPwdHash = await this.userRepository.createQueryBuilder('user')
.select(['user.password', 'user.id'])
.where('user.username = :username', {username})
.getOne();
return compare(password, dbPwdHash.password)
.then(
(res) => {
if (res) {
return sign({ id: dbPwdHash.id }, this.privateKey, { algorithm: 'ES512' }, (err, token) => {
if (err) {
return {err};
} else {
console.log(token);
return {data: token};
}
});
}
},
)
.catch(
(err) => {
console.log(err);
},
);
}
The type definitions type the returns for compare and sign (from bcrypt and jsonwebtoken respectively) are both void by default when using the asynchronous functions with the promise on the compare and the callback on the sign.
The biggest problem I am however experiencing is the fact that in the end nothing gets returned even though a console.log shows that the password is successfully compared and the JWT gets successfully signed.
I am sure it is a problem with the sign function as returning the res from the .then() in the compare works fine, however as soon as I add the sign codeblock, nothing returns. However, I'm not sure what exactly is causing that as well as how I'm supposed to respect the typing rules when compare returns <boolean | void> while sign returns <string | void> afaik.