Skip to content

Commit

Permalink
Merge pull request #89 from TrueSparrowSystems/login-changes
Browse files Browse the repository at this point in the history
Added Default User Login in Connect Flow And Environment based Cache Suffix
  • Loading branch information
mohitcharkha authored Sep 13, 2023
2 parents 39190a6 + fb5d026 commit 3640a0c
Show file tree
Hide file tree
Showing 14 changed files with 121 additions and 40 deletions.
4 changes: 3 additions & 1 deletion sample.secrets.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,7 @@
"ERROR_MAIL_FROM": "",
"ERROR_MAIL_TO": "",
"COOKIE_DOMAIN": "",
"OPENAI_API_KEY": ""
"OPENAI_API_KEY": "",
"DEFAULT_TEST_USER":"",
"DEFAULT_TEST_USER_PASSWORD":""
}
20 changes: 20 additions & 0 deletions src/main/java/com/salessparrow/api/config/CoreConstants.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@ public static Boolean isLocalTestEnvironment() {
return environment().equals("local-test");
}

public static Boolean isStagingEnvironment() {
return environment().equals("staging");
}

public static Boolean isProductionEnvironment() {
return environment().equals("production");
}

/* End: Env variables required before spring application context is initialized */

public static String cookieDomain() {
Expand Down Expand Up @@ -63,6 +71,18 @@ public static String localKmsEndpoint() {
return SecretConstants.localKmsEndpoint();
}

public static String defaultTestUser() {
return SecretConstants.defaultTestUser();
}

public static String defaultTestUserPassword() {
return SecretConstants.defaultTestUserPassword();
}

public static String defaultTestUserCode() {
return "test_12341234";
}

/**
* This method returns the memcached address that is going to be used for locals
* @return String
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,10 @@ public CacheManager cacheManager() {
private Collection<Memcached> internalCaches(MemcachedClient cache) {
final Collection<Memcached> caches = new ArrayList<>();

caches.add(new Memcached(CacheConstants.SS_SALESFORCE_USER_CACHE, CacheConstants.SS_SALESFORCE_USER_CACHE_EXP,
cache));
caches.add(new Memcached(CacheConstants.SS_SALESFORCE_OAUTH_TOKEN_CACHE,
CacheConstants.SS_SALESFORCE_OAUTH_TOKEN_CACHE_EXP, cache));
caches
.add(new Memcached(CacheConstants.SALESFORCE_USER_CACHE, CacheConstants.SALESFORCE_USER_CACHE_EXP, cache));
caches.add(new Memcached(CacheConstants.SALESFORCE_OAUTH_TOKEN_CACHE,
CacheConstants.SALESFORCE_OAUTH_TOKEN_CACHE_EXP, cache));
return caches;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,39 @@
package com.salessparrow.api.lib.globalConstants;

import org.springframework.stereotype.Component;
import com.salessparrow.api.config.CoreConstants;

@Component
public class CacheConstants {

public static final String SalesSparrowPrefix = "ss_";

public static final String SS_SALESFORCE_USER_CACHE = SalesSparrowPrefix + "sf_user";

public static final Integer SS_SALESFORCE_USER_CACHE_EXP = 30 * 24 * 60 * 60; // 30
// days

public static final String SS_SALESFORCE_OAUTH_TOKEN_CACHE = SalesSparrowPrefix + "sf_oauth_token";

public static final Integer SS_SALESFORCE_OAUTH_TOKEN_CACHE_EXP = 30 * 24 * 60 * 60; // 30
// days
public static final String CACHE_SUFFIX = getCacheSuffix();

public static final String SALESFORCE_USER_CACHE = "sf_user";

public static final Integer SALESFORCE_USER_CACHE_EXP = 30 * 24 * 60 * 60; // 30
// days

public static final String SALESFORCE_OAUTH_TOKEN_CACHE = "sf_oauth_token";

public static final Integer SALESFORCE_OAUTH_TOKEN_CACHE_EXP = 30 * 24 * 60 * 60; // 30
// days

public static String getCacheSuffix() {
if (CoreConstants.isProductionEnvironment()) {
return "_prod";
}
else if (CoreConstants.isStagingEnvironment()) {
return "_stag";
}
else if (CoreConstants.isTestEnvironment()) {
return "_test";
}
else if (CoreConstants.isLocalTestEnvironment()) {
return "_ltest";
}
else {
return "_dev";
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ public String authorizationCodeGrantType() {
return "authorization_code";
}

public String passwordGrantType() {
return "password";
}

public String refreshTokenGrantType() {
return "refresh_token";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,14 @@ public static String localKmsEndpoint() {
return getSecret("LOCAL_KMS_ENDPOINT");
}

public static String defaultTestUser() {
return getSecret("DEFAULT_TEST_USER");
}

public static String defaultTestUserPassword() {
return getSecret("DEFAULT_TEST_USER_PASSWORD");
}

/* Secrets end */

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import com.salessparrow.api.domain.SalesforceOauthToken;
import com.salessparrow.api.exception.CustomException;
import com.salessparrow.api.lib.errorLib.ErrorObject;
import com.salessparrow.api.lib.httpLib.HttpClient;
import com.salessparrow.api.repositories.SalesforceOauthTokenRepository;

import org.slf4j.Logger;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,24 @@ public class SalesforceTokens {
* @param redirectUri
* @return HttpResponse
*/
public HttpResponse getTokens(String code, String redirectUri) {
public HttpResponse getTokens(String code, String redirectUri, Boolean isTestUser) {

String salesforceOAuthEndpoint = salesforceConstants.oauth2Url();

String requestBody = "grant_type=" + salesforceConstants.authorizationCodeGrantType() + "&client_id="
+ CoreConstants.salesforceClientId() + "&client_secret=" + CoreConstants.salesforceClientSecret()
+ "&code=" + code + "&redirect_uri=" + redirectUri;
String requestBody;

if (!isTestUser) {
requestBody = String.format("grant_type=%s&client_id=%s&client_secret=%s&code=%s&redirect_uri=%s",
salesforceConstants.authorizationCodeGrantType(), CoreConstants.salesforceClientId(),
CoreConstants.salesforceClientSecret(), code, redirectUri);
}
else {
requestBody = String.format(
"grant_type=%s&client_id=%s&client_secret=%s&username=%s&password=%s&redirect_uri=%s",
salesforceConstants.passwordGrantType(), CoreConstants.salesforceClientId(),
CoreConstants.salesforceClientSecret(), CoreConstants.defaultTestUser(),
CoreConstants.defaultTestUserPassword(), redirectUri);
}

Map<String, String> headers = new HashMap<>();
headers.put("content-type", "application/x-www-form-urlencoded");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ public SalesforceOauthTokenRepository(DynamoDBMapper dynamoDBMapper) {
* @param salesforceOauthToken
* @return SalesforceOauthToken
*/
@CacheEvict(value = CacheConstants.SS_SALESFORCE_OAUTH_TOKEN_CACHE, key = "#salesforceOauthToken.externalUserId")
@CacheEvict(value = CacheConstants.SALESFORCE_OAUTH_TOKEN_CACHE,
key = "#salesforceOauthToken.externalUserId + T(com.salessparrow.api.lib.globalConstants.CacheConstants).CACHE_SUFFIX")
public SalesforceOauthToken createSalesforceOauthToken(SalesforceOauthToken salesforceOauthToken) {
// Create a row with status active and created at as current time
salesforceOauthToken.setStatus(SalesforceOauthToken.Status.ACTIVE);
Expand All @@ -48,7 +49,8 @@ public SalesforceOauthToken createSalesforceOauthToken(SalesforceOauthToken sale
* @param salesforceOauthToken
* @return SalesforceOauthToken
*/
@CacheEvict(value = CacheConstants.SS_SALESFORCE_OAUTH_TOKEN_CACHE, key = "#salesforceOauthToken.externalUserId")
@CacheEvict(value = CacheConstants.SALESFORCE_OAUTH_TOKEN_CACHE,
key = "#salesforceOauthToken.externalUserId + T(com.salessparrow.api.lib.globalConstants.CacheConstants).CACHE_SUFFIX")
public SalesforceOauthToken updateSalesforceOauthToken(SalesforceOauthToken salesforceOauthToken) {
try {
dynamoDBMapper.save(salesforceOauthToken);
Expand All @@ -65,7 +67,8 @@ public SalesforceOauthToken updateSalesforceOauthToken(SalesforceOauthToken sale
* @param externalUserId
* @return SalesforceOauthToken
*/
@Cacheable(value = CacheConstants.SS_SALESFORCE_OAUTH_TOKEN_CACHE, key = "#externalUserId")
@Cacheable(value = CacheConstants.SALESFORCE_OAUTH_TOKEN_CACHE,
key = "#externalUserId + T(com.salessparrow.api.lib.globalConstants.CacheConstants).CACHE_SUFFIX")
public SalesforceOauthToken getSalesforceOauthTokenByExternalUserId(String externalUserId) {
try {
return dynamoDBMapper.load(SalesforceOauthToken.class, externalUserId);
Expand All @@ -81,7 +84,8 @@ public SalesforceOauthToken getSalesforceOauthTokenByExternalUserId(String exter
* @param salesforceOauthToken
* @return void
*/
@CacheEvict(value = CacheConstants.SS_SALESFORCE_OAUTH_TOKEN_CACHE, key = "#salesforceOauthToken.externalUserId")
@CacheEvict(value = CacheConstants.SALESFORCE_OAUTH_TOKEN_CACHE,
key = "#salesforceOauthToken.externalUserId + T(com.salessparrow.api.lib.globalConstants.CacheConstants).CACHE_SUFFIX")
public void deleteSalesforceOauthTokenBySalesforceOauthToken(SalesforceOauthToken salesforceOauthToken) {
try {
dynamoDBMapper.delete(salesforceOauthToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ public SalesforceUserRepository(DynamoDBMapper dynamoDBMapper) {
* @param salesforceUser
* @return SalesforceUser
*/
@CacheEvict(value = CacheConstants.SS_SALESFORCE_USER_CACHE, key = "#salesforceUser.externalUserId")
@CacheEvict(value = CacheConstants.SALESFORCE_USER_CACHE,
key = "#salesforceUser.externalUserId + T(com.salessparrow.api.lib.globalConstants.CacheConstants).CACHE_SUFFIX")
public SalesforceUser createSalesforceUser(SalesforceUser salesforceUser) {
// Create a row with status active and created at as current time
salesforceUser.setStatus(SalesforceUser.Status.ACTIVE);
Expand All @@ -49,7 +50,8 @@ public SalesforceUser createSalesforceUser(SalesforceUser salesforceUser) {
* @param salesforceUser
* @return SalesforceUser
*/
@CacheEvict(value = CacheConstants.SS_SALESFORCE_USER_CACHE, key = "#salesforceUser.externalUserId")
@CacheEvict(value = CacheConstants.SALESFORCE_USER_CACHE,
key = "#salesforceUser.externalUserId + T(com.salessparrow.api.lib.globalConstants.CacheConstants).CACHE_SUFFIX")
public SalesforceUser updateSalesforceUser(SalesforceUser salesforceUser) {
try {
dynamoDBMapper.save(salesforceUser);
Expand All @@ -66,7 +68,8 @@ public SalesforceUser updateSalesforceUser(SalesforceUser salesforceUser) {
* @param id
* @return SalesforceUser
*/
@Cacheable(value = CacheConstants.SS_SALESFORCE_USER_CACHE, key = "#externalUserId")
@Cacheable(value = CacheConstants.SALESFORCE_USER_CACHE,
key = "#externalUserId + T(com.salessparrow.api.lib.globalConstants.CacheConstants).CACHE_SUFFIX")
public SalesforceUser getSalesforceUserByExternalUserId(String externalUserId) {
try {
return dynamoDBMapper.load(SalesforceUser.class, externalUserId);
Expand All @@ -76,7 +79,8 @@ public SalesforceUser getSalesforceUserByExternalUserId(String externalUserId) {
}
}

@CacheEvict(value = CacheConstants.SS_SALESFORCE_USER_CACHE, key = "#externalUserId")
@CacheEvict(value = CacheConstants.SALESFORCE_USER_CACHE,
key = "#externalUserId + T(com.salessparrow.api.lib.globalConstants.CacheConstants).CACHE_SUFFIX")
public void removeSalesforceUserData(String externalUserId) {
SalesforceUser salesforceUser = getSalesforceUserByExternalUserId(externalUserId);
salesforceUser.setIdentityUrl(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,17 @@ public AuthServiceDto connectToSalesforce(SalesforceConnectDto params, HttpServl
this.isNewUser = true; // setting default value true to this variable, this will
// be updated based on conditions in further processing

String testUserCode = CoreConstants.defaultTestUserCode();
Boolean isTestUser = false;

code = params.getCode();
if (code.equals(testUserCode)) {
isTestUser = true;
}

redirectUri = params.getRedirect_uri();

fetchOauthTokensFromSalesforce();
fetchOauthTokensFromSalesforce(isTestUser);

validateAndSaveSalesforceOrganization();

Expand All @@ -116,10 +123,11 @@ public AuthServiceDto connectToSalesforce(SalesforceConnectDto params, HttpServl
* Call Salesforce oauth token endpoint and fetch tokens.
* @return void
*/
private void fetchOauthTokensFromSalesforce() {
private void fetchOauthTokensFromSalesforce(Boolean isTestUser) {
logger.info("Fetching OAuth Tokens from Salesforce");

HttpResponse response = salesforceTokens.getTokens(this.code, this.redirectUri);
// TODO - Raj (Call below with diff params as per screenshot shared)
HttpResponse response = salesforceTokens.getTokens(this.code, this.redirectUri, isTestUser);

JsonNode jsonNode = util.getJsonNode(response.getResponseBody());

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.salessparrow.api.functional.controllers.authController;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;

Expand Down Expand Up @@ -92,7 +93,7 @@ public void testPostDisconnectSuccess() throws Exception {
getTokensMockRes
.setResponseBody(objectMapper.writeValueAsString(testDataItem.getMocks().get("revokeTokens")));

when(mockGetTokens.getTokens(anyString(), anyString())).thenReturn(getTokensMockRes);
when(mockGetTokens.getTokens(anyString(), anyString(), anyBoolean())).thenReturn(getTokensMockRes);

ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/auth/disconnect")
.cookie(new Cookie(CookieConstants.USER_LOGIN_COOKIE_NAME, cookieValue))
Expand Down Expand Up @@ -129,7 +130,7 @@ public void testPostDisconnectNoTokens() throws Exception {
getTokensMockRes
.setResponseBody(objectMapper.writeValueAsString(testDataItem.getMocks().get("revokeTokens")));

when(mockGetTokens.getTokens(anyString(), anyString())).thenReturn(getTokensMockRes);
when(mockGetTokens.getTokens(anyString(), anyString(), anyBoolean())).thenReturn(getTokensMockRes);

ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/auth/disconnect")
.cookie(new Cookie(CookieConstants.USER_LOGIN_COOKIE_NAME, cookieValue))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.slf4j.LoggerFactory;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
Expand Down Expand Up @@ -108,7 +109,7 @@ public void testPostSalesforceConnectSignup() throws Exception {
getIdentityMockRes
.setResponseBody(objectMapper.writeValueAsString(testDataItem.getMocks().get("getIdentity")));

when(mockGetTokens.getTokens(anyString(), anyString())).thenReturn(getTokensMockRes);
when(mockGetTokens.getTokens(anyString(), anyString(), anyBoolean())).thenReturn(getTokensMockRes);
when(mockGetIdentity.getUserIdentity(anyString(), anyString())).thenReturn(getIdentityMockRes);

ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/auth/salesforce/connect")
Expand Down Expand Up @@ -153,7 +154,7 @@ public void testPostSalesforceConnectLogin() throws Exception {
HttpResponse getTokensMockRes = new HttpResponse();
getTokensMockRes.setResponseBody(objectMapper.writeValueAsString(testDataItem.getMocks().get("getTokens")));

when(mockGetTokens.getTokens(anyString(), anyString())).thenReturn(getTokensMockRes);
when(mockGetTokens.getTokens(anyString(), anyString(), anyBoolean())).thenReturn(getTokensMockRes);

ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/auth/salesforce/connect")
.content(objectMapper.writeValueAsString(testDataItem.getInput().get("body")))
Expand All @@ -165,7 +166,7 @@ public void testPostSalesforceConnectLogin() throws Exception {

if (resultActions.andReturn().getResponse().getStatus() == 200) {
assertEquals(objectMapper.writeValueAsString(testDataItem.getOutput()), actualOutput);
verify(mockGetTokens, times(1)).getTokens(anyString(), anyString());
verify(mockGetTokens, times(1)).getTokens(anyString(), anyString(), anyBoolean());
verify(mockGetIdentity, times(0)).getUserIdentity(anyString(), anyString());
}
else if (resultActions.andReturn().getResponse().getStatus() == 400) {
Expand Down Expand Up @@ -202,7 +203,7 @@ public void testPostSalesforceConnectDisconnectedUserSignup() throws Exception {
getIdentityMockRes
.setResponseBody(objectMapper.writeValueAsString(testDataItem.getMocks().get("getIdentity")));

when(mockGetTokens.getTokens(anyString(), anyString())).thenReturn(getTokensMockRes);
when(mockGetTokens.getTokens(anyString(), anyString(), anyBoolean())).thenReturn(getTokensMockRes);
when(mockGetIdentity.getUserIdentity(anyString(), anyString())).thenReturn(getIdentityMockRes);

ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/auth/salesforce/connect")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public void testGetTokensSuccess() throws Exception {
httpClientMockedStatic.when(() -> HttpClient.makePostRequest(anyString(), anyMap(), anyString(), anyInt()))
.thenReturn(mockResponse);

HttpResponse actualResponse = salesforceTokens.getTokens(code, redirectUri);
HttpResponse actualResponse = salesforceTokens.getTokens(code, redirectUri, false);

// Assertions
assertEquals(mockResponse.getResponseBody(), actualResponse.getResponseBody());
Expand Down Expand Up @@ -116,7 +116,7 @@ public void testGetTokensException() throws Exception {
.thenThrow(new RuntimeException("Some error occurred"));

CustomException exception = assertThrows(CustomException.class, () -> {
salesforceTokens.getTokens(code, redirectUri);
salesforceTokens.getTokens(code, redirectUri, false);
});

// Assertions
Expand Down

0 comments on commit 3640a0c

Please sign in to comment.