DesenrolaAi / backend /src /admin /admin-auth.guard.ts
Rafael Giandoso
feat: deploy DesenrolaAí no HF Spaces
af69a75
Raw
History Blame Contribute Delete
1.61 kB
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { Request } from 'express';
import { AdminService } from './admin.service';
@Injectable()
export class AdminAuthGuard implements CanActivate {
constructor(private readonly adminService: AdminService) {}
canActivate(context: ExecutionContext): boolean {
const req = context.switchToHttp().getRequest<Request>();
const headerKey = this.getHeaderValue(req, 'x-dashboard-key');
const queryKey = this.getQueryValue(req, 'key');
const bearerKey = this.getBearerToken(req);
const chave = headerKey || queryKey || bearerKey;
if (!this.adminService.validarChaveDashboard(chave)) {
throw new UnauthorizedException('Dashboard key invalida');
}
return true;
}
private getHeaderValue(req: Request, nome: string): string | undefined {
const valor = req.headers[nome];
if (Array.isArray(valor)) {
return valor[0];
}
return typeof valor === 'string' ? valor : undefined;
}
private getQueryValue(req: Request, nome: string): string | undefined {
const valor = req.query?.[nome];
if (Array.isArray(valor)) {
return typeof valor[0] === 'string' ? valor[0] : undefined;
}
return typeof valor === 'string' ? valor : undefined;
}
private getBearerToken(req: Request): string | undefined {
const authHeader = this.getHeaderValue(req, 'authorization');
if (!authHeader) return undefined;
if (!authHeader.toLowerCase().startsWith('bearer ')) return undefined;
return authHeader.slice(7).trim();
}
}