Skip to content

Conversation

@jaypanchal-13
Copy link
Contributor

Product Description

Api call for credentials and insert data in credential table
ticket -> https://dimagi.atlassian.net/browse/CCCT-1337

Technical Summary

Feature Flag

Safety Assurance

Safety story

Automated test coverage

QA Plan

Labels and Review

  • Do we need to enhance the manual QA test coverage ? If yes, the "QA Note" label is set correctly
  • Does the PR introduce any major changes worth communicating ? If yes, the "Release Note" label is set and a "Release Note" is specified in PR description.
  • Risk label is set correctly
  • The set of people pinged as reviewers is appropriate for the level of risk of the change

@coderabbitai
Copy link

coderabbitai bot commented Jun 18, 2025

📝 Walkthrough

Walkthrough

This change introduces a new API flow for retrieving personal ID credentials. It adds a retrieveCredentials method to both the ApiPersonalId and PersonalIdApiHandler classes, enabling clients to initiate a credential retrieval process using a username and password. A new API endpoint constant and a corresponding Retrofit interface method are defined for the /users/credentials endpoint. The response is parsed by a new PersonalIdCredentialParser class, which processes the returned credentials, separates valid and corrupt entries, clears existing stored credentials, and saves the valid ones to persistent storage.

Sequence Diagram(s)

sequenceDiagram
    participant UI/Caller
    participant PersonalIdApiHandler
    participant ApiPersonalId
    participant ApiService
    participant PersonalIdCredentialParser
    participant Storage

    UI/Caller->>PersonalIdApiHandler: retrieveCredentials(context, userName, password)
    PersonalIdApiHandler->>ApiPersonalId: retrieveCredentials(context, userName, password, callback)
    ApiPersonalId->>ApiService: retrieveCredentials(token)
    ApiService-->>ApiPersonalId: Response (JSON with credentials)
    ApiPersonalId-->>PersonalIdApiHandler: Callback with response
    PersonalIdApiHandler->>PersonalIdCredentialParser: parse(json, sessionData)
    PersonalIdCredentialParser->>Storage: Clear all credentials
    PersonalIdCredentialParser->>Storage: Write valid credentials
Loading

Possibly related PRs

Suggested reviewers

  • OrangeAndGreen
  • pm-dimagi
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in Comment
  • Commit Unit Tests in branch CCCT-1337-retrieve-credential-api-call

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.

❤️ 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.
    • 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 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 for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for 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 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

@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

🧹 Nitpick comments (4)
app/src/org/commcare/connect/network/connectId/ApiEndPoints.java (1)

19-19: Use consistent constant naming (connectCredentialsURL)

All other endpoint constants follow the pattern connectXyzURL or at least end with URL.
Sticking to the same convention prevents confusion and makes grepping easier.

-    public static final String credentials = "/users/credentials";
+    public static final String connectCredentialsURL = "/users/credentials";
app/src/org/commcare/connect/network/connectId/ApiService.java (1)

35-36: Update reference if constant is renamed

If you rename the constant per previous comment, remember to adjust the annotation here:

-    @POST(ApiEndPoints.credentials)
+    @POST(ApiEndPoints.connectCredentialsURL)
app/src/org/commcare/connect/network/ApiPersonalId.java (1)

335-340: Add null-safety guard for tokenAuth to match surrounding methods

All other helpers (addOrVerifyName, validateFirebaseIdToken, …) validate the generated credential string.
Doing the same here keeps the behaviour uniform and avoids a possible NPE if HttpUtils.getCredential unexpectedly returns null.

-        String tokenAuth = HttpUtils.getCredential(authInfo);
+        String tokenAuth = HttpUtils.getCredential(authInfo);
+        Objects.requireNonNull(tokenAuth, "Failed to create Authorization header");
app/src/org/commcare/connect/network/parser/PersonalIdCredentialParser.java (1)

25-31: Batch writes inside a transaction & log corrupt entries

For large credential sets, writing one row at a time outside a transaction can be slow.
Also, corrupt credentials are silently dropped; logging them helps troubleshooting.

-        storage.removeAll();
-
-        // Save valid credentials
-        for (PersonalIdCredential credential : parseResult.getValidCredentials()) {
-            storage.write(credential);
-        }
+        storage.removeAll();
+        storage.beginTransaction();
+        try {
+            for (PersonalIdCredential credential : parseResult.getValidCredentials()) {
+                storage.write(credential);
+            }
+            storage.commitTransaction();
+        } finally {
+            storage.endTransaction();
+        }
+
+        if (!parseResult.getCorruptCredentials().isEmpty()) {
+            Logger.log("API Warning",
+                    parseResult.getCorruptCredentials().size() + " corrupt credentials skipped");
+        }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 491f498 and c898a56.

📒 Files selected for processing (5)
  • app/src/org/commcare/connect/network/ApiPersonalId.java (1 hunks)
  • app/src/org/commcare/connect/network/PersonalIdApiHandler.java (3 hunks)
  • app/src/org/commcare/connect/network/connectId/ApiEndPoints.java (1 hunks)
  • app/src/org/commcare/connect/network/connectId/ApiService.java (1 hunks)
  • app/src/org/commcare/connect/network/parser/PersonalIdCredentialParser.java (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Lint Code Base
🔇 Additional comments (3)
app/src/org/commcare/connect/network/connectId/ApiService.java (1)

35-36: Confirm verb & path – consider switching to @GET or supplying body

retrieveCredentials is declared as a POST with no body.
If the server is performing a read-only operation, a GET (or at least an empty @FormUrlEncoded body) would be semantically clearer.
Please double-check the backend contract.

No action needed if the endpoint explicitly expects POST /users/credentials with no payload.

app/src/org/commcare/connect/network/PersonalIdApiHandler.java (1)

163-167: sessionData created here is empty – verify consumer expectations

retrieveCredentials instantiates a fresh PersonalIdSessionData, but the credential parser doesn’t populate it, so the object passed to onSuccess() carries no useful state.
If downstream code expects tokens or flags inside sessionData, this will lead to NPEs or logic errors.

Please ensure either
a) the parser populates sessionData, or
b) the handler’s consumers do not assume anything inside it.

app/src/org/commcare/connect/network/ApiPersonalId.java (1)

335-335: Constructor overload differs from existing calls

Elsewhere in the file you call new AuthInfo.ProvidedAuth(user, pass, false).
Here the 2-arg overload is used. If the third parameter controls Base64 wrapping or other security behaviour, the call might deviate from expectations.

Double-check the correct overload (or add a clarifying comment).

callApi(context, call, callback);
}

public static void retrieveCredentials(Context context, String userName, String password, IApiCallback callback) {
Copy link
Contributor

Choose a reason for hiding this comment

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

naming is not clear to me

Copy link
Contributor

Choose a reason for hiding this comment

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

why not ?

Copy link
Contributor

Choose a reason for hiding this comment

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

for me its sounds like incomplete name retriveCredentials of what

Copy link
Contributor

Choose a reason for hiding this comment

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

i accept we are referring everywhere as credential only but it sounds incomplete

Copy link
Contributor

Choose a reason for hiding this comment

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

i accept we are referring everywhere as credential only but it sounds incomplete

public static final String connectClaimJobURL = "https://%s/api/opportunity/%d/claim";
public static final String connectDeliveriesURL = "https://%s/api/opportunity/%d/delivery_progress";
public static final String connectPaymentConfirmationURL = "https://%s/api/payment/%s/confirm";
public static final String credentials = "/users/credentials";
Copy link
Contributor

Choose a reason for hiding this comment

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

variable name should reflect the apiendpoint name

Copy link
Contributor

@shubham1g5 shubham1g5 Jun 20, 2025

Choose a reason for hiding this comment

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

this should use Java Const formatting like CREDENTIALS (would be nice to correct other constants in this class as well in a different PR)

Copy link
Contributor

Choose a reason for hiding this comment

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

@pm-dimagi I don't get your comment, it seems to be following the right naming as per the API endpoint.

Copy link
Contributor

Choose a reason for hiding this comment

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

may be i read it something wrong

// Get storage for this model
SqlStorage<PersonalIdCredential> storage =
CommCareApplication.instance().getUserStorage(PersonalIdCredential.class);

Copy link
Contributor

Choose a reason for hiding this comment

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

we can also create the wokerhistoryDb helper class which will perform all the datatbase related queries from there like ConnectUserDatabaseUtil

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@pm-dimagi SqlStorage is also a helper class why to create extra filtration for it as it is used only on this place

Copy link
Contributor

Choose a reason for hiding this comment

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

@jaypanchal-13 Even I am not sure but putting it here so others (Shubham/Dave) can comment.
Better/mandatory to use?

CommCareApplication.instance().getUserStorage(PersonalIdCredential.STORAGE_KEY,PersonalIdCredential.class)

import org.json.JSONException;
import org.json.JSONObject;

public class PersonalIdCredentialParser implements PersonalIdApiResponseParser {
Copy link
Contributor

Choose a reason for hiding this comment

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

@jaypanchal-13 I don't see any reason to implement PersonalIdApiResponseParser. Now, there is no use of PersonalIdSessionData.

Copy link
Contributor

Choose a reason for hiding this comment

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

Agree but think we should have a more generic interface for parsers independent of PersonalIdApiResponseParser

// Get storage for this model
SqlStorage<PersonalIdCredential> storage =
CommCareApplication.instance().getUserStorage(PersonalIdCredential.class);

Copy link
Contributor

Choose a reason for hiding this comment

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

@jaypanchal-13 Even I am not sure but putting it here so others (Shubham/Dave) can comment.
Better/mandatory to use?

CommCareApplication.instance().getUserStorage(PersonalIdCredential.STORAGE_KEY,PersonalIdCredential.class)


public void retrieveCredentials(Context context, String userName, String password) {
PersonalIdSessionData sessionData = new PersonalIdSessionData();
ApiPersonalId.retrieveCredentials(context, userName, password, createCallback(sessionData,
Copy link
Contributor

Choose a reason for hiding this comment

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

@jaypanchal-13 createCallback is instantiating IApiCallback which in turn is sending sessionData on success. I don't think we need sessionData this time. We might need to create some generic ApiCallback which in turn will render the required response.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@Jignesh-dimagi correct instead of creating new callback can we update sessionData nullable in createCallback?
@shubham1g5

Copy link
Contributor

@shubham1g5 shubham1g5 Jun 20, 2025

Choose a reason for hiding this comment

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

we probably should have 2 separate classes here abstracting from one another PersonaIdApiCallback and PersonaIdSessionDataCallback: PersonaIdApiCallback

@Override
public void parse(JSONObject json, PersonalIdSessionData sessionData) throws JSONException {
// Parse credentials array from response
JSONArray credentialsArray = json.getJSONArray("credentials");
Copy link
Contributor

Choose a reason for hiding this comment

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

this might not be present if there are no credentials and we should handle using optJsonArray


// Get storage for this model
SqlStorage<PersonalIdCredential> storage =
CommCareApplication.instance().getUserStorage(PersonalIdCredential.class);
Copy link
Contributor

Choose a reason for hiding this comment

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

PersonalIdCredential is stored in Personal ID database and user storage looks in CommCare user DB, look at how we are writing to other tables in Personal ID database to see the right way to do this.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@shubham1g5 updated this to store in Connect db

@jaypanchal-13 jaypanchal-13 mentioned this pull request Jul 1, 2025
4 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

skip-integration-tests Skip android tests.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants