Ошибка аутентификации NestJs Graphql Mongodb
Auth.service.ts
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { SearchUserOutput } from 'src/users/dto/search-user.output';
import { UsersService } from '../users/users.service';
@Injectable()
export class AuthService {
constructor(
private usersService: UsersService,
private jwtService: JwtService,
) {}
async validateUser(username: string, password: string): Promise<SearchUserOutput> {
const user = await this.usersService.findOne(username);
if (user && user.password == password) {
const { password, ...result } = user;
return result;
}
return null;
}
async login(user: SearchUserOutput,role:string) {
return {
accessToken: this.jwtService.sign({
username: user.username,
role: role
}),
user,
};
}
}
Auth.resolver.ts
import { UseGuards } from '@nestjs/common';
import { Args, Context, Mutation, Resolver } from '@nestjs/graphql';
import { AuthService } from './auth.service';
import { LoginUserInput } from './dto/login-user.input';
import { LoginResponse } from './dto/login-response.ouput';
import { GqlAuthGuard } from './guards/gql-auth.guard';
@Resolver()
export class AuthResolver {
constructor(private authService: AuthService) {}
@Mutation(() => LoginResponse)
@UseGuards(GqlAuthGuard)
loginUser(
@Args('loginUserInput') loginUserInput: LoginUserInput,
@Context() context
): Promise<LoginResponse> {
return this.authService.login(context.user,'user');
}
}
Auth.module.ts
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { MongooseModule } from '@nestjs/mongoose';
import { PassportModule } from '@nestjs/passport';
import { UserSchema } from 'src/users/entities/user.entity';
import { UsersModule } from 'src/users/users.module';
import { AuthResolver } from './auth.resolver';
import { AuthService } from './auth.service';
import { JwtStrategy } from './strategies/jwt.strategy';
import { LocalStrategy } from './strategies/local.strategy';
@Module({
imports: [PassportModule,UsersModule,JwtModule.register({
secret: 'secret',
signOptions: { expiresIn: '30d' },
}),MongooseModule.forFeature([{ name: 'User', schema: UserSchema }])],
providers: [AuthResolver, AuthService,LocalStrategy,JwtStrategy]
})
export class AuthModule {}
local.strategy.ts
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { AuthService } from '../auth.service';
import { Strategy } from 'passport-local';
import { SearchUserOutput } from 'src/users/dto/search-user.output';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super();
}
async validate(username: string, password: string): Promise<SearchUserOutput> {
const user = await this.authService.validateUser(username, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
gql-authh.guard.ts
import { ExecutionContext, Injectable } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class GqlAuthGuard extends AuthGuard('local') {
constructor() {
super();
}
getRequest(context: ExecutionContext) {
const ctx = GqlExecutionContext.create(context);
const request = ctx.getContext();
request.body = ctx.getArgs().loginUserInput;
return request;
}
}
логин-ответ.output.ts
import { Field, ObjectType } from '@nestjs/graphql';
import { SearchUserOutput } from 'src/users/dto/search-user.output';
@ObjectType()
export class LoginResponse {
@Field(() => String)
accessToken: string;
@Field(() => SearchUserOutput)
user: SearchUserOutput;
}
логин-user.input.ts
import { Field, InputType } from '@nestjs/graphql';
import { IsNotEmpty, IsString } from 'class-validator';
@InputType()
export class LoginUserInput {
@Field(() => String)
@IsNotEmpty()
@IsString()
username: string;
@Field(() => String)
@IsNotEmpty()
@IsString()
password: string;
}
он постоянно выдает мне ошибку, если вам нужен исходный код, я пришлю вам
"зависимости": { "@nestjs/apollo": "^10.0.19", "@nestjs/common": "^9.0.0", "@nestjs/core": "^9.0.0", "@nestjs /graphql": "^10.0.21", "@nestjs/jwt": "^9.0.0", "@nestjs/mapped-types": "*", "@nestjs/mongoose": "^9.2.0 ", "@nestjs/passport": "^9.0.0", "@nestjs/platform-express": "^9.0.0", "@nestjs/testing": "^9.0.11", "@types/ jest": "^28.1.7", "@types/node": "^18.7.6", "@types/passport-jwt": "^3.0.6", "apollo-server-express": "^ 3.10.1", "класс-валидатор": "^0.13.2", "экспресс": "^4.18.1", "graphql": "^15","мангуст": "^6.5.2", "паспорт": "^0.6.0", "паспорт-jwt": "^4.0.0", "паспорт-местный": "^1.0.0", "отражать -metadata": "^0.1.13", "rimraf": "^3.0.2", "rxjs": "^7.2.0", "type-graphql": "^1.1.1", "webpack": "^5.74.0" }, "devDependencies": { "@types/express": "^4.17.13", "@types/passport-local": "^1.0.34", "@types/supertest": "^2.0.11", "@typescript-eslint/eslint-plugin": "^5.0.0", "@typescript-eslint/parser": "^5.0.0", "eslint": "^8.0.1 ", "eslint-config-prettier": "^8.3.0", "eslint-plugin-prettier": "^4.0.0", "шутка": "28.1.2", "красивее": "^2.3.2", "поддержка исходной карты": "^0.5.20", "супертест": "^6.1.3", "ts-jest": "28.0.5", "ts-loader": "^9.2.3", "ts-node": "^10.0.0", "tsconfig-paths": "4.0.0", "машинопись": "^4.3.5" },