Skip to content

feat: salesforce connector backend changes#173

Open
snehakumari369 wants to merge 10 commits intodevfrom
1093-Salesforce_Connector_Backend_Changes
Open

feat: salesforce connector backend changes#173
snehakumari369 wants to merge 10 commits intodevfrom
1093-Salesforce_Connector_Backend_Changes

Conversation

@snehakumari369
Copy link

Description

Made required changes in UserResource.java to create a new endpoint for salesforce login and also created a method to get user information in salesforce.

Changes Made

Created different methods for a new endpoint for salesforce login and for getting user info for salesforce.

How to Test

  • Try to login inside an app to test the new endpoint for salesforce login.
  • Now username is getting stored and displayed on salesforce SSO login.

@github-actions
Copy link

@CodiumAI-Agent /describe

@QodoAI-Agent
Copy link

Title

feat: salesforce connector backend changes


User description

Description

Made required changes in UserResource.java to create a new endpoint for salesforce login and also created a method to get user information in salesforce.

Changes Made

Created different methods for a new endpoint for salesforce login and for getting user info for salesforce.

How to Test

  • Try to login inside an app to test the new endpoint for salesforce login.
  • Now username is getting stored and displayed on salesforce SSO login.

PR Type

Enhancement


Description

  • Add Salesforce userinfo endpoint

  • Support DB-driven Salesforce OAuth login

  • Populate Salesforce access token profile

  • Query credentials from SECURITY_DB


Diagram Walkthrough

flowchart LR
  A["/login2/salesforce endpoint"] -- "read uuid" --> B["Query SALESFORCE_CREDENTIALS"]
  B -- "clientId, secret, redirectUri" --> C["Exchange code for token"]
  C -- "SalesforceTokenFiller" --> D["Add access token to session"]
  E["/userinfo/salesforce endpoint"] -- "use session token" --> F["GET /userinfo from Salesforce"]
  F -- "extract name" --> G["Return JSON { name }"]
Loading

File Walkthrough

Relevant files
Enhancement
UserResource.java
Salesforce userinfo and DB-based OAuth login                         

src/prerna/semoss/web/services/local/UserResource.java

  • Add /userinfo/salesforce to return Salesforce user name.
  • Enhance existing Salesforce OAuth to fill token via
    SalesforceTokenFiller.
  • Implement /login2/salesforce using DB-stored credentials by UUID.
  • Add DB queries to SALESFORCE_CREDENTIALS and redirect helper.
+202/-0 

@github-actions
Copy link

@CodiumAI-Agent /review

@QodoAI-Agent
Copy link

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 No relevant tests
🔒 Security concerns

Sensitive information handling:
Ensure that database-stored CLIENTSECRET is handled securely. Although parameterized queries are used, verify that logging does not include secrets (current debug logs print the access token value; avoid logging tokens). Also validate and sanitize the 'uuid' and 'redirect' parameters to prevent open redirect or misuse of credentials selection.

⚡ Recommended focus areas for review

Possible Issue

In userinfoSalesforce, the catch block returns an error message instructing to log into a Microsoft account, which is inconsistent with the Salesforce context and likely confusing to users.

} catch (Exception e) {
	ret.put(Constants.ERROR_MESSAGE, "Log into your Microsoft account");
	return WebUtility.getResponse(ret, 200);
}
Input Validation

The uuid parameter from the request is used directly in DB lookups without explicit validation; ensure it is present, non-empty, and conforms to expected format before querying, and handle missing/invalid cases with clear responses.

        String uuid = request.getParameter("uuid");
        boolean autoAdd = true;

        IRDBMSEngine salesforceDB = (RDBMSNativeEngine) Utility.getDatabase(Constants.SECURITY_DB);
        String query = "SELECT CLIENTID, CLIENTSECRET, REDIRECTURI FROM SALESFORCE_CREDENTIALS WHERE ID = ?";
        try (Connection conn = salesforceDB.makeConnection(); PreparedStatement pstmt = conn.prepareStatement(query)){
        	pstmt.setString(1, uuid);
        	try (ResultSet rs = pstmt.executeQuery()) {
        		if (rs.next()) {
                    clientId = rs.getString("CLIENTID");
                    clientSecret = rs.getString("CLIENTSECRET");
                    redirectUri = rs.getString("REDIRECTURI");
        		}
        	}
        } catch (Exception e) {
			classLogger.error("Error loading Salesforce credentials by UUID ", e);
			throw new SemossPixelException("Error loading Salesforce credentials by UUID ");
		}
Null Handling

After retrieving AccessToken for Salesforce in userinfoSalesforce, code assumes non-null; add null checks to avoid NPE if token retrieval fails or is absent.

AccessToken salesforceToken = semossUser.getAccessToken(AuthProvider.SALESFORCE);
accessString = salesforceToken.getAccess_token();
String url = "https://login.salesforce.com/services/oauth2/userinfo";
Map<String, Object> params = new HashMap<>();
params.put("access_token", accessString);
params.put("alt", "json");

String output = HttpHelperUtility.makeGetCall(url, accessString, params, true);
AccessToken accessToken2 = (AccessToken) BeanFiller.fillFromJson(output, jsonPattern, beanProps,
		new AccessToken());
String name = accessToken2.getName();
ret.put("name", name);
return WebUtility.getResponse(ret, 200);

@github-actions
Copy link

@CodiumAI-Agent /improve

@QodoAI-Agent
Copy link

PR Code Suggestions ✨

CategorySuggestion                                                                                                                                    Impact
Possible issue
Correct mismatched error handling

The error message references Microsoft in the Salesforce userinfo handler, confusing
users and masking true failures. Return a Salesforce-specific message and
appropriate HTTP status. Also log the exception for diagnostics while not exposing
details to the client.

src/prerna/semoss/web/services/local/UserResource.java [439-442]

 } catch (Exception e) {
-	ret.put(Constants.ERROR_MESSAGE, "Log into your Microsoft account");
-	return WebUtility.getResponse(ret, 200);
+	classLogger.error("Failed to fetch Salesforce user info", e);
+	ret.put(Constants.ERROR_MESSAGE, "Log into your Salesforce account");
+	return WebUtility.getResponse(ret, 401);
 }
Suggestion importance[1-10]: 8

__

Why: The catch block in the Salesforce userinfo method incorrectly tells users to log into Microsoft and always returns 200; updating the message to Salesforce and using 401 improves correctness and UX. The improved_code also adds proper logging, aligning with the method’s context.

Medium
Validate required UUID parameter

Validate uuid before using it in DB queries to prevent null or empty values causing
errors or unintended behavior. Reject invalid input early with a clear response and
avoid querying with a bad identifier.

src/prerna/semoss/web/services/local/UserResource.java [1008]

 String uuid = request.getParameter("uuid");
+if (uuid == null || uuid.isEmpty()) {
+    response.setStatus(400);
+    response.getWriter().write("Missing required parameter: uuid");
+    return null;
+}
 ...
 pstmt.setString(1, uuid);
Suggestion importance[1-10]: 7

__

Why: Validating uuid before DB use prevents null/empty inputs and avoids unclear errors; the change is accurate and localized. Impact is moderate as prepared statements mitigate injection, but early validation improves robustness and response clarity.

Medium
Security
Encode redirect URL parameters

URL-encode clientId and redirectUri to avoid malformed redirects or injection via
special characters. Build the URL using encoded parameter values consistently.

src/prerna/semoss/web/services/local/UserResource.java [1025-1027]

-String redirectUrl = "https://login.salesforce.com/services/oauth2/authorize?" + "client_id=" + clientId
-				+ "&response_type=code" + "&redirect_uri=" + redirectUri + "&scope="
-				+ URLEncoder.encode("api", "UTF-8");
+String redirectUrl = "https://login.salesforce.com/services/oauth2/authorize?"
+        + "client_id=" + URLEncoder.encode(clientId, "UTF-8")
+        + "&response_type=code"
+        + "&redirect_uri=" + URLEncoder.encode(redirectUri, "UTF-8")
+        + "&scope=" + URLEncoder.encode("api", "UTF-8");
Suggestion importance[1-10]: 7

__

Why: Encoding clientId and redirectUri in the authorization URL prevents malformed redirects due to special characters and improves security; the fix is precise and matches the existing code location.

Medium

@snehakumari369 snehakumari369 requested a review from a team August 19, 2025 17:53
@snehakumari369 snehakumari369 self-assigned this Aug 19, 2025
@anurag91jain anurag91jain linked an issue Aug 20, 2025 that may be closed by this pull request
1 task
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.

Create a connector for Salesforce - BE

3 participants