init project
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user