Skip to content

Conversation

@helenKaryamsetty
Copy link
Member

@helenKaryamsetty helenKaryamsetty commented Jan 30, 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

    • Added configuration for ABHA V3 APIs across different environments.
    • Introduced new methods for user login verification and web login PHR card retrieval.
    • Added a new service implementation for generating and retrieving ABHA authentication tokens.
  • Improvements

    • Updated authentication mechanism for public key retrieval by incorporating an authentication token.
    • Enhanced error handling and logging practices in the authentication process.
    • Standardized configuration entries for ABHA V3 services across development, test, and example environments.
    • Simplified code structure by utilizing Lombok annotations for data classes.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 30, 2025

Walkthrough

This pull request introduces configuration entries for ABHA V3 APIs across multiple environment properties files and updates the CertificateKeyService interface and its implementations. The changes primarily focus on adding new authentication endpoints for ABHA V3 and modifying methods to include an authentication token when retrieving public keys. Additional methods for user profile verification and web login functionality are also introduced, enhancing the overall ABHA authentication and key retrieval process.

Changes

File Change Summary
src/main/environment/*.properties Added new configuration entries for ABHA V3 user authentication and profile verification in common_ci.properties, common_dev.properties, common_example.properties, and common_test.properties
src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyService.java Updated getCertPublicKey() method signature to include String ndhmAuthToken parameter
src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyServiceImpl.java Modified getCertPublicKey() to handle ndhmAuthToken, including enhanced request handling and response processing
src/main/java/com/wipro/fhir/service/v3/abha/*ServiceImpl.java Updated method calls to getCertPublicKey() to pass the abhaAuthToken
src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java Added new methods for profile login verification and web login PHR card retrieval, updated authentication token handling
src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java Introduced printWebLoginPhrCard method for handling web login PHR card requests
src/main/java/com/wipro/fhir/data/v3/abhaCard/VerifyProfileUserLogin.java Added new class VerifyProfileUserLogin with fields for ABHA login information
src/main/java/com/wipro/fhir/service/v3/abha/GenerateAuthSessionService.java Introduced new interface for generating and retrieving ABHA authentication tokens
src/main/java/com/wipro/fhir/service/v3/abha/GenerateAuthSessionServiceImpl.java Implemented the new service for handling authentication token generation and retrieval

Possibly related PRs

  • Abdm M1 V3 ChangesΒ #52: The changes in the main PR are related to those in the retrieved PR as both involve modifications to the common_ci.properties file, specifically adding new configuration entries for ABHA V3 APIs, including user authentication and profile verification endpoints.
  • ABHA - Address Search API changesΒ #56: The changes in the main PR are related to the addition of new configuration entries for ABHA V3 APIs, while the retrieved PR also adds new properties for web login functionality in the same configuration file, indicating a direct connection in terms of modifications to the same properties related to ABHA API functionality.
  • AMM-871 Abdm Facility fetch services changesΒ #46: The changes in the main PR, which add new configuration entries related to the ABHA V3 APIs in the common_ci.properties file, are related to the retrieved PR as both involve modifications to the same file and introduce new properties for API endpoints, although they focus on different aspects of the API.

Suggested reviewers

  • ravishanigarapu

Poem

🐰 Hopping through code with glee,
ABHA V3 keys set free!
Authentication's new dance,
With tokens giving us a chance,
Rabbit's code hops with delight! πŸ”‘

✨ Finishing Touches
  • πŸ“ Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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
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: 0

πŸ”­ Outside diff range comments (8)
src/main/environment/common_ci.properties (2)

Line range hint 88-98: Standardize environment variable usage across V3 API configurations.

The configuration shows inconsistent usage of environment variables. Some endpoints use @env.ABDM_BASE_URL@ while others use direct URLs. This could make environment management more difficult.

Consider using environment variables consistently:

abdmV3UserAuthenticate = @env.ABDM_BASE_URL@/api/hiecm/gateway/v3/sessions
-getAuthCertPublicKey = @env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/cert
-requestOtpForEnrollment = @env.ABDM_BASE_URL@/abha/api/v3/enrollment/request/otp
-abhaEnrollByAadhaar = @env.ABDM_BASE_URL@/abha/api/v3/enrollment/enrol/byAadhaar
-printAbhaCard = @env.ABDM_BASE_URL@/abha/api/v3/profile/account/abha-card
-abhaLoginRequestOtp = @env.ABDM_BASE_URL@/abha/api/v3/profile/login/request/otp
-verifyAbhaLogin = @env.ABDM_BASE_URL@/abha/api/v3/profile/login/verify
+getAuthCertPublicKey = @env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/cert
+requestOtpForEnrollment = @env.ABDM_V3_BASE_URL@/abha/api/v3/enrollment/request/otp
+abhaEnrollByAadhaar = @env.ABDM_V3_BASE_URL@/abha/api/v3/enrollment/enrol/byAadhaar
+printAbhaCard = @env.ABDM_V3_BASE_URL@/abha/api/v3/profile/account/abha-card
+abhaLoginRequestOtp = @env.ABDM_V3_BASE_URL@/abha/api/v3/profile/login/request/otp
+verifyAbhaLogin = @env.ABDM_V3_BASE_URL@/abha/api/v3/profile/login/verify

Line range hint 88-98: Ensure consistent environment usage across ABHA V3 endpoints.

The configuration mixes production and sandbox environments:

  • abdmV3UserAuthenticate uses production URL (dev.abdm.gov.in)
  • Other endpoints use sandbox URLs (abhasbx.abdm.gov.in)

This inconsistency could lead to authentication issues in the CI environment.

Consider using environment variables consistently:

-abdmV3UserAuthenticate = @env.ABDM_BASE_URL@/api/hiecm/gateway/v3/sessions
-getAuthCertPublicKey = @env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/cert
-requestOtpForEnrollment = @env.ABDM_BASE_URL@/abha/api/v3/enrollment/request/otp
+abdmV3UserAuthenticate = @env.ABDM_V3_BASE_URL@/api/hiecm/gateway/v3/sessions
+getAuthCertPublicKey = @env.ABDM_V3_BASE_URL@/api/v1/auth/cert
+requestOtpForEnrollment = @env.ABDM_V3_BASE_URL@/abha/api/v3/enrollment/request/otp
src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java (3)

Line range hint 106-111: Enhance error handling for encryption operations.

The encryption of loginId should have proper error handling to prevent potential security vulnerabilities. Consider adding specific exception handling for encryption failures.

-            publicKeyString = certificateKeyService.getCertPublicKey(ndhmAuthToken);
-            if (loginMethod.getLoginId() != null) {
-                encryptedLoginId = encryption.encrypt(loginMethod.getLoginId(), publicKeyString);
+            try {
+                publicKeyString = certificateKeyService.getCertPublicKey(ndhmAuthToken);
+                if (loginMethod.getLoginId() == null) {
+                    throw new FHIRException("Login ID cannot be null");
+                }
+                encryptedLoginId = encryption.encrypt(loginMethod.getLoginId(), publicKeyString);
+            } catch (Exception e) {
+                logger.error("Failed to encrypt login ID", e);
+                throw new FHIRException("Failed to secure your data. Please try again.");

Also applies to: 174-179, 265-270


Line range hint 89-90: Consider using a dedicated HTTP client configuration.

The class creates new RestTemplate instances for each request. Consider using a configured RestTemplate bean with proper timeout and retry settings.

+    @Value("${rest.template.timeout:5000}")
+    private int timeout;
+
+    @Bean
+    public RestTemplate restTemplate() {
+        RestTemplate restTemplate = new RestTemplate();
+        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
+        factory.setConnectTimeout(timeout);
+        factory.setReadTimeout(timeout);
+        restTemplate.setRequestFactory(factory);
+        return restTemplate;
+    }
+
     @Override
     public String getOtpForEnrollment(String request) throws FHIRException {
         String res = null;
         Map<String, String> responseMap = new HashMap<>();
-        RestTemplate restTemplate = new RestTemplate();
+        RestTemplate restTemplate = restTemplate();

Also applies to: 91-92


Line range hint 428-429: Improve error handling in constructHealthIdResponse.

The method assumes that all required fields are present in the JSON response. Consider adding null checks and proper error handling.

     private void constructHealthIdResponse(HealthIDResponse healthIDResp, JsonObject profile) throws ParseException {
-        healthIDResp.setHealthIdNumber(profile.get("ABHANumber").getAsString());
+        if (!profile.has("ABHANumber")) {
+            throw new FHIRException("ABHA number is missing in the response");
+        }
+        healthIDResp.setHealthIdNumber(profile.get("ABHANumber").getAsString());
+
+        if (!profile.has("phrAddress")) {
+            throw new FHIRException("PHR address is missing in the response");
+        }
         JsonArray phrAddressArray = profile.getAsJsonArray("phrAddress");

Also applies to: 430-431

src/main/environment/common_example.properties (1)

Line range hint 91-97: Use environment variables instead of hardcoded URLs in example configuration.

The example configuration contains hardcoded URLs which may become outdated. Consider using placeholder variables to maintain consistency with other environment files and make updates easier.

Apply this change:

-abdmV3UserAuthenticate = https://dev.abdm.gov.in/api/hiecm/gateway/v3/sessions
-getAuthCertPublicKey = https://healthidsbx.abdm.gov.in/api/v1/auth/cert
-requestOtpForEnrollment = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/request/otp
+abdmV3UserAuthenticate = @env.ABDM_V3_BASE_URL@/api/hiecm/gateway/v3/sessions
+getAuthCertPublicKey = @env.ABDM_V3_BASE_URL@/api/v1/auth/cert
+requestOtpForEnrollment = @env.ABDM_V3_BASE_URL@/abha/api/v3/enrollment/request/otp
src/main/environment/common_dev.properties (1)

Line range hint 88-98: Avoid mixing production and sandbox URLs in development environment.

The configuration uses both production (dev.abdm.gov.in) and sandbox (abhasbx.abdm.gov.in) URLs. This mixing of environments could lead to unexpected behavior during development and testing.

Consider using consistent sandbox URLs for the development environment:

-abdmV3UserAuthenticate = https://dev.abdm.gov.in/api/hiecm/gateway/v3/sessions
+abdmV3UserAuthenticate = https://abhasbx.abdm.gov.in/api/hiecm/gateway/v3/sessions
src/main/environment/common_test.properties (1)

Standardize test environment URLs to use sandbox endpoints consistently

The review comment is correct. The test configuration file mixes development and sandbox URLs, which could lead to integration issues. This is particularly concerning given that abhaMode=sbx indicates sandbox environment should be used.

URLs that need to be changed to sandbox endpoints:

  • abdmV3UserAuthenticate: Change from dev to sandbox
  • ndhmuserAuthenticate: Change from dev to sandbox
  • generateOTPForCareContext: Change from dev to sandbox
  • validateOTPForCareContext: Change from dev to sandbox
  • generateABDM_NotifySMS: Change from dev to sandbox
  • getAbdmFacilityServicies: Change from dev to sandbox

All ABDM endpoints in the test environment should consistently use the sandbox domain (abhasbx.abdm.gov.in or healthidsbx.abdm.gov.in) to ensure proper integration testing.

πŸ”— Analysis chain

Line range hint 88-98: Standardize environment configuration for test environment.

Similar to the development environment, the test configuration mixes production and sandbox URLs. Additionally, consider adding validation for these endpoints in the test suite.

  1. Standardize URLs to use sandbox environment:
-abdmV3UserAuthenticate = https://dev.abdm.gov.in/api/hiecm/gateway/v3/sessions
+abdmV3UserAuthenticate = https://abhasbx.abdm.gov.in/api/hiecm/gateway/v3/sessions
  1. Verify the endpoints with this script:
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all ABHA V3 endpoints are accessible in test environment

echo "Checking ABHA V3 endpoints accessibility..."
for endpoint in \
    "https://abhasbx.abdm.gov.in/api/hiecm/gateway/v3/sessions" \
    "https://abhasbx.abdm.gov.in/api/v1/auth/cert" \
    "https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/request/otp"
do
    response=$(curl -s -o /dev/null -w "%{http_code}" $endpoint)
    if [ $response -eq 000 ]; then
        echo "Warning: Endpoint $endpoint is not accessible"
    fi
done

Length of output: 386


Script:

#!/bin/bash
# Search for different environment URLs in property files
echo "Checking for environment URLs in property files..."
echo -e "\nFiles containing 'dev.abdm.gov.in':"
rg "dev\.abdm\.gov\.in" --type properties

echo -e "\nFiles containing 'abhasbx.abdm.gov.in':"
rg "abhasbx\.abdm\.gov\.in" --type properties

echo -e "\nFiles containing other ABDM domains:"
rg "abdm\.gov\.in" --type properties | grep -v "dev\." | grep -v "abhasbx\."

Length of output: 669


Script:

#!/bin/bash
# Find all .properties files and search for ABDM URLs
echo "Searching .properties files for ABDM URLs..."

# Find all .properties files
properties_files=$(fd -e properties)

if [ -n "$properties_files" ]; then
    echo -e "\nFiles containing 'dev.abdm.gov.in':"
    echo "$properties_files" | xargs grep -l "dev.abdm.gov.in" 2>/dev/null

    echo -e "\nFiles containing 'abhasbx.abdm.gov.in':"
    echo "$properties_files" | xargs grep -l "abhasbx.abdm.gov.in" 2>/dev/null

    echo -e "\nFull content of common_test.properties:"
    cat src/main/environment/common_test.properties 2>/dev/null
else
    echo "No .properties files found"
fi

Length of output: 6923

🧹 Nitpick comments (4)
src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyServiceImpl.java (1)

45-54: Centralize header creation and reuse across multiple calls.
You are repeatedly building headers with similar entries. Consider extracting a helper method that populates standard headersβ€”improving consistency and reducing the risk of missing or duplicating headers in other parts of the code.

src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java (3)

106-106: Consider caching the public key to reduce API calls.

The getCertPublicKey method is called multiple times with the same ndhmAuthToken. Consider caching the public key for a specific token to avoid redundant API calls, while ensuring proper cache invalidation when the token expires.

@Service
public class CreateAbhaV3ServiceImpl implements CreateAbhaV3Service {
+    private Map<String, CachedPublicKey> publicKeyCache = new ConcurrentHashMap<>();
+
+    @Value("${public.key.cache.duration:300000}")  // 5 minutes default
+    private long publicKeyCacheDuration;
+
+    private String getCachedPublicKey(String ndhmAuthToken) {
+        CachedPublicKey cached = publicKeyCache.get(ndhmAuthToken);
+        if (cached != null && !cached.isExpired()) {
+            return cached.getKey();
+        }
+        String newKey = certificateKeyService.getCertPublicKey(ndhmAuthToken);
+        publicKeyCache.put(ndhmAuthToken, new CachedPublicKey(newKey, publicKeyCacheDuration));
+        return newKey;
+    }
+
+    private static class CachedPublicKey {
+        private final String key;
+        private final long expiryTime;
+
+        public CachedPublicKey(String key, long cacheDuration) {
+            this.key = key;
+            this.expiryTime = System.currentTimeMillis() + cacheDuration;
+        }
+
+        public String getKey() {
+            return key;
+        }
+
+        public boolean isExpired() {
+            return System.currentTimeMillis() > expiryTime;
+        }
+    }

Also applies to: 174-174, 265-265


Line range hint 63-67: Refactor timestamp generation to reduce code duplication.

The timestamp generation logic is duplicated across multiple methods. Consider extracting it into a utility method.

+    private String generateUTCTimestamp() {
+        TimeZone tz = TimeZone.getTimeZone("UTC");
+        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
+        df.setTimeZone(tz);
+        return df.format(new Date());
+    }
+
     @Override
     public String getOtpForEnrollment(String request) throws FHIRException {
         // ...
-        TimeZone tz = TimeZone.getTimeZone("UTC");
-        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
-        df.setTimeZone(tz);
-        String nowAsISO = df.format(new Date());
+        String nowAsISO = generateUTCTimestamp();

Also applies to: 156-160, 252-256


Line range hint 58-59: Consider using constructor injection for required dependencies.

The class has multiple required dependencies that are autowired. Consider using constructor injection to make dependencies explicit and improve testability.

 @Service
 public class CreateAbhaV3ServiceImpl implements CreateAbhaV3Service {
-    @Autowired
-    private GenerateSession_NDHMService generateSession_NDHM;
-    @Autowired
-    private Common_NDHMService common_NDHMService;
-    @Autowired
-    HttpUtils httpUtils;
-    @Autowired
-    Encryption encryption;
-    @Autowired
-    HealthIDRepo healthIDRepo;
-    @Autowired
-    CertificateKeyService certificateKeyService;
+    private final GenerateSession_NDHMService generateSession_NDHM;
+    private final Common_NDHMService common_NDHMService;
+    private final HttpUtils httpUtils;
+    private final Encryption encryption;
+    private final HealthIDRepo healthIDRepo;
+    private final CertificateKeyService certificateKeyService;
+
+    public CreateAbhaV3ServiceImpl(
+            GenerateSession_NDHMService generateSession_NDHM,
+            Common_NDHMService common_NDHMService,
+            HttpUtils httpUtils,
+            Encryption encryption,
+            HealthIDRepo healthIDRepo,
+            CertificateKeyService certificateKeyService) {
+        this.generateSession_NDHM = generateSession_NDHM;
+        this.common_NDHMService = common_NDHMService;
+        this.httpUtils = httpUtils;
+        this.encryption = encryption;
+        this.healthIDRepo = healthIDRepo;
+        this.certificateKeyService = certificateKeyService;
+    }

Also applies to: 61-62

πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 7fe11c4 and 82f88e6.

πŸ“’ Files selected for processing (8)
  • src/main/environment/common_ci.properties (1 hunks)
  • src/main/environment/common_dev.properties (1 hunks)
  • src/main/environment/common_example.properties (1 hunks)
  • src/main/environment/common_test.properties (1 hunks)
  • src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyService.java (1 hunks)
  • src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyServiceImpl.java (1 hunks)
  • src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java (3 hunks)
  • src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java (2 hunks)
🧰 Additional context used
πŸ““ Learnings (1)
src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java (1)
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#52
File: src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java:84-91
Timestamp: 2024-12-09T16:01:39.809Z
Learning: In the `requestOtpForAbhaLogin` and `verifyAbhaLogin` methods of `LoginAbhaV3ServiceImpl.java`, `loginId` is mandatory, but even if it is null, the process can proceed without input validation.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (java)
πŸ”‡ Additional comments (4)
src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyServiceImpl.java (2)

40-40: Validate the authorization token's presence and format.
The updated method signature includes ndhmAuthToken. Consider validating that the token is neither null nor empty before proceeding, to avoid unexpected NullPointerException or authentication failures.


58-63: πŸ› οΈ Refactor suggestion

Check for missing 'publicKey' field and non-200 status codes.
Currently, the code retrieves publicKey assuming it always exists in the response for a 200 status. If the field is missing or the status code differs, the method returns null without logging or throwing an exception. This could lead to unhandled null references downstream. Consider rigorous error handling and logging for non-200 responses or malformed responses.

src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyService.java (1)

7-7: Document the new parameter in the interface.
The ndhmAuthToken parameter changes the contract. Update the method’s documentation to explain the usage and necessity of this token so that implementations and consumers can properly comply.

src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java (1)

93-93: πŸ› οΈ Refactor suggestion

Possibility of null or empty login IDs and tokens.
Lines 93 and 184 now retrieve the public key via getCertPublicKey(ndhmAuthToken), but there is no explicit validation of ndhmAuthToken, nor is there a guard against a null or empty loginId. If loginId is null or empty, encryption and subsequent processes could fail without clear error messages.

Also applies to: 184-184

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 (6)
src/main/java/com/wipro/fhir/data/v3/abhaCard/VerifyProfileUserLogin.java (1)

8-9: Follow Java naming conventions for fields.

The field ABHANumber should be renamed to abhaNumber to follow Java naming conventions for instance variables (camelCase).

-	private String ABHANumber;
+	private String abhaNumber;
src/main/java/com/wipro/fhir/data/healthID/Authorize.java (1)

28-30: Add access modifiers and validation annotations.

Fields should have explicit access modifiers and could benefit from validation annotations:

-String clientId;
-String clientSecret;
-String grantType;
+@NotBlank(message = "Client ID is required")
+private String clientId;
+@NotBlank(message = "Client Secret is required")
+private String clientSecret;
+@NotBlank(message = "Grant Type is required")
+private String grantType;

Don't forget to add the import:

import jakarta.validation.constraints.NotBlank;
src/main/java/com/wipro/fhir/service/v3/abha/GenerateAuthSessionService.java (1)

5-11: Add method documentation.

Consider adding Javadoc to describe the purpose, parameters, return values, and exceptions of each method:

 public interface GenerateAuthSessionService {
 
+	/**
+	 * Generates a new ABHA authentication token.
+	 * 
+	 * @return The generated authentication token
+	 * @throws FHIRException if token generation fails
+	 */
 	String generateAbhaAuthToken() throws FHIRException;
 
+	/**
+	 * Retrieves the current ABHA authentication token.
+	 * 
+	 * @return The current authentication token
+	 * @throws FHIRException if token retrieval fails
+	 */
 	String getAbhaAuthToken() throws FHIRException;
 
 }
src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java (1)

68-85: Fix typo in log message and consider adding request logging.

The implementation looks good but has a minor typo in the log message ("respponse"). Also, consider adding request logging for consistency with other methods.

Apply this diff to fix the typo and add request logging:

 @CrossOrigin
 @Operation(summary = "Print PHR card - abha address web login")
 @PostMapping(value = { "/printWebLoginPhrCard" })
 public String printWebLoginPhrCard(@RequestBody String request) {
+    logger.info("Print PHR card for ABHA web login API request " + request);
     OutputResponse response = new OutputResponse();
     try {
         if (request != null) {
             String s = loginAbhaV3Service.getWebLoginPhrCard(request);
             response.setResponse(s);
         } else
             throw new FHIRException("NDHM_FHIR Empty request object");
     } catch (FHIRException e) {
         response.setError(5000, e.getMessage());
         logger.error(e.toString());
     }
-    logger.info("NDHM_FHIR generate OTP for ABHA card API respponse " + response.toString());
+    logger.info("NDHM_FHIR print PHR card for ABHA web login API response " + response.toString());
     return response.toString();
 }
src/main/java/com/wipro/fhir/data/healthID/HealthIDResponse.java (1)

130-131: Consider adding @expose annotation for consistency.

The new field isNewAbha should follow the same pattern as other fields in the class.

Apply this diff to add the @expose annotation:

+	@Expose
 	@Column(name = "isNewAbha")
 	private Boolean isNewAbha;
src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java (1)

105-137: Reduce repetitive conditional blocks.
The if-else chain performing multiple checks on loginMethod and loginHint could be simplified using a mapping or a helper function. This approach can improve maintainability and readability.

πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 82f88e6 and 114cfff.

πŸ“’ Files selected for processing (14)
  • src/main/environment/common_ci.properties (1 hunks)
  • src/main/environment/common_dev.properties (1 hunks)
  • src/main/environment/common_example.properties (1 hunks)
  • src/main/environment/common_test.properties (1 hunks)
  • src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java (0 hunks)
  • src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java (1 hunks)
  • src/main/java/com/wipro/fhir/data/healthID/Authorize.java (1 hunks)
  • src/main/java/com/wipro/fhir/data/healthID/HealthIDResponse.java (2 hunks)
  • src/main/java/com/wipro/fhir/data/v3/abhaCard/VerifyProfileUserLogin.java (1 hunks)
  • src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java (10 hunks)
  • src/main/java/com/wipro/fhir/service/v3/abha/GenerateAuthSessionService.java (1 hunks)
  • src/main/java/com/wipro/fhir/service/v3/abha/GenerateAuthSessionServiceImpl.java (1 hunks)
  • src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3Service.java (1 hunks)
  • src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java (11 hunks)
πŸ’€ Files with no reviewable changes (1)
  • src/main/java/com/wipro/fhir/controller/v3/abha/CreateAbhaV3Controller.java
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/main/environment/common_test.properties
  • src/main/environment/common_ci.properties
  • src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java
🧰 Additional context used
🧠 Learnings (4)
src/main/java/com/wipro/fhir/data/v3/abhaCard/VerifyProfileUserLogin.java (1)
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#57
File: src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java:242-251
Timestamp: 2025-01-07T12:49:16.294Z
Learning: The ABDM API response for user verification has a fixed structure where "accounts" and "users" arrays are guaranteed to contain data when present, making null/empty checks unnecessary. This is part of the API contract with ABDM.
src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3Service.java (2)
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#52
File: src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java:84-91
Timestamp: 2024-12-09T16:01:39.809Z
Learning: In the `requestOtpForAbhaLogin` and `verifyAbhaLogin` methods of `LoginAbhaV3ServiceImpl.java`, `loginId` is mandatory, but even if it is null, the process can proceed without input validation.
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#57
File: src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java:242-251
Timestamp: 2025-01-07T12:49:16.294Z
Learning: The ABDM API response for user verification has a fixed structure where "accounts" and "users" arrays are guaranteed to contain data when present, making null/empty checks unnecessary. This is part of the API contract with ABDM.
src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java (1)
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#52
File: src/main/java/com/wipro/fhir/controller/v3/abha/LoginAbhaV3Controller.java:18-20
Timestamp: 2024-12-09T16:09:31.513Z
Learning: In the Java Spring Boot project, all controllers, including `LoginAbhaV3Controller.java` at `src/main/java/com/wipro/fhir/controller/v3/abha/`, use the `@CrossOrigin` annotation without parameters to maintain consistency across the codebase.
src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java (3)
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#57
File: src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java:242-251
Timestamp: 2025-01-07T12:49:16.294Z
Learning: The ABDM API response for user verification has a fixed structure where "accounts" and "users" arrays are guaranteed to contain data when present, making null/empty checks unnecessary. This is part of the API contract with ABDM.
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#52
File: src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java:84-91
Timestamp: 2024-12-09T16:01:39.809Z
Learning: In the `requestOtpForAbhaLogin` and `verifyAbhaLogin` methods of `LoginAbhaV3ServiceImpl.java`, `loginId` is mandatory, but even if it is null, the process can proceed without input validation.
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#58
File: src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java:0-0
Timestamp: 2025-01-09T12:17:11.789Z
Learning: In the FHIR-API project's ABDM integration, complete responseEntity logging is preferred over just status codes for better debugging capabilities, particularly in the LoginAbhaV3ServiceImpl class when handling ABDM API responses.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (java)
πŸ”‡ Additional comments (7)
src/main/java/com/wipro/fhir/data/v3/abhaCard/VerifyProfileUserLogin.java (1)

1-6: LGTM!

Good use of Lombok's @Data annotation to reduce boilerplate code.

src/main/java/com/wipro/fhir/data/healthID/Authorize.java (1)

24-26: LGTM!

Good use of Lombok's @Data annotation to reduce boilerplate code.

src/main/environment/common_example.properties (1)

91-101: LGTM! Configuration entries are consistent.

The new ABHA V3 API endpoints are properly configured and consistent with other environment files.

src/main/java/com/wipro/fhir/data/healthID/HealthIDResponse.java (1)

34-34: LGTM! Good use of Lombok to reduce boilerplate code.

Using Lombok's @DaTa annotation is a good practice to reduce boilerplate code and improve maintainability.

Also applies to: 39-39

src/main/java/com/wipro/fhir/service/v3/abha/GenerateAuthSessionServiceImpl.java (2)

35-36: Be cautious with static fields in a multi-threaded environment.
Storing the token and expiry time in static fields may cause concurrency conflicts if multiple requests attempt to update or read these fields. Consider using thread-safe data structures or injecting a scoped bean to avoid potential race conditions.

Would you like me to generate a script to search for concurrent usage across the codebase, ensuring no unexpected writes happen from other threads?


85-86:

Details

βœ… Verification successful

Verify the unit of the expiresIn field.
You're assuming expiresIn is in seconds and dividing by 60 to determine minutes, which seems correct for many APIs. However, confirm the API's documentation to ensure this is indeed the intended unit.


🌐 Web query:

Is the "expiresIn" field returned by the ABHA authentication endpoint specified in seconds?

πŸ’‘ Result:

The "expiresIn" field returned by authentication endpoints like those in ABHA (Ayushman Bharat Health Account) systems follows the OAuth2 standard where time durations are specified in seconds [1][9]. This aligns with:

  1. OAuth2 specifications (RFC 6749) that explicitly define expires_in as "the lifetime in seconds of the access token" [1][9]
  2. ABDM sandbox documentation showing example values like "expiresIn": 1200 (equivalent to 20 minutes) [4][8]
  3. Token management patterns where time intervals for access tokens are universally measured in seconds across authentication systems [5][9]

For ABHA-specific implementations:

  • The /token endpoint responses include this field when returning access tokens for API authorization [3][7]
  • Refresh token lifetimes (e.g., refreshExpiresIn) also use second-based values in ABDM systems [4][8]

Citations:


ABHA "expiresIn" Field Unit Confirmed
The ABHA authentication endpoint adheres to the OAuth2 standard, so the expiresIn field is indeed specified in seconds. Dividing this value by 60 to convert it to minutes is correct. No changes are needed.

  • File: src/main/java/com/wipro/fhir/service/v3/abha/GenerateAuthSessionServiceImpl.java (Lines 85-86)
src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java (1)

82-83: Good move to use the new getAbhaAuthToken method.
Switching to generateAuthSessionService for token retrieval streamlines the authentication flow and ensures consistency across the codebase.

Comment on lines +11 to +14
String verifyProfileLoginUser(String tToken, String txnId, String abhaNumber) throws FHIRException;

String getWebLoginPhrCard(String reqObj) throws FHIRException;

Copy link
Contributor

Choose a reason for hiding this comment

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

πŸ’‘ Verification agent

❓ Verification inconclusive

Add method documentation and consider parameter validation.

Consider adding Javadoc and parameter validation:

+	/**
+	 * Verifies the user profile during login.
+	 * 
+	 * @param tToken The authentication token
+	 * @param txnId The transaction ID
+	 * @param abhaNumber The ABHA number
+	 * @return The verification result
+	 * @throws FHIRException if verification fails
+	 */
 	String verifyProfileLoginUser(String tToken, String txnId, String abhaNumber) throws FHIRException;
 
+	/**
+	 * Retrieves the web login PHR card.
+	 * 
+	 * @param reqObj The request object
+	 * @return The PHR card data
+	 * @throws FHIRException if retrieval fails
+	 */
 	String getWebLoginPhrCard(String reqObj) throws FHIRException;

Based on the retrieved learnings about input validation, verify if parameter validation is needed for these new methods:


🏁 Script executed:

#!/bin/bash
# Description: Check if parameter validation is implemented in the service implementation.

# Search for validation annotations or null checks
rg -A 5 "verifyProfileLoginUser|getWebLoginPhrCard" | rg "@NotNull|@NotBlank|Objects.requireNonNull"

Length of output: 102


Action: Enhance documentation and enforce parameter validation.

It appears that neither Javadoc comments nor explicit parameter validations (e.g. using annotations such as @NotNull, @NotBlank or calls like Objects.requireNonNull) are present in the service implementations for the methods below. Please add comprehensive method documentation and incorporate input validation to ensure robustness. For example:

+	/**
+	 * Verifies the user profile during login.
+	 * 
+	 * @param tToken The authentication token (must not be null).
+	 * @param txnId The transaction ID (must not be null).
+	 * @param abhaNumber The ABHA number (must not be null).
+	 * @return The verification result.
+	 * @throws FHIRException if verification fails.
+	 */
 	String verifyProfileLoginUser(String tToken, String txnId, String abhaNumber) throws FHIRException;
 	
+	/**
+	 * Retrieves the web login PHR card.
+	 * 
+	 * @param reqObj The request object (must not be null).
+	 * @return The PHR card data.
+	 * @throws FHIRException if retrieval fails.
+	 */
 	String getWebLoginPhrCard(String reqObj) throws FHIRException;

Based on our initial search output showing no evidence of validation patterns in the related implementations, please review and add the necessary validations.

πŸ“ 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
String verifyProfileLoginUser(String tToken, String txnId, String abhaNumber) throws FHIRException;
String getWebLoginPhrCard(String reqObj) throws FHIRException;
/**
* Verifies the user profile during login.
*
* @param tToken The authentication token (must not be null).
* @param txnId The transaction ID (must not be null).
* @param abhaNumber The ABHA number (must not be null).
* @return The verification result.
* @throws FHIRException if verification fails.
*/
String verifyProfileLoginUser(String tToken, String txnId, String abhaNumber) throws FHIRException;
/**
* Retrieves the web login PHR card.
*
* @param reqObj The request object (must not be null).
* @return The PHR card data.
* @throws FHIRException if retrieval fails.
*/
String getWebLoginPhrCard(String reqObj) throws FHIRException;

Comment on lines 98 to 99
webLoginAbhaVerify = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/verify
webLoginAbhaVerify = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/verify
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

Remove duplicate property definition.

The property webLoginAbhaVerify is defined twice with the same value. Remove one of the duplicate entries to avoid confusion.

Apply this diff to remove the duplicate:

 webLoginAbhaVerify = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/verify
-webLoginAbhaVerify = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/verify
πŸ“ 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
webLoginAbhaVerify = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/verify
webLoginAbhaVerify = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/verify
webLoginAbhaVerify = https://abhasbx.abdm.gov.in/abha/api/v3/phr/web/login/abha/verify

Comment on lines 125 to 131
} else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())
&& "mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())) {
reqOtpEnrollment.setScope(new String[] { "abha-login", "mobile-verify" });
reqOtpEnrollment.setLoginHint("mobile");
reqOtpEnrollment.setOtpSystem("abdm");
} else if ("aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) && "aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) ) {
} else if ("aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())
&& "aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())) {
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

Fix confusing repeated condition.
The checks at lines 125–131 compare loginMethod with the same string on both sides, causing dead code. They likely should be comparing loginMethod with "mobile" or "aadhaar" and loginHint with "mobile" or "aadhaar".

Apply this diff to correct the conditions:

} else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())
-        && "mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())) {
+        && "mobile".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) {
  reqOtpEnrollment.setScope(new String[] { "abha-login", "mobile-verify" });
  reqOtpEnrollment.setLoginHint("mobile");
  reqOtpEnrollment.setOtpSystem("abdm");
} else if ("aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())
-        && "aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())) {
+        && "aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) {
  reqOtpEnrollment.setScope(new String[] { "abha-login", "aadhaar-verify" });
  reqOtpEnrollment.setLoginHint("aadhaar");
  reqOtpEnrollment.setOtpSystem("aadhaar");
} else {
πŸ“ 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
} else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())
&& "mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())) {
reqOtpEnrollment.setScope(new String[] { "abha-login", "mobile-verify" });
reqOtpEnrollment.setLoginHint("mobile");
reqOtpEnrollment.setOtpSystem("abdm");
} else if ("aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) && "aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod()) ) {
} else if ("aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())
&& "aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())) {
} else if ("mobile".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())
&& "mobile".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) {
reqOtpEnrollment.setScope(new String[] { "abha-login", "mobile-verify" });
reqOtpEnrollment.setLoginHint("mobile");
reqOtpEnrollment.setOtpSystem("abdm");
} else if ("aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginMethod())
&& "aadhaar".equalsIgnoreCase(loginAbhaRequest.getLoginHint())) {
reqOtpEnrollment.setScope(new String[] { "abha-login", "aadhaar-verify" });
reqOtpEnrollment.setLoginHint("aadhaar");
reqOtpEnrollment.setOtpSystem("aadhaar");
} else {

@sonarqubecloud
Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
1 Security Hotspot
19.8% Duplication on New Code (required ≀ 3%)
C Reliability Rating on New Code (required β‰₯ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

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: 0

🧹 Nitpick comments (3)
src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java (3)

282-325: New user profile verification implementation.

The new verifyProfileLoginUser method implements the verification process for profile logins with proper token handling. The implementation follows the same pattern as other methods in the class.

Consider extracting the repetitive header setup code into a helper method to reduce duplication across all methods.

+ private MultiValueMap<String, String> createStandardHeaders(String authToken) {
+     MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
+     headers.add("Content-Type", MediaType.APPLICATION_JSON.toString());
+     headers.add("REQUEST-ID", UUID.randomUUID().toString());
+     
+     TimeZone tz = TimeZone.getTimeZone("UTC");
+     DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
+     df.setTimeZone(tz);
+     String nowAsISO = df.format(new Date());
+     headers.add("TIMESTAMP", nowAsISO);
+     headers.add("Authorization", authToken);
+     
+     return headers;
+ }

328-373: New PHR card retrieval implementation.

The new getWebLoginPhrCard method properly handles the PHR card retrieval process with appropriate token handling and error management. Note that the success condition checks for status code 202 (Accepted) rather than 200 (OK), which appears to be specific to this API.

Consider adding more detailed error information in the thrown exception to assist with debugging:

- throw new FHIRException(e.getMessage());
+ throw new FHIRException("Error retrieving web login PHR card: " + e.getMessage());

314-319: Incorrect log message.

The log message indicates "response otp for Abha login" but this method is for profile verification. Update the log message to match the actual operation.

- logger.info("ABDM response for response otp for Abha login: " + responseEntity);
+ logger.info("ABDM response for verify profile user login: " + responseEntity);
πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between e67eca9 and cf66e78.

πŸ“’ Files selected for processing (2)
  • src/main/environment/common_dev.properties (1 hunks)
  • src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java (11 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/environment/common_dev.properties
🧰 Additional context used
🧠 Learnings (1)
src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java (3)
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#57
File: src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java:242-251
Timestamp: 2025-01-07T12:49:16.294Z
Learning: The ABDM API response for user verification has a fixed structure where "accounts" and "users" arrays are guaranteed to contain data when present, making null/empty checks unnecessary. This is part of the API contract with ABDM.
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#52
File: src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java:84-91
Timestamp: 2024-12-09T16:01:39.809Z
Learning: In the `requestOtpForAbhaLogin` and `verifyAbhaLogin` methods of `LoginAbhaV3ServiceImpl.java`, `loginId` is mandatory, but even if it is null, the process can proceed without input validation.
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#58
File: src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java:0-0
Timestamp: 2025-01-09T12:17:11.789Z
Learning: In the FHIR-API project's ABDM integration, complete responseEntity logging is preferred over just status codes for better debugging capabilities, particularly in the LoginAbhaV3ServiceImpl class when handling ABDM API responses.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (java)
πŸ”‡ Additional comments (8)
src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java (8)

45-45: New authentication flow and endpoints integrated.

The update introduces new ABHA V3 authentication mechanisms and profile verification functionality:

  • Switched to GenerateAuthSessionService for authentication tokens
  • Added new configuration properties for profile login verification and web PHR card endpoints
  • Added VerifyProfileUserLogin import for user verification

These changes align with the new authentication flow described in the PR summary.

Also applies to: 34-35, 65-69


83-83: Authentication mechanism updated correctly.

The method now uses generateAuthSessionService.getAbhaAuthToken() instead of the previous NDHM token service, and correctly passes the token to the certificate key service. This is a consistent change throughout the authentication flow.

Also applies to: 94-94, 99-99


105-137: Previously identified condition bug fixed.

The login method and login hint conditions have been fixed to compare the correct values, resolving the duplicate condition issue identified in previous reviews.


143-148: Endpoint selection based on login hint.

Good implementation of conditional logic to select the appropriate endpoint based on the login hint value, enabling the service to handle both ABHA number and ABHA address authentication flows.


179-179: Authentication mechanism consistently updated.

The consistent use of the new authentication token service throughout the class improves maintainability and follows the updated authentication pattern.

Also applies to: 189-189, 194-194


228-233: Web login verification endpoint selection.

The conditional logic to select between web login and standard verification endpoints based on the login method is now properly implemented, supporting different authentication flows.


245-256: Enhanced token retrieval for mobile login.

The implementation now includes profile login verification for mobile authentication method, enhancing the security flow. Based on the retrieved learnings, the code correctly handles ABDM API responses without unnecessary null checks for accounts array.


359-366:

Details

βœ… Verification successful

Check HTTP response status code.

The success condition checks for HTTP status code 202 (Accepted) rather than the more common 200 (OK). Verify that this is the expected response code from the ABHA API for this operation.


🏁 Script executed:

#!/bin/bash
# Description: Search for other status code checks in the codebase to verify consistency

# Check for other status code patterns in the codebase
echo "Checking for status code handling patterns in the codebase..."
rg "getStatusCode\(\) == HttpStatusCode\.valueOf\(20[0-9]\)" -A 2 -B 2

Length of output: 6725


Review Verification: HTTP 202 for Print Abha Card Confirmed

The code consistently checks for a 202 (Accepted) response when handling the print Abha card response in both the LoginAbhaV3ServiceImpl and CreateAbhaV3ServiceImpl classes. This differs from other endpointsβ€”which use 200 (OK)β€”and suggests that the ABHA API is expected to return 202 for print card operations. Please confirm that the ABHA API specification defines 202 as the success response for this action. If confirmed, no changes are needed; however, consider documenting this behavior inline for clarity.

Copy link
Contributor

@ravishanigarapu ravishanigarapu left a comment

Choose a reason for hiding this comment

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

looks fine

@ravishanigarapu ravishanigarapu merged commit b47be0f into PSMRI:develop Feb 26, 2025
6 of 7 checks passed
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.

2 participants