您必须命名您的策略并在提供商中注册。对我来说,它适用于以下设置
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class LocalAuthGuard extends AuthGuard('UsernamePasswordStrategy') {}
@Injectable()
export class OTPAuthGuard extends AuthGuard('OTPStrategy') {}
用户名和密码策略
import { Strategy } from 'passport-local';
@Injectable()
export class LocalStrategy extends PassportStrategy(
Strategy,
'UsernamePasswordStrategy',
) {
constructor(
@Inject(IAuthService)
private readonly authService: IAuthService,
) {
super({
usernameField: 'user_name',
passwordField: 'password',
});
}
async validate(user_name: string, password: string): Promise<any> {
const loginDto = new LoginDto();
loginDto.userName = user_name;
loginDto.password = password;
const user: UserDto = await this.authService.validateUser(loginDto);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
一次性密码策略
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { IAuthService } from '../services';
import { OtpLoginDto } from '../dto';
import { UserDto } from 'src/modules/user/dto';
import { plainToClass } from 'class-transformer';
@Injectable()
export class OTPStrategy extends PassportStrategy(Strategy, 'OTPStrategy') {
constructor(
@Inject(IAuthService)
private readonly authService: IAuthService,
) {
super({
usernameField: 'phone',
passwordField: 'otp',
});
}
async validate(phone: string, otp: string): Promise<any> {
const loginDto = plainToClass(OtpLoginDto, {
phone: phone,
otp: otp,
});
const user: UserDto = await this.authService.verifyOtp(loginDto);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}