Skip to content
Snippets Groups Projects
auth.resolver.ts 1.09 KiB
Newer Older
  • Learn to ignore specific revisions
  • Adrian Paschkowski's avatar
    V2
    Adrian Paschkowski committed
    import { Args, Mutation, Resolver } from '@nestjs/graphql';
    import { LoginModel } from './models/login.model';
    import { PrismaService } from '../prisma/prisma.service';
    import { randomBytes } from 'crypto';
    import { AgentFlags } from './models/agent.model';
    
    import { UnauthorizedException } from '@nestjs/common';
    
    Adrian Paschkowski's avatar
    V2
    Adrian Paschkowski committed
    
    @Resolver()
    export class AuthResolver {
    	constructor(private readonly prisma: PrismaService) {}
    
    	@Mutation(() => LoginModel)
    	async login(@Args('slug') slug: string) {
    		const [group, agent] = await Promise.all([
    			this.prisma.group.findFirst({
    				where: { slug },
    			}),
    			this.prisma.agent.findFirst({
    				where: { slug },
    			}),
    		]);
    
    		let entityId, role;
    		if (agent) {
    			entityId = agent.id;
    			if ((agent.flags & AgentFlags.ADMIN) === AgentFlags.ADMIN)
    				role = 'admin';
    			else role = 'agent';
    		} else if (group) {
    			entityId = group.id;
    			role = 'group';
    
    			throw new UnauthorizedException('Invalid Login Slug');
    
    Adrian Paschkowski's avatar
    V2
    Adrian Paschkowski committed
    		return await this.prisma.accessToken.create({
    			data: {
    				entityId,
    				role,
    				authToken: randomBytes(36).toString('base64url'),
    			},
    		});
    	}
    }