Skip to content

Conversation

@drtechie
Copy link
Member

@drtechie drtechie commented May 23, 2025

πŸ“‹ Description

JIRA ID:

Please provide a summary of the change and the motivation behind it. Include relevant context and details.


βœ… Type of Change

  • 🐞 Bug fix (non-breaking change which resolves an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • πŸ”₯ Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • πŸ›  Refactor (change that is neither a fix nor a new feature)
  • βš™οΈ Config change (configuration file or build script updates)
  • πŸ“š Documentation (updates to docs or readme)
  • πŸ§ͺ Tests (adding new or updating existing tests)
  • 🎨 UI/UX (changes that affect the user interface)
  • πŸš€ Performance (improves performance)
  • 🧹 Chore (miscellaneous changes that don't modify src or test files)

ℹ️ Additional Information

Please describe how the changes were tested, and include any relevant screenshots, logs, or other information that provides additional context.

Summary by CodeRabbit

  • New Features
    • Improved authentication by supporting JWT token retrieval from multiple sources (headers and cookies) during login.
    • Added ability to retrieve user service role mappings for enhanced role management.
  • Enhancements
    • Streamlined user authentication response, consolidating user privilege and mapping logic for a more consistent experience.
    • Added null checks to prevent errors during user role mapping processing.

@drtechie drtechie requested a review from ravishanigarapu May 23, 2025 09:30
@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 23, 2025

## Walkthrough

The changes update the authentication flow in `IEMRAdminController` to support retrieving JWT tokens from multiple sources (headers and cookies) and refactor response preparation into a helper method. Additionally, a new utility method is added in `JwtUtil` to extract the user ID from a JWT token. The user service interface and implementation were updated to expose user service role mappings publicly.

## Changes

| File(s)                                                                                 | Summary                                                                                                               |
|-----------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------|
| `src/main/java/com/iemr/common/controller/users/IEMRAdminController.java`               | Enhanced `getLoginResponse` to support JWT retrieval from headers/cookies, added helper for response preparation, added null checks, minor comment update. |
| `src/main/java/com/iemr/common/utils/JwtUtil.java`                                      | Added `getUserIdFromToken(String token)` to extract user ID from JWT token.                                           |
| `src/main/java/com/iemr/common/service/users/IEMRAdminUserService.java`                 | Added method declaration `getUserServiceRoleMapping(Long userID)` to retrieve user service role mappings.              |
| `src/main/java/com/iemr/common/service/users/IEMRAdminUserServiceImpl.java`             | Changed `getUserServiceRoleMapping(Long userID)` method access from private to public without changing implementation. |

## Sequence Diagram(s)

```mermaid
sequenceDiagram
    participant Client
    participant IEMRAdminController
    participant JwtUtil
    participant UserService

    Client->>IEMRAdminController: getLoginResponse(request)
    alt Authorization header present
        IEMRAdminController->>SessionService: getSession(Authorization)
        SessionService-->>IEMRAdminController: Session object
        IEMRAdminController->>Client: Return session-based response
    else Authorization header missing
        IEMRAdminController->>Request: Get Jwttoken header or jwtToken cookie
        alt JWT token found
            IEMRAdminController->>JwtUtil: getUserIdFromToken(token)
            JwtUtil-->>IEMRAdminController: userId
            IEMRAdminController->>UserService: getUser(userId)
            UserService-->>IEMRAdminController: User object
            IEMRAdminController->>IEMRAdminController: prepareAuthenticationResponse(User, remoteAddress, remoteHost)
            IEMRAdminController->>Client: Return authentication response
        else No JWT token found
            IEMRAdminController->>Client: Throw exception (token missing)
        end
    end

Suggested reviewers

  • ravishanigarapu

Poem

In the warren of code, a token hops in,
From headers or cookies, it’s sure to begin.
With helpers to guide it, and claims to decode,
The user’s now mapped on a much smoother road.
πŸ₯• For every new login, the journey’s less grim!


<!-- walkthrough_end -->

<!-- announcements_start -->

> [!NOTE]
> <details>
> <summary>⚑️ AI Code Reviews for VS Code, Cursor, Windsurf</summary>
> 
> CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
> Learn more [here](http://coderabbit.ai/ide).
> 
> </details>

<!-- announcements_end -->

---

<details>
<summary>πŸ“œ Recent review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**
**Plan: Pro**


<details>
<summary>πŸ“₯ Commits</summary>

Reviewing files that changed from the base of the PR and between 265e911f47eaccf887ffce7105c96443d6ac3708 and 268fd39e99093adb1fbca806ab35ccd5de26b5d3.

</details>

<details>
<summary>πŸ“’ Files selected for processing (1)</summary>

* `src/main/java/com/iemr/common/controller/users/IEMRAdminController.java` (3 hunks)

</details>

<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary>

* src/main/java/com/iemr/common/controller/users/IEMRAdminController.java

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (3)</summary>

* GitHub Check: Analyze (java)
* GitHub Check: Package-test
* GitHub Check: Build

</details>

</details>
<!-- internal state start -->


<!-- DwQgtGAEAqAWCWBnSTIEMB26CuAXA9mAOYCmGJATmriQCaQDG+Ats2bgFyQAOFk+AIwBWJBrngA3EsgEBPRvlqU0AgfFwA6NPEgQAfACgjoCEYDEZyAAUASpETZWaCrKNwSPbABsvkCiQBHbGlcSHFcLzpIACIAM3gADy4yB39IUlCvfCJ4LH9EbnwMRA9uNEQS5Ap4IlhQ/MLikmjIAHdy+2wBZnUaejkw2A9sEr5aChoGBA8O20gMRwFKSAAmAAYARhQsXCHrAGUAWRsASQB6AGEWZiKwAEErE78SQsR1fBcNGD2lRAZq7jiIrbWjwBjUaSDaiDVBTTCkFDINCQATYIiQeIJdDwNj0aH5fBeCS5dGYREODz+LwQ+gEQYeLI5PLSRolSCwTC0Lwkr7uHC7D7sjrMZwAayiuw8cIwCI6yIwtwE/jQopJKLRGMSXwAcvh7NxRPB4gxIAApE42O6QE4AEX4YxIuG0kXoTAwNASoXayF4+GJSloXzutFBQIwaF8uViHxFYfQAnweDCITVgoc3EKEzVJH9ZAYHgcU3QyD+/hSsHwuGQgsZyG980r2wYXmwAe29Mgv3+8EB8CKvL2c2jDBGkOBKWw1RlUNCksgbAF9AaRTeAkiGMFgiduTVc8ZuWeBRXlMdk+KHaYFH8YkPrJmyFyNAwAY0Rn0xnAUDI9HwsX5hFIcgqD6BRWHYLheH4YRRHEKQZHkJglCoVR1C0HR3xMKA4FQVAyTQPAALIZQQKYMD3S4KhWk6JwXBRBDFGUF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hFcaCXcSQACRsBsLEM8e8QoQwLEA8TCQifmO8RsGsHcQwACWCc8dcbQL8R7Nce8WsA8axIYEMaCQ8bELQNcQCZiQCWsACdcelAIDiQIOCJCYyQINcVSUiXcUoKCQIAqdceyRxFAFsbgDsbQHsQcWXHQISt+OyUAA -->

<!-- internal state end -->
<!-- finishing_touch_checkbox_start -->

<details open="true">
<summary>✨ Finishing Touches</summary>

- [ ] <!-- {"checkboxId": "7962f53c-55bc-4827-bfbf-6a18da830691"} --> πŸ“ Generate Docstrings

</details>

<!-- finishing_touch_checkbox_end -->
<!-- tips_start -->

---

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

<details>
<summary>❀️ Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<details>
<summary>πŸͺ§ Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=PSMRI/Common-API&utm_content=201):

- Review comments: Directly reply to a review comment made by CodeRabbit. Example:
  - `I pushed a fix in commit <commit_id>, please review it.`
  - `Explain this complex logic.`
  - `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 explain this code block.`
  -	`@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 explain its main purpose.`
  - `@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.`

### Support

Need help? Create a ticket on our [support page](https://www.coderabbit.ai/contact-us/support) for assistance with any issues or questions.

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 generate docstrings` to [generate docstrings](https://docs.coderabbit.ai/finishing-touches/docstrings) for this PR.
- `@coderabbitai generate sequence diagram` to generate a sequence diagram of the changes in this 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](https://docs.coderabbit.ai/guides/configure-coderabbit) 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](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->

Copy link
Contributor

@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: 3

🧹 Nitpick comments (1)
src/main/java/com/iemr/common/controller/users/IEMRAdminController.java (1)

212-213: Remove or clarify the incomplete comment.

The comment // responseObj ==> helper appears to be an incomplete TODO or reminder. Either remove it or provide a meaningful comment explaining the intent.

-			// responseObj ==> helper
-
πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 71f4013 and 3c58342.

πŸ“’ Files selected for processing (2)
  • src/main/java/com/iemr/common/controller/users/IEMRAdminController.java (3 hunks)
  • src/main/java/com/iemr/common/utils/JwtUtil.java (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: style-check / checkstyle
  • GitHub Check: Package-test
  • GitHub Check: Analyze (java)
  • GitHub Check: Build
πŸ”‡ Additional comments (1)
src/main/java/com/iemr/common/controller/users/IEMRAdminController.java (1)

1104-1128: Good refactoring to reduce code duplication!

The extraction of response preparation logic into a separate helper method improves code maintainability and reduces duplication across authentication methods.

Comment on lines +93 to +96
public String getUserIdFromToken(String token) {
return getAllClaimsFromToken(token).get("userId", String.class);
}

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for token validation and missing claims.

The method should handle potential exceptions and validate that the userId claim exists before returning it. Consider wrapping in try-catch or documenting the expected exceptions.

Apply this diff to add error handling:

 public String getUserIdFromToken(String token) {
-    return getAllClaimsFromToken(token).get("userId", String.class);
+    try {
+        Claims claims = getAllClaimsFromToken(token);
+        String userId = claims.get("userId", String.class);
+        if (userId == null || userId.isEmpty()) {
+            throw new IllegalArgumentException("JWT token does not contain userId claim");
+        }
+        return userId;
+    } catch (Exception e) {
+        throw new IllegalArgumentException("Failed to extract userId from token", e);
+    }
 }
πŸ“ 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
public String getUserIdFromToken(String token) {
return getAllClaimsFromToken(token).get("userId", String.class);
}
public String getUserIdFromToken(String token) {
try {
Claims claims = getAllClaimsFromToken(token);
String userId = claims.get("userId", String.class);
if (userId == null || userId.isEmpty()) {
throw new IllegalArgumentException("JWT token does not contain userId claim");
}
return userId;
} catch (Exception e) {
throw new IllegalArgumentException("Failed to extract userId from token", e);
}
}
πŸ€– Prompt for AI Agents
In src/main/java/com/iemr/common/utils/JwtUtil.java around lines 93 to 96, the
method getUserIdFromToken lacks error handling for invalid tokens or missing
userId claims. Modify the method to wrap the claim extraction in a try-catch
block to handle exceptions from token parsing, and check if the userId claim is
present before returning it. If the claim is missing or an exception occurs,
handle it appropriately, such as returning null or throwing a custom exception,
and document the behavior or exceptions thrown.

Comment on lines +506 to +512
if (jwtToken == null) {
throw new IEMRException("No authentication token found in header or cookie");
}

// Extract user ID from the JWT token
String userId = jwtUtil.getUserIdFromToken(jwtToken);

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Validate JWT token before extracting userId.

The code extracts userId from the JWT token without validating it first. This could lead to security issues if an invalid or expired token is provided.

Add JWT validation before extracting the userId:

 if (jwtToken == null) {
     throw new IEMRException("No authentication token found in header or cookie");
 }
 
+// Validate the JWT token first
+Claims claims = jwtUtil.validateToken(jwtToken);
+if (claims == null) {
+    throw new IEMRException("Invalid or expired JWT token");
+}
+
 // Extract user ID from the JWT token
 String userId = jwtUtil.getUserIdFromToken(jwtToken);
πŸ“ 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 (jwtToken == null) {
throw new IEMRException("No authentication token found in header or cookie");
}
// Extract user ID from the JWT token
String userId = jwtUtil.getUserIdFromToken(jwtToken);
if (jwtToken == null) {
throw new IEMRException("No authentication token found in header or cookie");
}
// Validate the JWT token first
Claims claims = jwtUtil.validateToken(jwtToken);
if (claims == null) {
throw new IEMRException("Invalid or expired JWT token");
}
// Extract user ID from the JWT token
String userId = jwtUtil.getUserIdFromToken(jwtToken);
πŸ€– Prompt for AI Agents
In src/main/java/com/iemr/common/controller/users/IEMRAdminController.java
around lines 506 to 512, the JWT token is used to extract the userId without
validating the token first. To fix this, add a validation step using jwtUtil to
check if the token is valid and not expired before calling getUserIdFromToken.
If the token is invalid, throw an appropriate exception to prevent further
processing with an invalid token.

String authHeader = request.getHeader("Authorization");
if (authHeader == null) {
// Try JWT token from header first
String jwtToken = request.getHeader("Jwttoken");
Copy link
Contributor

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Use consistent header naming convention.

The header name "Jwttoken" should follow a consistent naming convention. Consider using "JWT-Token", "JwtToken", or "Authorization" with "Bearer" prefix as per standard practices.

-				String jwtToken = request.getHeader("Jwttoken");
+				String jwtToken = request.getHeader("JwtToken");
πŸ€– Prompt for AI Agents
In src/main/java/com/iemr/common/controller/users/IEMRAdminController.java at
line 491, the header name "Jwttoken" is inconsistent with standard naming
conventions. Update the header name to a consistent and standard format such as
"Authorization" and handle the token with the "Bearer" prefix, or alternatively
use "JWT-Token" or "JwtToken" to align with common practices.

@sonarqubecloud
Copy link

@ravishanigarapu ravishanigarapu merged commit 10a0608 into develop May 23, 2025
6 checks passed
This was referenced May 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants