I'm trying to get the current user but in the resolver I get undefined, in the jwt strategy I get the user object using the token but in the resolver the user is undefined
auth guard
import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { GqlExecutionContext } from '@nestjs/graphql';
import { AuthenticationError } from 'apollo-server-core';
import { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host';
@Injectable()
export class GqlAuthGuard extends AuthGuard('jwt') {
canActivate(context: ExecutionContext) {
const ctx = GqlExecutionContext.create(context);
const { req } = ctx.getContext();
return super.canActivate(
new ExecutionContextHost([req]),
);
}
handleRequest(err: any, user: any) {
if (err || !user) {
throw err || new AuthenticationError('GqlAuthGuard');
}
return user;
}
}
user decorator
import {createParamDecorator} from '@nestjs/common';
export const CurrentUser = createParamDecorator(
(data, req) => req.user )
;
app module
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
signOptions: {
expiresIn: 3600,
},
}),
SharedModule,
AuthModule,
GraphQLModule.forRoot({
autoSchemaFile: 'schema.gql',
context: ({ req }) => ({ req })
}),
MongooseModule.forRoot(process.env.MONGO_URI,
{
useNewUrlParser: true ,
useUnifiedTopology: true
}),
// RewardsModule,
OrdersModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
resolver
import {User} from "src/types/user";
import {GqlAuthGuard} from "../guards/graphql.auth.guard";
@Resolver()
export class OrdersResolver {
constructor(
private orderService: OrdersService
) {
}
@Query(returns => [Order])
@UseGuards(GqlAuthGuard)
listOrders(@CurrentUser() user: User): Promise<Order> {
console.log(user)
return this.orderService.listOrdersByUser(user.id);
}
}
I also tried to implement the solution explained here NestJS Get current user in GraphQL resolver authenticated with JWT and still, I got the same error
createParamDecorator
function between v6 and v7. – Marxmarxian