Skip to content

Commit

Permalink
Various updates
Browse files Browse the repository at this point in the history
  • Loading branch information
InbarGazit committed Jan 15, 2025
1 parent 7c46474 commit b9963d0
Show file tree
Hide file tree
Showing 17 changed files with 157 additions and 107 deletions.
12 changes: 11 additions & 1 deletion Quick_ACG/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@
<includes>
<include>Locals.java</include>
<include>User.java</include>
<include>EnvelopeDocumentInfo.java</include>
</includes>
</resource>
<resource>
Expand Down Expand Up @@ -199,7 +200,16 @@
<targetPath>${basedir}/src/main/java/com/docusign/core/security</targetPath>
<directory>../src/main/java/com/docusign/core/security</directory>
<includes>
<include>OAuthProperties.java</include>
<include>SecurityHelpers.java</include>
<include>JWTOAuth2User.java</include>
<include>CustomAuthenticationFailureHandler.java</include>
</includes>
</resource>
<resource>
<targetPath>${basedir}/src/main/java/com/docusign/core/security/acg</targetPath>
<directory>../src/main/java/com/docusign/core/security/acg</directory>
<includes>
<include>ACGAuthenticationMethod.java</include>
</includes>
</resource>
<resource>
Expand Down
18 changes: 15 additions & 3 deletions Quick_ACG/src/main/java/com/docusign/DSConfiguration.java
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,20 @@ public class DSConfiguration {
@Value("${DS_ADMIN_BASE_PATH}")
private String adminBasePath;

@Value("${spring.security.oauth2.client.registration.acg.client-secret}")
private String secretUserId;

@Value("${spring.security.oauth2.client.provider.acg.token-uri}")
private String tokenEndpoint;

@Value("${spring.security.oauth2.client.provider.acg.authorization-uri}")
private String authorizationEndpoint;

@Value("${spring.security.oauth2.client.registration.jwt.client-id}")
private String userId;

public String examplesApiPath = "examplesApi.json";

public String apiTypeHeader = "ApiType";

@Value("${CodeExamplesManifest}")
Expand All @@ -94,14 +106,14 @@ public String getDsPingUrl() {
}

public ManifestStructure getCodeExamplesText() {
if (codeExamplesText != null){
if (codeExamplesText != null) {
return codeExamplesText;
}

try {
String json = loadFileData(codeExamplesManifest);
codeExamplesText = new ObjectMapper().readValue(json, ManifestStructure.class);
} catch (JSONException | IOException e){
} catch (JSONException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
Expand Down
13 changes: 6 additions & 7 deletions Quick_ACG/src/main/java/com/docusign/WebSecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import com.docusign.core.security.CustomAuthenticationFailureHandler;

@EnableWebSecurity
public class WebSecurityConfig {
Expand All @@ -28,26 +29,24 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
try {
authorize
.antMatchers("/", "/error**", "/assets/**", "/ds/mustAuthenticate**",
"/ds/authenticate**", "/ds/selectApi**")
"/ds/authenticate**", "/ds/selectApi**", "/pkce")
.permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(
new LoginUrlAuthenticationEntryPoint("/ds/mustAuthenticate")
);
new LoginUrlAuthenticationEntryPoint("/ds/mustAuthenticate"));
} catch (Exception e) {
throw new RuntimeException(e);
}
})
.requestCache().requestCache(requestCache()).and()
.oauth2Login(Customizer.withDefaults())
.oauth2Login(login -> login.failureHandler(new CustomAuthenticationFailureHandler()))
.oauth2Client(Customizer.withDefaults())
.logout(logout -> logout
.logoutSuccessUrl("/")
)
.logoutSuccessUrl("/"))
.csrf().disable();

return http.build();
return http.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
import com.docusign.core.model.User;
import java.io.IOException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.docusign.core.security.acg.ACGAuthenticationMethod;

import com.docusign.core.utils.AccountsConverter;
import org.apache.commons.lang3.StringUtils;
Expand All @@ -26,21 +29,16 @@
import com.docusign.esign.client.auth.OAuth;
import java.util.stream.Collectors;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import javax.servlet.http.HttpServletResponse;

@Controller
@ControllerAdvice
@Scope(WebApplicationContext.SCOPE_SESSION)
public class IndexController {
private static final String ATTR_ENVELOPE_ID = "qpEnvelopeId";
private static final List<String> ESIGNATURE_SCOPES = Arrays.asList("signature");
private static final String ATTR_STATE = "state";
private static final String ATTR_EVENT = "event";
private static final String ATTR_TITLE = "title";

private static final String ERROR_ACCOUNT_NOT_FOUND = "Could not find account information for the user";
private static final String SELECTED_API_NOT_SUPPORTED = "Currently selected api is not supported by launcher. Please, check appsettings.json file.";
private final DSConfiguration config;
private final Session session;
private final User user;
Expand All @@ -65,22 +63,45 @@ public String index(ModelMap model, HttpServletResponse response) throws IOExcep
}

@GetMapping(path = "/ds/mustAuthenticate")
public ModelAndView mustAuthenticateController(ModelMap model) throws IOException {
public ModelAndView mustAuthenticateController(ModelMap model) throws IOException, Exception {
return new ModelAndView(getRedirectView());
}

@GetMapping(path = "/ds-return")
public String returnController(@RequestParam(value = ATTR_STATE, required = false) String state,
@RequestParam(value = ATTR_EVENT, required = false) String event,
@RequestParam(required = false) String envelopeId, ModelMap model, HttpServletResponse response) throws IOException {
@RequestParam(required = false) String envelopeId, ModelMap model, HttpServletResponse response)
throws IOException {
String site = "/eg001";
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
return null;
}

private RedirectView getRedirectView() {
RedirectView redirect = new RedirectView(getLoginPath());
@GetMapping("/pkce")
public RedirectView pkce(String code, String state, HttpServletRequest req, HttpServletResponse resp)
throws Exception {
String redirectURL = "/";
RedirectView redirect;
try {
redirect = new ACGAuthenticationMethod().exchangeCodeForToken(code, config, session, redirectURL,
ESIGNATURE_SCOPES);
} catch (Exception e) {
redirect = new RedirectView(getLoginPath());
this.session.setIsPKCEWorking(false);
}

return redirect;
}

private RedirectView getRedirectView() throws Exception {
RedirectView redirect;
if (this.session.getIsPKCEWorking()) {
redirect = new ACGAuthenticationMethod().initiateAuthorization(config, ESIGNATURE_SCOPES);
} else {
redirect = new RedirectView(getLoginPath());
}

redirect.setExposeModelAttributes(false);
return redirect;
}
Expand Down Expand Up @@ -111,12 +132,16 @@ public Object populateLocals() throws IOException {
OAuth2User oauthUser = oauth.getPrincipal();
OAuth2AuthorizedClient oauthClient = authorizedClientService.loadAuthorizedClient(
oauth.getAuthorizedClientRegistrationId(),
oauthUser.getName()
);
oauthUser.getName());

if (oauth.isAuthenticated()) {
user.setName(oauthUser.getAttribute("name"));
user.setAccessToken(oauthClient.getAccessToken().getTokenValue());

if (oauthClient != null) {
user.setAccessToken(oauthClient.getAccessToken().getTokenValue());
} else {
user.setAccessToken(((OAuth.OAuthToken) oauthUser.getAttribute("access_token")).getAccessToken());
}

if (account.isEmpty()) {
account = Optional.ofNullable(getDefaultAccountInfo(getOAuthAccounts(oauthUser)));
Expand All @@ -139,7 +164,7 @@ private String getBaseUrl(OAuth.Account oauthAccount) {

private static List<OAuth.Account> getOAuthAccounts(OAuth2User user) {
List<Map<String, Object>> oauthAccounts = user.getAttribute("accounts");
if(oauthAccounts == null){
if (oauthAccounts == null) {
return new ArrayList<>();
}

Expand All @@ -152,7 +177,7 @@ private OAuth.Account getDefaultAccountInfo(List<OAuth.Account> accounts) {
String targetAccountId = config.getTargetAccountId();
if (StringUtils.isNotBlank(targetAccountId)) {
OAuth.Account account = getAccountById(accounts, targetAccountId);
if(account != null) {
if (account != null) {
return account;
}
}
Expand Down
28 changes: 12 additions & 16 deletions Quick_ACG/src/main/java/com/docusign/core/model/Session.java
Original file line number Diff line number Diff line change
@@ -1,37 +1,33 @@
package com.docusign.core.model;

import com.docusign.esign.client.auth.OAuth;
import lombok.Data;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import java.io.Serializable;
import java.util.List;
import java.util.UUID;

@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION,
proxyMode = ScopedProxyMode.TARGET_CLASS)
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
@Data
public class Session implements Serializable {
private static final long serialVersionUID = 2695379118371574037L;

public Long tokenExpirationTime;

private String accountId;

private String accountName;

private String basePath;
private String statusCFR;
private String roomsBasePath;

private String envelopeId;
private String templateId;
private String templateName;
private String permissionProfileId;
private String permissionProfileName;
private String apiIndexPath;
private boolean refreshToken = false;
private String clickwrapId;
private String clickwrapVersionNumber;
private String exportId;
private String importId;
private UUID orgId;
public UUID bulkListId;

private String statusCFR;

private Boolean isPKCEWorking = true;
}
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ For a list of code examples that use the Web Forms API, see the [How-to guides o
1. Extract the Quickstart ZIP file or download or clone the code-examples-java repository.
1. In your command-line environment, switch to the :
`cd <Quickstart >` or `cd code-examples-java`
1. Package the code: `mvn package`
1. Package the code: `mvn package -Dmaven.test.skip=true`
1. To configure the launcher for [Authorization Code Grant](https://developers.docusign.com/platform/auth/authcode/) authentication, create a copy of the file src/main/resources/application.example.json and save the copy as src/main/resources/application.json.
1. Add your User ID. On the [Apps and Keys](https://admindemo.docusign.com/authenticate?goTo=apiIntegratorKey) page, under **My Account Information**, copy the **User ID** GUID and save it in application.json as your `DS_TARGET_ACCOUNT_ID`.
1. Add your integration key. On the [Apps and Keys](https://admindemo.docusign.com/authenticate?goTo=apiIntegratorKey) page, under **Apps and Integration Keys**, choose the app to use, then select **Actions > Edit**. Under **General Info**, copy the **Integration Key** GUID and save it in application.json as your `authorization.code.grant.client.client-id`.
Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
<maestro.version>2.0.0</maestro.version>
<swagger-core-version>2.2.22</swagger-core-version>
<jackson-version>2.17.2</jackson-version>
<jersey2.version>3.1.8</jersey2.version>
<jersey2.version>3.0.9</jersey2.version>
</properties>

<dependencies>
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/com/docusign/DSConfiguration.java
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ public ManifestStructure getCodeExamplesText() {

try {
codeExamplesText = new ObjectMapper().readValue(loadFileData(codeExamplesManifest),
ManifestStructure.class);
ManifestStructure.class);
} catch (Exception e) {
e.printStackTrace();
}
Expand All @@ -182,8 +182,8 @@ public String loadFileData(String linkToManifestFile) throws Exception {
httpConnection.setRequestMethod(HttpMethod.GET);

httpConnection.setRequestProperty(
HttpHeaders.CONTENT_TYPE,
String.valueOf(MediaType.APPLICATION_JSON));
HttpHeaders.CONTENT_TYPE,
String.valueOf(MediaType.APPLICATION_JSON));

int responseCode = httpConnection.getResponseCode();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,22 @@
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public final class GetMonitoringDataService {
private static final Logger LOGGER = LoggerFactory.getLogger(GetMonitoringDataService.class);

public static JSONArray getMonitoringData(DataSetApi datasetApi) throws Exception {
// Declare variables
boolean complete = false;
String cursorValue = "";
LocalDate cursorDate = LocalDate.now().minusYears(1);
String cursorValue = cursorDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "T00:00:00Z";
JSONArray monitoringData = new JSONArray();

LOGGER.info("before optinos");
DataSetApi.GetStreamOptions options = datasetApi.new GetStreamOptions();
options.setLimit(2000);

// First call the endpoint with no cursor to get the first records.
// After each call, save the cursor and use it to make the next
Expand Down
Loading

0 comments on commit b9963d0

Please sign in to comment.