Alejandro Peña
Alejandro Peña

Reputation: 131

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?

Upvotes: 3

Views: 2709

Answers (1)

hanego
hanego

Reputation: 1635

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.

Upvotes: 4

Related Questions