Reputation: 320
I just want to implemented authentication by passportjs in NestJS. I got these lines of error when I send post request to "localhost:3000/auth/login".
[ExceptionsHandler] Cannot read property 'validateUser' of undefined
TypeError: Cannot read property 'validateUser' of undefined
and These is my code :
local.strategy.ts
import { AuthService } from './auth.service';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-local';
import { UnauthorizedException } from '@nestjs/common';
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super();
}
async validate(username: string, password: string): Promise<any> {
console.log(username, password);
const user = await this.authService.validateUser(username, password); <====This part
if (!user) {
return new UnauthorizedException();
}
return user;
}
}
auth.service.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class AuthService {
users = [{ id: 1, username: 'Peyman', password: 'password' }];
async validateUser(username: string, password: string): Promise<any> {
console.log('Validate');
const user = await this.users.find((x) => x.username === username);
if (user && user.password === password) {
return user;
}
return null;
}
}
auth.module.ts
import { LocalStrategy } from './local.strategy';
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { AuthService } from './auth.service';
@Module({
imports: [PassportModule],
providers: [AuthService, LocalStrategy],
exports: [PassportModule],
})
export class AuthModule {}
app.module.ts
import { Contact } from './contacts/contacts.entity';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Module } from '@nestjs/common';
import { ContactsModule } from './contacts/contacts.module';
import { AppController } from './app.controller';
import { AuthModule } from './auth/auth.module';
import { PassportModule } from '@nestjs/passport';
@Module({
imports: [
ContactsModule,
PassportModule,
TypeOrmModule.forRoot({ entities: [Contact] }),
AuthModule,
],
controllers: [AppController],
providers: [],
})
export class AppModule {}
app.controller.ts
import { Controller, Post, UseGuards, Request } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Controller()
export class AppController {
@UseGuards(AuthGuard('local'))
@Post('auth/login')
public async login(@Request() req): Promise<any> {
return req.user;
}
}
I inject authservice by dependency injection, by got an error. How can I fix this?
Upvotes: 3
Views: 1870
Reputation: 1
manually removing the dist folder and restarting the server worked for me
Upvotes: 0