import { Injectable, ExecutionContext } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class GqlAuthGuard extends AuthGuard('jwt') {
getRequest(context: ExecutionContext) {
const ctx = GqlExecutionContext.create(context);
return ctx.getContext().req;
}
}
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: 'reallyfuckinghard',
});
}
async validate(payload: any) {
const { _id, email } = payload;
return { _id, email };
}
}
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
export const CurrentUser = createParamDecorator(
(data: unknown, context: ExecutionContext) => {
console.log(GqlExecutionContext.create(context).getContext().req.user);
const { _id, email } =
GqlExecutionContext.create(context).getContext().req.user;
return {
_id,
email,
};
},
);
@Query(() => [User])
@UseGuards(GqlAuthGuard)
async findAllUsers() {
try {
return await this.userService.findAll();
} catch (error) {
console.error(error);
}
}