Skip to content
Snippets Groups Projects
web-auth.guard.ts 802 B
Newer Older
  • Learn to ignore specific revisions
  • Pascal Kosak's avatar
    Pascal Kosak committed
    import { CanActivate, ExecutionContext, ForbiddenException, Injectable, UnauthorizedException } from '@nestjs/common';
    
    import { Request } from 'express';
    import { PrismaService } from '../prisma/prisma.service';
    
    export class WebAuthGuard implements CanActivate {
    
        constructor(private prismaService: PrismaService) {}
    
        async canActivate(context: ExecutionContext): Promise<boolean> {
    
            const req: Request = context.switchToHttp().getRequest();
    
    
            const token = req.headers.authorization;
    
    
    Pascal Kosak's avatar
    Pascal Kosak committed
            if (!token) throw new UnauthorizedException();
    
    
            const group = await this.prismaService.group.findFirst({
                where: { code: token },
            });
    
    
    Pascal Kosak's avatar
    Pascal Kosak committed
            if (!group) throw new ForbiddenException();
    
    
            req.group = group;
    
            return true;
        }