Skip to content
Snippets Groups Projects
graphql-auth.guard.ts 887 B
Newer Older
  • Learn to ignore specific revisions
  • import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
    import { GqlExecutionContext } from "@nestjs/graphql";
    import { Request } from "express";
    import { Observable } from "rxjs";
    import { PrismaService } from "src/prisma/prisma.service";
    
    @Injectable()
    
    export class GraphQLAuthGuard implements CanActivate {
    
    
        constructor(private prismaService: PrismaService) {}
        
        async canActivate(context: ExecutionContext): Promise<boolean> {
            const ctx = GqlExecutionContext.create(context);
    
            const req: Request = ctx.getContext().req;
    
            const token = req.headers.authorization;
    
            if (!token)
                return false;
    
            const group = await this.prismaService.group.findFirst({
                where: { code: token },
            });
    
            if (!group)
                return false;
    
            req.group = group;
    
            return true;
        }
    
    }