From afd4424f27d65c1731aa46af8aba1461cf436d4f Mon Sep 17 00:00:00 2001 From: barrfalk Date: Thu, 19 Sep 2024 13:52:56 -0700 Subject: [PATCH] Added read only capabilities to case management Users with the readonly role will not be able to consume non-GET requests --- backend/src/auth/jwtrole.guard.ts | 24 ++++++++++++++++++++---- backend/src/enum/role.enum.ts | 1 + 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/backend/src/auth/jwtrole.guard.ts b/backend/src/auth/jwtrole.guard.ts index c2343d24..4c50167f 100644 --- a/backend/src/auth/jwtrole.guard.ts +++ b/backend/src/auth/jwtrole.guard.ts @@ -1,4 +1,11 @@ -import { ExecutionContext, Injectable, CanActivate, UnauthorizedException, Logger } from "@nestjs/common"; +import { + ExecutionContext, + Injectable, + CanActivate, + UnauthorizedException, + Logger, + ForbiddenException, +} from "@nestjs/common"; import { Reflector } from "@nestjs/core"; import { AuthGuard } from "@nestjs/passport"; import { Role } from "src/enum/role.enum"; @@ -38,6 +45,18 @@ export class JwtRoleGuard extends AuthGuard("jwt") implements CanActivate { throw new UnauthorizedException("Cannot verify user authorization"); } + const userRoles: string[] = user.client_roles; + // Check if the user has the readonly role + const hasReadOnlyRole = userRoles.includes(Role.READ_ONLY); + + // If the user has readonly role, allow only GET requests + if (hasReadOnlyRole) { + if (request.method !== "GET") { + this.logger.debug(`User with readonly role attempted ${request.method} method`); + throw new ForbiddenException("Access denied: Read-only users cannot perform this action"); + } + } + // if there aren't any required roles, don't allow the user to access any api. Unless the API is marked as public, at least one role is required. if (!requiredRoles) { this.logger.error( @@ -46,9 +65,6 @@ export class JwtRoleGuard extends AuthGuard("jwt") implements CanActivate { return false; } - // roles that the user has - const userRoles: string[] = user.client_roles; - this.logger.debug(`User Roles: ${userRoles}`); // does the user have a required role? diff --git a/backend/src/enum/role.enum.ts b/backend/src/enum/role.enum.ts index 344ec3a1..fa012a15 100644 --- a/backend/src/enum/role.enum.ts +++ b/backend/src/enum/role.enum.ts @@ -2,4 +2,5 @@ export enum Role { COS_OFFICER = "COS Officer", COS_ADMIN = "COS Admin", CEEB = "CEEB", + READ_ONLY = "READ ONLY", }