I am trying to implement authorization to my loopback4 project using this tutorial https://github.com/strongloop/loopback-next/blob/master/packages/authentication/README.md Now on the provider part on the file called auth-strategy.provider, on the verify method, I want to verify the username with a mongoDB. I already have a repository and database access on the project. My question is how do I access the database from this part of the code?
You can inject your repository in the constructor of your provider and then compare the password to check if it's ok like this:
import {repository} from '@loopback/repository';
export class MyAuthStrategyProvider implements Provider<Strategy | undefined> {
constructor(
@inject(AuthenticationBindings.METADATA)
private metadata: AuthenticationMetadata,
@repository(UserRepository) protected userRepository: UserRepository,
) {}
[...]
verify(
username: string,
password: string,
cb: (err: Error | null, user?: UserProfile | false) => void,
) {
let user = await this.userRepository.findOne({where: {username: username}});
if(!user || user.password !== password)
return cb(null, false);
cb(null, user);
}
}
This code is just a sample, in general the password should be hashed in the database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With