base con autenticacion, registro, modulo encuestas
This commit is contained in:
2
apps/api/src/common/guards/index.ts
Normal file
2
apps/api/src/common/guards/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export * from './jwt-auth.guard';
|
||||
export * from './roles.guard';
|
||||
81
apps/api/src/common/guards/jwt-auth.guard.ts
Normal file
81
apps/api/src/common/guards/jwt-auth.guard.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { Request } from 'express';
|
||||
import { IS_PUBLIC_KEY } from 'src/common/decorators';
|
||||
import { envs } from '../config/envs';
|
||||
import { NodePgDatabase } from 'drizzle-orm/node-postgres';
|
||||
import { DRIZZLE_PROVIDER } from 'src/database/drizzle-provider';
|
||||
import { Inject } from '@nestjs/common';
|
||||
import { roles, usersRole } from 'src/database/schema/auth';
|
||||
import { eq } from 'drizzle-orm';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private jwtService: JwtService,
|
||||
private reflector: Reflector,
|
||||
@Inject(DRIZZLE_PROVIDER)
|
||||
private readonly drizzle: NodePgDatabase,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
if (isPublic) {
|
||||
return true;
|
||||
}
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const token = this.extractTokenFromHeader(request);
|
||||
if (!token) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
try {
|
||||
const payload = await this.jwtService.verifyAsync(token, {
|
||||
secret: envs.access_token_secret,
|
||||
});
|
||||
|
||||
// Asegurarse de que el payload contiene el ID del usuario
|
||||
if (!payload.sub && !payload.id) {
|
||||
throw new UnauthorizedException('Invalid token payload');
|
||||
}
|
||||
|
||||
const userId = payload.sub || payload.id;
|
||||
|
||||
// Obtener los roles del usuario desde la base de datos
|
||||
const userRoles = await this.drizzle
|
||||
.select({ name: roles.name })
|
||||
.from(roles)
|
||||
.innerJoin(usersRole, eq(usersRole.roleId, roles.id))
|
||||
.where(eq(usersRole.userId, userId));
|
||||
|
||||
// Verificar si el usuario tiene el rol SUPERADMIN
|
||||
const isSuperAdmin = userRoles.some(role => role.name === 'superadmin');
|
||||
|
||||
// Adjuntar el usuario a la solicitud con el ID correcto y sus roles
|
||||
request.user = {
|
||||
id: userId,
|
||||
username: payload.username,
|
||||
email: payload.email,
|
||||
roles: userRoles.map(role => role.name),
|
||||
isSuperAdmin, // Añadir flag para indicar si es SUPERADMIN
|
||||
};
|
||||
} catch (error) {
|
||||
throw new UnauthorizedException('Invalid Access Token');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private extractTokenFromHeader(request: Request): string | undefined {
|
||||
const [type, token] = request.headers.authorization?.split(' ') ?? [];
|
||||
return type === 'Bearer' ? token : undefined;
|
||||
}
|
||||
}
|
||||
49
apps/api/src/common/guards/jwt-refresh.guard.ts
Normal file
49
apps/api/src/common/guards/jwt-refresh.guard.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { DRIZZLE_PROVIDER } from '@/database/drizzle-provider';
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Inject,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { NodePgDatabase } from 'drizzle-orm/node-postgres';
|
||||
import { Request } from 'express';
|
||||
import * as schema from 'src/database/index';
|
||||
import { envs } from '../config/envs';
|
||||
|
||||
@Injectable()
|
||||
export class JwtRefreshGuard implements CanActivate {
|
||||
constructor(
|
||||
private jwtService: JwtService,
|
||||
@Inject(DRIZZLE_PROVIDER) private drizzle: NodePgDatabase<typeof schema>,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const token = this.extractTokenFromHeader(request);
|
||||
if (!token) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
try {
|
||||
request.user = await this.jwtService.verifyAsync(token, {
|
||||
secret: envs.refresh_token_secret,
|
||||
});
|
||||
} catch {
|
||||
const session = await this.drizzle
|
||||
.select()
|
||||
.from(schema.sessions)
|
||||
.where(eq(schema.sessions, token));
|
||||
if (session.length === 0) {
|
||||
throw new UnauthorizedException('Invalid Refresh Token');
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private extractTokenFromHeader(request: Request): string | undefined {
|
||||
const [type, token] = request.headers.authorization?.split(' ') ?? [];
|
||||
return type === 'Bearer' ? token : undefined;
|
||||
}
|
||||
}
|
||||
47
apps/api/src/common/guards/roles.guard.ts
Normal file
47
apps/api/src/common/guards/roles.guard.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { ROLES_KEY } from '../decorators/roles.decorator';
|
||||
import { IS_PUBLIC_KEY } from '../decorators';
|
||||
|
||||
@Injectable()
|
||||
export class RolesGuard implements CanActivate {
|
||||
constructor(
|
||||
private reflector: Reflector,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
|
||||
if (isPublic) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
|
||||
if (!requiredRoles || requiredRoles.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const { user } = context.switchToHttp().getRequest();
|
||||
|
||||
if (!user) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Si el usuario es SUPERADMIN, permitir acceso sin verificar más
|
||||
if (user.isSuperAdmin) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Verificar si el usuario tiene alguno de los roles requeridos
|
||||
return requiredRoles.some(role =>
|
||||
user.roles.includes(role)
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user