Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loopback 4 authentication using a db

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?

like image 952
Alejandro Peña Avatar asked Dec 07 '25 18:12

Alejandro Peña


1 Answers

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.

like image 87
hanego Avatar answered Dec 09 '25 15:12

hanego