-
Notifications
You must be signed in to change notification settings - Fork 49
fix: ensure get login response passes right response #201
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
Conversation
## 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
endSuggested reviewers
Poem
|
There was a problem hiding this 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 ==> helperappears 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
π 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.
| public String getUserIdFromToken(String token) { | ||
| return getAllClaimsFromToken(token).get("userId", String.class); | ||
| } | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
| 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.
| 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); | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
| 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"); |
There was a problem hiding this comment.
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.
|



π Description
JIRA ID:
Please provide a summary of the change and the motivation behind it. Include relevant context and details.
β Type of Change
βΉοΈ 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