首页 > 解决方案 > 绑定自定义服务时出现 Loopback 4 身份验证错误

问题描述

我已按照此链接在环回 4 中创建用于身份验证的自定义服务。我成功创建了该服务,但在 application.ts 中绑定此服务时出现以下错误。

“typeof CustomUserService”类型的参数不能分配给“Constructor>”类型的参数。
构造签名返回类型“CustomUserService”和“UserService”不兼容。'verifyCredentials(...)' 返回的类型在这些类型之间不兼容。“Promise”类型不能分配给“Promise”类型。'import("d:/ionic-pr/loopback-projects/custom/src/models/user.model").User' 类型中缺少属性 'userCredentials',但在 'import("d:/ionic- pr/loopback-projects/custom/node_modules/@loopback/authentication-jwt/dist/models/user.model").User'

GIT 存储库- https://github.com/pratikjaiswal15/loopbck4uth

我有两个模型 user 和 userCred 有一个关系。关系名称是userCred

这是代码

先感谢您

应用程序.ts

import {UserCredRepository, UserRepository} from './repositories';
import {CustomUserService} from './services/custom-user.service';
import {UserServiceBindings} from '@loopback/authentication-jwt';

// Bind user service inside constructor
    this.bind(UserServiceBindings.USER_SERVICE).toClass(CustomUserService),// error on this line

      // Bind user and credentials repository
      this.bind(UserServiceBindings.USER_REPOSITORY).toClass(
        UserRepository,
      ),

      this.bind(UserServiceBindings.USER_CREDENTIALS_REPOSITORY).toClass(
        UserCredRepository,
      )

定制服务.ts

import {UserService} from '@loopback/authentication';
import {repository} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
import {securityId, UserProfile} from '@loopback/security';
import {compare} from 'bcryptjs';
// User --> MyUser
import {User} from '../models/user.model';
// UserRepository --> MyUserRepository
import {Credentials, UserRepository} from '../repositories/user.repository';


export class CustomUserService implements UserService<User, Credentials> {
  constructor(
    // UserRepository --> MyUserRepository
    @repository(UserRepository) public userRepository: UserRepository,
  ) {}

  // User --> MyUser
  async verifyCredentials(credentials: Credentials): Promise<User> {
    const invalidCredentialsError = 'Invalid email or password.';

    const foundUser = await this.userRepository.findOne({
      where: {email: credentials.email},
    });
    if (!foundUser) {
      throw new HttpErrors.Unauthorized(invalidCredentialsError);
    }

    const credentialsFound = await this.userRepository.findCredentials(
      foundUser.id,
    );
    if (!credentialsFound) {
      throw new HttpErrors.Unauthorized(invalidCredentialsError);
    }

    const passwordMatched = await compare(
      credentials.password,
      credentialsFound.password,
    );

    if (!passwordMatched) {
      throw new HttpErrors.Unauthorized(invalidCredentialsError);
    }

    return foundUser;
  }

  // User --> MyUser
  convertToUserProfile(user: User): UserProfile {

    let address = ''
    if (user.address) {
      address = user.address
    }

    return {
      [securityId]: user.id!.toString(),
      name: user.name,
      id: user.id,
      email: user.email,
      address: address

    };


  }
}

用户.repositor.ts

import {Getter, inject} from '@loopback/core';
import {DefaultCrudRepository, HasOneRepositoryFactory, repository} from '@loopback/repository';
import {MygodDataSource} from '../datasources';
import {User, UserCred, UserRelations} from '../models';
import {UserCredRepository} from './user-cred.repository';

export type Credentials = {
  email: string;
  password: string;
};



export class UserRepository extends DefaultCrudRepository<
  User,
  typeof User.prototype.id,
  UserRelations
  > {

  public readonly userCred: HasOneRepositoryFactory<UserCred, typeof User.prototype.id>;

  constructor(
    @inject('datasources.mygod') dataSource: MygodDataSource, @repository.getter('UserCredRepository') protected userCredRepositoryGetter: Getter<UserCredRepository>,
  ) {
    super(User, dataSource);
    this.userCred = this.createHasOneRepositoryFactoryFor('userCred', userCredRepositoryGetter);
    this.registerInclusionResolver('userCred', this.userCred.inclusionResolver);
  }


  async findCredentials(
    userId: typeof User.prototype.id,
  ): Promise<UserCred | undefined> {
    try {
      return await this.userCred(userId).get();
    } catch (err) {
      if (err.code === 'ENTITY_NOT_FOUND') {
        return undefined;
      }
      throw err;
    }
  }
}

标签: loopback4

解决方案


在您的 git 帖子中对问题进行简要说明 按照您在 https://github.com/strongloop/loopback-next/issues/5541的回答


推荐阅读