Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add function to authorize user to register patient #9000

Open
wants to merge 8 commits into
base: develop
Choose a base branch
from

Conversation

JavidSumra
Copy link
Contributor

@JavidSumra JavidSumra commented Nov 5, 2024

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate the bug fix or test the new feature.
  • Update product documentation.
  • Ensure that all UI text is stored in I18n files.
  • Prepare and attach a screenshot or demo video for the changelog entry to the issue.
  • Request peer reviews.
  • Complete QA.

Summary by CodeRabbit

  • New Features

    • Introduced dynamic rendering for the "Add Patient" button in the FacilityHome component, ensuring only authorized users can access it.
    • Enhanced user authentication logic for patient registration, streamlining the process based on user roles and facility context.
  • Bug Fixes

    • Improved control flow for user permissions, ensuring accurate access rights for patient registration.

@JavidSumra JavidSumra requested a review from a team as a code owner November 5, 2024 12:10
Copy link

coderabbitai bot commented Nov 5, 2024

Walkthrough

The changes introduce a new function, PatientRegisterAuth, to handle user authorization for adding patient details in the FacilityHome component. This function checks user permissions based on their role and facility context, replacing a static button with a conditionally rendered one. The PatientRegister component is updated to utilize this function, enhancing modularity and readability. The overall component structure remains unchanged, with no impact on existing methods or error handling.

Changes

File Path Change Summary
src/components/Facility/FacilityHome.tsx Added PatientRegisterAuth function to conditionally render the button for adding patient details.
src/components/Patient/PatientRegister.tsx Introduced PatientRegisterAuth function for user authorization, replacing inline logic. Updated imports and function signature.

Assessment against linked issues

Objective Addressed Explanation
Display a notification for unauthorized access when adding a patient (#8988) The changes do not implement notification or redirection logic for unauthorized users.

Possibly related PRs

  • Added dynamic lock icon and strong types #9006: This PR introduces the PatientRegisterAuth function in the PatientRegister component, which is directly related to the changes made in the main PR that also involves the PatientRegisterAuth function for user authorization in the FacilityHome component.

Suggested labels

needs review, good to merge, tested, urgent, P1

Suggested reviewers

  • rithviknishad
  • shivankacker

Poem

🐇 In the land of care, where patients reside,
A button appears, with permissions as guide.
Only those trusted can add with delight,
A safer place blooms, in the soft moonlight.
With roles now defined, all can see,
A world of health, for you and for me! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Nov 5, 2024

Deploy Preview for care-ohc failed.

Name Link
🔨 Latest commit 7976cea
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/672c3f4860a3dd000872c4e4

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
src/components/Facility/FacilityHome.tsx (1)

488-500: Button implementation needs minor improvements

The conditional rendering successfully prevents unauthorized access, addressing the PR objective. However, there are a few improvements to consider:

  1. Update the function name once fixed (from previous comment)
  2. Add an id attribute for testing/accessibility

Apply these improvements:

-{isAuthorizedToRegisterPatientsterAuth() && (
+{isAuthorizedToRegisterPatientsAuth() && (
   <ButtonV2
+    id="add-patient-details-button"
     variant="primary"
     ghost
     border
     className="mt-2 flex w-full flex-row justify-center md:w-auto"
     onClick={() => navigate(`/facility/${facilityId}/patient`)}
     authorizeFor={NonReadOnlyUsers}
   >
     <CareIcon icon="l-plus" className="text-lg" />
     <span className="text-sm">{t("add_details_of_patient")}</span>
   </ButtonV2>
 )}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6b57124 and 80a8168.

📒 Files selected for processing (1)
  • src/components/Facility/FacilityHome.tsx (2 hunks)
🔇 Additional comments (1)
src/components/Facility/FacilityHome.tsx (1)

160-182: Verify the authorization implementation fixes the infinite loop issue

The implementation appears to properly address the infinite loop issue by:

  1. Preventing unauthorized access through proper authorization checks
  2. Hiding the "Add Details of Patient" button for unauthorized users
  3. Properly handling different user types and their permissions

Let's verify there are no other instances of patient registration routes that could bypass this check.

Also applies to: 488-500

✅ Verification successful

Authorization checks are properly implemented across patient registration flow

The verification confirms that the infinite loop issue is properly addressed through consistent authorization checks:

  1. FacilityHome.tsx has proper authorization checks before showing the registration button
  2. PatientRegister.tsx implements identical authorization logic preventing unauthorized access
  3. ManagePatients.tsx enforces the same authorization rules with proper redirects
  4. Router configuration in PatientRoutes.tsx shows all patient-related routes are properly structured

The implementation successfully prevents unauthorized access and infinite loops by consistently checking user permissions across all components in the patient registration flow.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for patient registration routes and verify they're protected
echo "Searching for patient registration routes..."
rg -l "facility/\$\{.*\}/patient" --type ts --type tsx

echo "Searching for navigation to patient registration..."
rg "navigate\(.*facility.*patient" --type ts --type tsx

Length of output: 381


Script:

#!/bin/bash
# Search for patient registration routes and verify they're protected
echo "Searching for patient registration routes..."
rg -l "facility.*patient"

echo "Searching for navigation to patient registration..."
rg "navigate.*facility.*patient" -A 2

Length of output: 5813


Script:

#!/bin/bash
# Check the PatientRegister component for authorization checks
echo "Checking PatientRegister component for auth checks..."
rg "isAuthorized|user_type|authUser" src/components/Patient/PatientRegister.tsx -B 2 -A 2

# Check ManagePatients component for auth checks
echo "Checking ManagePatients component for auth checks..."
rg "isAuthorized|user_type|authUser" src/components/Patient/ManagePatients.tsx -B 2 -A 2

# Check router configuration for patient routes
echo "Checking router protection..."
rg "PatientRegister|patient" src/Routers/routes/PatientRoutes.tsx -B 2 -A 2

Length of output: 4653

Comment on lines 160 to 182
const isAuthorizedToRegisterPatientsterAuth = () => {
const showAllFacilityUsers = ["DistrictAdmin", "StateAdmin"];
if (
!showAllFacilityUsers.includes(authUser.user_type) &&
authUser.home_facility_object?.id === facilityId
) {
return true;
}
if (
authUser.user_type === "DistrictAdmin" &&
authUser.district === facilityData?.district
) {
return true;
}
if (
authUser.user_type === "StateAdmin" &&
authUser.state === facilityData?.state
) {
return true;
}

return false;
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Function implementation needs improvements

The authorization function has several issues that should be addressed:

  1. The function name contains a typo: "PatientsterAuth" should be "PatientsAuth"
  2. The array name showAllFacilityUsers is misleading as it's used for authorization checks
  3. The first condition's logic can be simplified
  4. Type safety improvements needed for user types

Consider applying these improvements:

-const isAuthorizedToRegisterPatientsterAuth = () => {
-  const showAllFacilityUsers = ["DistrictAdmin", "StateAdmin"];
-  if (
-    !showAllFacilityUsers.includes(authUser.user_type) &&
-    authUser.home_facility_object?.id === facilityId
-  ) {
-    return true;
-  }
+const isAuthorizedToRegisterPatientsAuth = () => {
+  type AdminType = "DistrictAdmin" | "StateAdmin";
+  const adminUserTypes: AdminType[] = ["DistrictAdmin", "StateAdmin"];
+
+  // Regular users can only register in their home facility
+  if (authUser.home_facility_object?.id === facilityId) {
+    return true;
+  }
+
+  // Admins have extended privileges
+  if (!adminUserTypes.includes(authUser.user_type as AdminType)) {
+    return false;
+  }

   if (
     authUser.user_type === "DistrictAdmin" &&
-    authUser.district === facilityData?.district
+    authUser.district === facilityData?.district_object?.id
   ) {
     return true;
   }
   if (
     authUser.user_type === "StateAdmin" &&
-    authUser.state === facilityData?.state
+    authUser.state === facilityData?.state_object?.id
   ) {
     return true;
   }

   return false;
 };

Committable suggestion skipped: line range outside the PR's diff.

@nihal467
Copy link
Member

nihal467 commented Nov 6, 2024

@JavidSumra iam seeing changes suggested by ai, look into that as well

@nihal467
Copy link
Member

nihal467 commented Nov 6, 2024

@JavidSumra
image

we already have this auth defined in the code base, so use that rather than duplicating it :)

@github-actions github-actions bot added the Deploy-Failed Deplyment is not showing preview label Nov 6, 2024
…f github.com:JavidSumra/care_fe into issues/8988/fix-infinite-rendering-non-home-facility
@rithviknishad rithviknishad removed the Deploy-Failed Deplyment is not showing preview label Nov 6, 2024
@github-actions github-actions bot added the Deploy-Failed Deplyment is not showing preview label Nov 7, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 088f675 and 7976cea.

📒 Files selected for processing (1)
  • src/components/Patient/PatientRegister.tsx (4 hunks)
🔇 Additional comments (1)
src/components/Patient/PatientRegister.tsx (1)

1877-1903: Verify authorization implementation consistency.

Based on the PR comments mentioning existing authorization checks, let's verify:

  1. If this implementation duplicates existing authorization logic
  2. If this function is used consistently across all patient registration points
✅ Verification successful

Authorization implementation is consistent and well-integrated

The verification reveals that:

  1. The PatientRegisterAuth function follows existing authorization patterns in the codebase, similar to those in permissions.ts and AuthorizedChild.tsx
  2. It's properly integrated in both PatientRegister.tsx and FacilityHome.tsx components
  3. The implementation aligns with the existing role-based access control system using user_type checks
  4. No duplicate authorization logic was found for patient registration
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for existing authorization checks and patient registration points

# Test 1: Look for existing authorization checks
echo "Searching for existing authorization checks..."
rg -l "isAuthorized|canAccess|hasPermission|checkPermission" --type ts --type tsx

# Test 2: Look for patient registration components/routes
echo "Searching for patient registration components..."
rg -l "PatientRegister|addPatient|registerPatient" --type ts --type tsx

# Test 3: Look for facility access checks
echo "Searching for facility access checks..."
rg "facility.*access|access.*facility" --type ts --type tsx

Length of output: 602


Script:

#!/bin/bash
# Description: Search for existing authorization checks and patient registration points

# Test 1: Look for existing authorization checks
echo "Searching for existing authorization checks..."
rg -l "isAuthorized|canAccess|hasPermission|checkPermission"

# Test 2: Look for patient registration components/routes
echo "Searching for patient registration components..."
rg -l "PatientRegister|addPatient|registerPatient"

# Test 3: Look for facility access checks
echo "Searching for facility access checks..."
rg "facility.*access|access.*facility"

# Test 4: Look for similar authorization patterns
echo "Searching for similar authorization patterns..."
rg "user_type.*=.*(\"|').*Admin(\"|')"

# Test 5: Look for usage of PatientRegisterAuth
echo "Searching for PatientRegisterAuth usage..."
rg "PatientRegisterAuth"

Length of output: 4319


Script:

#!/bin/bash
# Let's examine the existing authorization implementations

# Check AuthorizedChild implementation
echo "Checking AuthorizedChild implementation..."
cat src/CAREUI/misc/AuthorizedChild.tsx

# Check permissions.ts implementation
echo "Checking permissions.ts implementation..."
cat src/Utils/permissions.ts

# Check FacilityHome usage context
echo "Checking FacilityHome usage context..."
rg -A 5 -B 5 "PatientRegisterAuth" src/components/Facility/FacilityHome.tsx

Length of output: 2955

Comment on lines +925 to +930
if (
!isLoading &&
facilityId &&
facilityObject &&
!PatientRegisterAuth(authUser, facilityObject, facilityId)
) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Use a more appropriate error component for unauthorized access.

Instead of using Error404 which indicates a missing resource, consider using a dedicated unauthorized access component or error message that clearly communicates the authorization issue to the user.

Example implementation:

-  if (
-    !isLoading &&
-    facilityId &&
-    facilityObject &&
-    !PatientRegisterAuth(authUser, facilityObject, facilityId)
-  ) {
-    return <Error404 />;
-  }
+  if (
+    !isLoading &&
+    facilityId &&
+    facilityObject &&
+    !PatientRegisterAuth(authUser, facilityObject, facilityId)
+  ) {
+    return (
+      <div className="text-center">
+        <h1 className="text-2xl font-bold text-red-600">Unauthorized Access</h1>
+        <p>You are not authorized to register patients in this facility.</p>
+      </div>
+    );
+  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (
!isLoading &&
facilityId &&
facilityObject &&
!PatientRegisterAuth(authUser, facilityObject, facilityId)
) {
if (
!isLoading &&
facilityId &&
facilityObject &&
!PatientRegisterAuth(authUser, facilityObject, facilityId)
) {
return (
<div className="text-center">
<h1 className="text-2xl font-bold text-red-600">Unauthorized Access</h1>
<p>You are not authorized to register patients in this facility.</p>
</div>
);
}

Comment on lines +1877 to +1903
export function PatientRegisterAuth(
authUser: UserModel,
facilityObject: FacilityModel | undefined,
facilityId: string,
) {
const showAllFacilityUsers = ["DistrictAdmin", "StateAdmin"];
if (
!showAllFacilityUsers.includes(authUser.user_type) &&
authUser.home_facility_object?.id === facilityId
) {
return true;
}
if (
authUser.user_type === "DistrictAdmin" &&
authUser.district === facilityObject?.district
) {
return true;
}
if (
authUser.user_type === "StateAdmin" &&
authUser.state === facilityObject?.state
) {
return true;
}

return false;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve the PatientRegisterAuth function implementation.

The function needs several improvements for better maintainability and type safety:

  1. Add return type annotation and JSDoc documentation
  2. Move constants outside function
  3. Simplify logic with early returns
+const FACILITY_ADMIN_TYPES = ["DistrictAdmin", "StateAdmin"] as const;
+
+/**
+ * Checks if a user is authorized to register patients in a specific facility
+ * @param authUser - The authenticated user
+ * @param facilityObject - The facility to check authorization for
+ * @param facilityId - The ID of the facility
+ * @returns boolean indicating if the user is authorized
+ */
-export function PatientRegisterAuth(
+export function PatientRegisterAuth(
   authUser: UserModel,
   facilityObject: FacilityModel | undefined,
   facilityId: string,
-) {
-  const showAllFacilityUsers = ["DistrictAdmin", "StateAdmin"];
-  if (
-    !showAllFacilityUsers.includes(authUser.user_type) &&
-    authUser.home_facility_object?.id === facilityId
-  ) {
-    return true;
-  }
-  if (
-    authUser.user_type === "DistrictAdmin" &&
-    authUser.district === facilityObject?.district
-  ) {
-    return true;
-  }
-  if (
-    authUser.user_type === "StateAdmin" &&
-    authUser.state === facilityObject?.state
-  ) {
-    return true;
-  }
-
-  return false;
+): boolean {
+  // Regular users can only access their home facility
+  if (!FACILITY_ADMIN_TYPES.includes(authUser.user_type)) {
+    return authUser.home_facility_object?.id === facilityId;
+  }
+
+  // District admins can access facilities in their district
+  if (authUser.user_type === "DistrictAdmin") {
+    return authUser.district === facilityObject?.district;
+  }
+
+  // State admins can access facilities in their state
+  if (authUser.user_type === "StateAdmin") {
+    return authUser.state === facilityObject?.state;
+  }
+
+  return false;
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function PatientRegisterAuth(
authUser: UserModel,
facilityObject: FacilityModel | undefined,
facilityId: string,
) {
const showAllFacilityUsers = ["DistrictAdmin", "StateAdmin"];
if (
!showAllFacilityUsers.includes(authUser.user_type) &&
authUser.home_facility_object?.id === facilityId
) {
return true;
}
if (
authUser.user_type === "DistrictAdmin" &&
authUser.district === facilityObject?.district
) {
return true;
}
if (
authUser.user_type === "StateAdmin" &&
authUser.state === facilityObject?.state
) {
return true;
}
return false;
}
const FACILITY_ADMIN_TYPES = ["DistrictAdmin", "StateAdmin"] as const;
/**
* Checks if a user is authorized to register patients in a specific facility
* @param authUser - The authenticated user
* @param facilityObject - The facility to check authorization for
* @param facilityId - The ID of the facility
* @returns boolean indicating if the user is authorized
*/
export function PatientRegisterAuth(
authUser: UserModel,
facilityObject: FacilityModel | undefined,
facilityId: string,
): boolean {
// Regular users can only access their home facility
if (!FACILITY_ADMIN_TYPES.includes(authUser.user_type)) {
return authUser.home_facility_object?.id === facilityId;
}
// District admins can access facilities in their district
if (authUser.user_type === "DistrictAdmin") {
return authUser.district === facilityObject?.district;
}
// State admins can access facilities in their state
if (authUser.user_type === "StateAdmin") {
return authUser.state === facilityObject?.state;
}
return false;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
changes required Deploy-Failed Deplyment is not showing preview
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Infinite Rendering and Redirection to 'not-found' Page When Adding Patient from Non-Home Facility
3 participants