Skip to content

Commit

Permalink
Merge pull request #159 from Xitija/rbac-changes
Browse files Browse the repository at this point in the history
PS-4057 : Changed role create api to accept blank tenant
  • Loading branch information
Shubham4026 authored Feb 26, 2025
2 parents 724d57a + fb064ec commit 47ba938
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 42 deletions.
44 changes: 29 additions & 15 deletions src/adapters/postgres/rbac/role-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { HttpStatus, Injectable } from "@nestjs/common";
import { Role } from "src/rbac/role/entities/role.entity";
import { RolePrivilegeMapping } from "src/rbac/assign-privilege/entities/assign-privilege.entity";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { IsNull, Repository } from "typeorm";
import {
CreateRolesDto,
RoleDto,
Expand All @@ -15,6 +15,8 @@ import { isUUID } from "class-validator";
import APIResponse from "src/common/responses/response";
import { Response } from "express";
import { APIID } from "src/common/utils/api-id.config";
import { validate as uuidValidate } from 'uuid';


@Injectable()
export class PostgresRoleService {
Expand All @@ -25,34 +27,46 @@ export class PostgresRoleService {
private readonly userRoleMappingRepository: Repository<UserRoleMapping>,
@InjectRepository(RolePrivilegeMapping)
private readonly roleprivilegeMappingRepository: Repository<RolePrivilegeMapping>
) {}
) { }
public async createRole(
request: any,
createRolesDto: CreateRolesDto,
response: Response
) {
const apiId = APIID.ROLE_CREATE;
const tenant = await this.checkTenantID(createRolesDto.tenantId);
if (!tenant) {
return APIResponse.error(
response,
apiId,
`Please enter valid tenantId`,
"Invalid Tenant Id",
HttpStatus.BAD_REQUEST
);
}
const roles = [];
const errors = [];

try {
if (createRolesDto?.tenantId?.trim() !== '' && !uuidValidate(createRolesDto?.tenantId)) {
return APIResponse.error(
response,
apiId,
`Please enter valid tenantId or keep blank`,
"Invalid Tenant Id",
HttpStatus.BAD_REQUEST
);
} else if (uuidValidate(createRolesDto?.tenantId)) {
const tenant = await this.checkTenantID(createRolesDto.tenantId);
if (!tenant) {
return APIResponse.error(
response,
apiId,
`Tenant Id not found`,
"Tenant Id not found",
HttpStatus.NOT_FOUND
);
}
}

// Convert role name to lowercase
const tenantId = createRolesDto.tenantId;
for (const roleDto of createRolesDto.roles) {
const tenantId = createRolesDto.tenantId;
const code = roleDto.title.toLowerCase().replace(/\s+/g, "_");

// Check if role name already exists
const existingRole = await this.roleRepository.findOne({
where: { code: code, tenantId: tenantId },
where: { code: code, tenantId: tenantId ? tenantId : IsNull() },
});
if (existingRole) {
errors.push({
Expand All @@ -68,7 +82,7 @@ export class PostgresRoleService {
updatedAt: new Date(),
createdBy: request.user.userId, // Assuming you have a user object in the request
updatedBy: request.user.userId,
tenantId, // Add the tenantId to the RoleDto
tenantId: tenantId ? tenantId : null, // Add the tenantId to the RoleDto
});
// Convert roleDto to lowercase
// const response = await this.roleRepository.save(roleDto);
Expand Down
49 changes: 27 additions & 22 deletions src/middleware/permission.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,30 +6,35 @@ import { RolePermissionService } from "src/permissionRbac/rolePermissionMapping/

@Injectable()
export class PermissionMiddleware implements NestMiddleware {
constructor(private readonly rolePermissionService: RolePermissionService) {}
constructor(private readonly rolePermissionService: RolePermissionService) { }

async use(req: Request, res: Response, next: NextFunction) {
LoggerUtil.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
let role = "";
if (req.headers.authorization) {
role = this.getRole(req.headers.authorization);
} else {
role = "public";
}
const isPermissionValid = await this.checkPermissions(
role,
req.baseUrl,
req.method
);
if (isPermissionValid) return next();
else {
return APIResponse.error(
res,
"",
"You do not have permission to access this resource",
"You do not have permission to access this resource",
HttpStatus.FORBIDDEN
try {
LoggerUtil.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
let role = "";
if (req.headers.authorization) {
role = this.getRole(req.headers.authorization);
} else {
role = "public";
}
const isPermissionValid = await this.checkPermissions(
role,
req.baseUrl,
req.method
);

if (isPermissionValid) next();
else {
return APIResponse.error(
res,
"",
"You do not have permission to access this resource",
"You do not have permission to access this resource",
HttpStatus.FORBIDDEN
);
}
} catch (e) {
return APIResponse.error(res, "Something went wrong", e, "Internal error", HttpStatus.INTERNAL_SERVER_ERROR)
}
}
async checkPermissions(
Expand Down Expand Up @@ -67,6 +72,6 @@ export class PermissionMiddleware implements NestMiddleware {
const payloadBase64 = token.split(".")[1]; // Get the payload part
const payloadJson = Buffer.from(payloadBase64, "base64").toString("utf-8"); // Decode Base64
const payload = JSON.parse(payloadJson); // Convert to JSON
return payload.pratham_role;
return payload.user_roles;
}
}
7 changes: 2 additions & 5 deletions src/rbac/role/dto/role.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ import { Expose, Type } from "class-transformer";
import { ApiProperty } from "@nestjs/swagger";
import {
IsNotEmpty,
IsString,
IsUUID,
IsOptional,
ValidateNested,
isUUID,
} from "class-validator";

export class RoleDto {
Expand Down Expand Up @@ -47,8 +45,7 @@ export class CreateRolesDto {
description: "Tenant",
})
@Expose()
@IsNotEmpty()
@IsUUID()
@IsOptional()
tenantId: string;

@ApiProperty({ type: [RoleDto] })
Expand Down

0 comments on commit 47ba938

Please sign in to comment.