43 lines
1.3 KiB
TypeScript
43 lines
1.3 KiB
TypeScript
import { ExecutionContext, Injectable } from "@nestjs/common";
|
|
import { Reflector } from "@nestjs/core";
|
|
import { GqlExecutionContext } from "@nestjs/graphql";
|
|
import { AuthGuard } from "@nestjs/passport";
|
|
import { IS_PUBLIC_KEY } from "./public.decorator";
|
|
|
|
@Injectable()
|
|
export class GqlAuthGuard extends AuthGuard("jwt") {
|
|
constructor(private readonly reflector: Reflector) {
|
|
super();
|
|
}
|
|
|
|
canActivate(context: ExecutionContext) {
|
|
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
|
context.getHandler(),
|
|
context.getClass(),
|
|
]);
|
|
if (isPublic) return true;
|
|
return super.canActivate(context);
|
|
}
|
|
|
|
getRequest(context: ExecutionContext) {
|
|
if (context.getType<string>() === "http") {
|
|
return context.switchToHttp().getRequest();
|
|
}
|
|
const ctx = GqlExecutionContext.create(context);
|
|
const { req, connectionParams, extra } = ctx.getContext();
|
|
if (req?.headers?.authorization) return req;
|
|
const auth =
|
|
connectionParams?.authorization ??
|
|
connectionParams?.Authorization ??
|
|
extra?.request?.headers?.authorization;
|
|
if (auth && req) {
|
|
req.headers.authorization = auth;
|
|
}
|
|
if (auth && !req?.headers?.authorization && extra?.request) {
|
|
extra.request.headers.authorization = auth;
|
|
return extra.request;
|
|
}
|
|
return req;
|
|
}
|
|
}
|