Team Ai
Apppublic

oex2003/evolution-api

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
auth.guard.ts54 linesDownload Raw Back to guards
1import { InstanceDto } from '@api/dto/instance.dto';2import { prismaRepository } from '@api/server.module';3import { Auth, configService, Database } from '@config/env.config';4import { Logger } from '@config/logger.config';5import { ForbiddenException, UnauthorizedException } from '@exceptions';6import { NextFunction, Request, Response } from 'express';7 8const logger = new Logger('GUARD');9 10async function apikey(req: Request, _: Response, next: NextFunction) {11  const env = configService.get<Auth>('AUTHENTICATION').API_KEY;12  const key = req.get('apikey');13  const db = configService.get<Database>('DATABASE');14 15  if (!key) {16    throw new UnauthorizedException();17  }18 19  if (env.KEY === key) {20    return next();21  }22 23  if ((req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) && !key) {24    throw new ForbiddenException('Missing global api key', 'The global api key must be set');25  }26  const param = req.params as unknown as InstanceDto;27 28  try {29    if (param?.instanceName) {30      const instance = await prismaRepository.instance.findUnique({31        where: { name: param.instanceName },32      });33      if (instance.token === key) {34        return next();35      }36    } else {37      if (req.originalUrl.includes('/instance/fetchInstances') && db.SAVE_DATA.INSTANCE) {38        const instanceByKey = await prismaRepository.instance.findFirst({39          where: { token: key },40        });41        if (instanceByKey) {42          return next();43        }44      }45    }46  } catch (error) {47    logger.error(error);48  }49 50  throw new UnauthorizedException();51}52 53export const authGuard = { apikey };54