Search code examples
loopback4

Loopback 4 authentication Issue with login controller


I am trying to add authentication to my app. There are two models named user and user-credential. The user has one user-credential.

The post request to the User is working fine. Password is stored in the user-credential model(hashed) and other fields are stored in the user model.

But When I make login request I am getting following error

Unhandled error in POST /users/login: 500 TypeError: this.userRepository.findCredentials is not a function at MyUserService.verifyCredentials (D:\ionic-pr\loopback-projects\no\node_modules@loopback\authentication-jwt\src\services\user.service.ts:38:56) at process._tickCallback (internal/process/next_tick.js:68:7)

The user-service inside authentication-jwt in node-modules is throwing error.

I can't get what is going wrong.

Thank you in advance

EDIT: Now I have made two controllers. The first one makes post request works fine. And the second one performs login as below

imports -

import {TokenService} from '@loopback/authentication';
import {Credentials, MyUserService, TokenServiceBindings, UserRepository, UserServiceBindings} from "@loopback/authentication-jwt";
import {inject} from '@loopback/core';
import {repository} from '@loopback/repository';
import {post, requestBody} from '@loopback/rest';
import {SecurityBindings, UserProfile} from '@loopback/security';

constructor -

constructor(
    @inject(TokenServiceBindings.TOKEN_SERVICE)
    public jwtService: TokenService,
    @inject(UserServiceBindings.USER_SERVICE)
    public userService: MyUserService,
    @inject(SecurityBindings.USER, {optional: true})
    public user: UserProfile,
    @repository(UserRepository) protected userRepository: UserRepository,
  )

Solution

  • As you stated you are using @ loopback/authenntication-jwt

    import {User} from '../models';
    import {UserRepository} from '../repositories';
    

    From above it seems that you have created your own user-repository. You are not usng the default one from the extension, which is throwing error. the above import should be like

    import {
      Credentials,
      MyUserService,
      TokenServiceBindings,
      User,
      UserRepository,
      UserServiceBindings,
    } from "@loopback/authentication-jwt";
    

    This will fix you out. If you are trying to create your own custom user than please refer https://github.com/strongloop/loopback-next/tree/master/extensions/authentication-jwt#customizing-user Also you have imported wrong UserSerivce. it should be from @loopback/authentication-jwt and your injection should be like

    @inject(UserServiceBindings.USER_SERVICE) public userService: MyUserService,