【发布时间】:2021-09-24 03:54:17
【问题描述】:
我正在尝试遵循 tutorial,并且正在努力将实现转换为 GraphQL。
local.strategy.ts
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authenticationService: AuthenticationService) {
super();
}
async validate(email: string, password: string): Promise<any> {
const user = await this.authenticationService.getAuthenticatedUser(
email,
password,
);
if (!user) throw new UnauthorizedException();
return user;
}
}
local.guard.ts
@Injectable()
export class LogInWithCredentialsGuard extends AuthGuard('local') {
async canActivate(context: ExecutionContext): Promise<boolean> {
const ctx = GqlExecutionContext.create(context);
const { req } = ctx.getContext();
req.body = ctx.getArgs();
await super.canActivate(new ExecutionContextHost([req]));
await super.logIn(req);
return true;
}
}
authentication.type.ts
@InputType()
export class AuthenticationInput {
@Field()
email: string;
@Field()
password: string;
}
authentication.resolver.ts
@UseGuards(LogInWithCredentialsGuard)
@Mutation(() => User, { nullable: true })
logIn(
@Args('variables')
_authenticationInput: AuthenticationInput,
@Context() req: any,
) {
return req.user;
}
变异
mutation {
logIn(variables: {
email: "email@email.com",
password: "123123"
} ) {
id
email
}
}
即使上述凭据是正确的,我也会收到未经授权的错误。
【问题讨论】:
标签: graphql nestjs passport-local nestjs-passport