环回4:@repository依赖项注入失败(TypeError:无法读取未定义的属性'findOne')

山姆·马来耶克

我正在我的Loopback 4应用程序上设置Bearer Token身份验证,并且遵循以下常规实现:https : //github.com/strongloop/loopback-next/tree/master/packages/authentication

在我的中src/providers/auth-strategy.provider.ts,我需要引用存储库对象才能查询我的数据源。我希望通过在@repository我正在使用的类的构造函数中使用装饰器进行依赖项注入来实现此目标

但是,当我调用findOne()@repository装饰器创建的存储库引用时,会产生以下错误:

TypeError: Cannot read property 'findOne' of undefined

这是我的版本auth-strategy.provider.ts

import {Provider, inject, ValueOrPromise} from '@loopback/context';
import {Strategy} from 'passport';
import {
  AuthenticationBindings,
  AuthenticationMetadata,
} from '@loopback/authentication';
import {IVerifyOptions} from 'passport-http-bearer';
import {ApiClient} from '../models';
import {ApiClientRepository} from '../repositories';
import {Strategy as BearerStrategy} from 'passport-http-bearer';
import {repository} from '@loopback/repository';

export class BearerStrategyProvider implements Provider<Strategy | undefined> {
  constructor(
    @inject(AuthenticationBindings.METADATA)
    private metadata: AuthenticationMetadata,
    @repository(ApiClientRepository)
    private apiClientRepository: ApiClientRepository,
  ) {}

  value(): ValueOrPromise<Strategy | undefined> {
    // The function was not decorated, so we shouldn't attempt authentication
    if (!this.metadata) {
      return undefined;
    }

    const name = this.metadata.strategy;
    if (name === 'BearerStrategy') {
      return new BearerStrategy(this.verify);
    } else {
      return Promise.reject(`The strategy ${name} is not available.`);
    }
  }

  async verify(
    token: string,
    done: (error: any, user?: any, options?: IVerifyOptions | string) => void,
  ) {
    // call cb(null, false) when user not found
    // call cb(null, user) when user is authenticated
    let apiClient: ApiClient | null;
    try {
      apiClient = await this.apiClientRepository.findOne({
        where: {Token: token},
      });
      if (apiClient) {
        console.log("Found CLIENT!!! Here: " + apiClient.Email);
        done(null, {user: apiClient});
      } else {
        // if token not found in DB:
        done('Authentication Error.', false);
      }
    } catch (e) {
      console.log(e);
    }
  }
}
羽子

实际上,我认为在您的情况下,问题与此相同:https : //github.com/strongloop/loopback-next/issues/1835

你应该绑定您的验证功能,你的类的情况下,否则thisBearerStrategyProvider但是BearerStrategy,再this.apiClientRepository没有在该类存在。您可以这样绑定它:

return new BearerStrategy(this.verify.bind(this));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章