I'm trying to implement a Passport Local Strategy but the validate method is not working. When I do @UseGuards(AuthGuard("local"))
, it automatically throws an Unauthorized Exception without going through the validate method that I wrote. I have no idea what I'm doing wrong as the documentation did the same.
Here's my LocalStrategy class:
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(
@InjectRepository(UserRepository) private userRepository: UserRepository,
) {
super();
}
async validate(credentials: string, password: string): Promise<User> {
// this method is never called, I've already did some console.logs
const user = await this.userRepository.findByCredentials(credentials);
if (!user) throw new UnauthorizedException('Invalid credentials');
if (!(await argon2.verify(user.hash, password)))
throw new UnauthorizedException('Invalid credentials');
return user;
}
}
My AuthModule imports:
@Module({
imports: [TypeOrmModule.forFeature([UserRepository]), PassportModule],
controllers: [AuthController],
providers: [AuthService, LocalStrategy],
})
export class AuthModule {}
Example usage:
@Post("/login")
@UseGuards(LocalAuthGuard)
async login(@Body() loginDto: LoginDto) {
return this.authService.login(loginDto);
}