common added for decorators dto and guards
This commit is contained in:
@@ -0,0 +1,3 @@
|
|||||||
|
import { SetMetadata } from "@nestjs/common";
|
||||||
|
|
||||||
|
export const Roles = (...roles: string[]) => SetMetadata("roles", roles);
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { createParamDecorator, ExecutionContext } from "@nestjs/common";
|
||||||
|
|
||||||
|
export const User = createParamDecorator((data: string | undefined, ctx: ExecutionContext) => {
|
||||||
|
const request = ctx.switchToHttp().getRequest();
|
||||||
|
const user = request.user;
|
||||||
|
return data ? user?.[data] : user;
|
||||||
|
});
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { IsDateString, IsOptional } from "class-validator";
|
||||||
|
|
||||||
|
export class DateRangeQueryDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsDateString()
|
||||||
|
start?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsDateString()
|
||||||
|
end?: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { IsUUID } from "class-validator";
|
||||||
|
|
||||||
|
export class IdParamDto {
|
||||||
|
@IsUUID()
|
||||||
|
id: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { IsOptional, IsPositive } from "class-validator";
|
||||||
|
|
||||||
|
export class PaginationQueryDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsPositive()
|
||||||
|
offset?: number;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsPositive()
|
||||||
|
limit?: number;
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { IsOptional, IsString, MinLength } from "class-validator";
|
||||||
|
|
||||||
|
export class SearchQueryDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MinLength(2)
|
||||||
|
q?: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
|
||||||
|
import { Reflector } from "@nestjs/core";
|
||||||
|
import { Observable } from "rxjs";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class RolesGuard implements CanActivate {
|
||||||
|
constructor(private readonly reflector: Reflector) {}
|
||||||
|
canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
|
||||||
|
const requiredRoles = this.reflector.get<string[]>('roles', context.getHandler());
|
||||||
|
if (!requiredRoles || requiredRoles.length === 0) {
|
||||||
|
return true; // Si aucun role est requis -> accès autorise
|
||||||
|
}
|
||||||
|
|
||||||
|
const request = context.switchToHttp().getRequest();
|
||||||
|
const user = request.user;
|
||||||
|
if (!user || !user.role) {
|
||||||
|
return false; // Si l'utilisateur est pas authentifie ou a pas de role -> accès refusé
|
||||||
|
}
|
||||||
|
return requiredRoles.includes(user.role);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user