I have a Custom Decorator that returns user details created from the an AuthGuard.
auth.guard.ts
import {
Injectable,
CanActivate,
ExecutionContext,
UnauthorizedException,
} from '@nestjs/common'
import { GqlExecutionContext } from '@nestjs/graphql'
import { JwtService } from '@nestjs/jwt'
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private jwtService: JwtService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const ctx = GqlExecutionContext.create(context).getContext()
if (!ctx.headers.authorization) {
return false
}
ctx.user = await this.validateToken(ctx.headers.authorization)
return true
}
async validateToken(auth: string) {
if (auth.split(' ')[0] !== 'Bearer') {
throw new UnauthorizedException('Invalid access token')
}
const token = auth.split(' ')[1]
try {
const decoded = await this.jwtService.verifyAsync(token)
return decoded
} catch (err) {
const message = 'Token error: ' + (err.message || err.name)
throw new UnauthorizedException(message)
}
}
}
custom.decorator.ts
import { createParamDecorator, ExecutionContext } from '@nestjs/common'
import { GqlExecutionContext } from '@nestjs/graphql'
export const CustomDecorator = createParamDecorator(
(_data, context: ExecutionContext) => {
const ctx = GqlExecutionContext.create(context).getContext()
return ctx.user
},
)
export default CustomDecorator
But the custom decorator returns undefined on some GraphQL resolvers files, with basically within the same module and auth guards.