use of io.dockstore.webservice.resources.ResourceConstants.OPENAPI_JWT_SECURITY_DEFINITION_NAME in project dockstore by dockstore.
the class UserResource method addUserToDockstoreWorkflows.
@PATCH
@Timed
@UnitOfWork
@Path("/{userId}/workflows")
@ApiOperation(value = "Adds a user to any Dockstore workflows that they should have access to.", authorizations = { @Authorization(value = JWT_SECURITY_DEFINITION_NAME) }, response = Workflow.class, responseContainer = "List")
@Operation(operationId = "addUserToDockstoreWorkflows", description = "Adds the logged-in user to any Dockstore workflows that they should have access to.", security = @SecurityRequirement(name = OPENAPI_JWT_SECURITY_DEFINITION_NAME))
public List<Workflow> addUserToDockstoreWorkflows(@ApiParam(hidden = true) @Parameter(hidden = true, name = "user") @Auth User authUser, @ApiParam(name = "userId", required = true, value = "User to update") @PathParam("userId") @Parameter(name = "userId", in = ParameterIn.PATH, description = "User to update", required = true) long userId, @ApiParam(name = "emptyBody", value = APPEASE_SWAGGER_PATCH) @Parameter(description = APPEASE_SWAGGER_PATCH, name = "emptyBody") String emptyBody) {
final User user = userDAO.findById(authUser.getId());
if (user == null || !Objects.equals(userId, user.getId())) {
throw new CustomWebApplicationException("The user id provided does not match the logged-in user id.", HttpStatus.SC_BAD_REQUEST);
}
// Ignore hosted workflows
List<SourceControl> sourceControls = Arrays.stream(SourceControl.values()).filter(sourceControl -> !Objects.equals(sourceControl, SourceControl.DOCKSTORE)).collect(Collectors.toList());
List<Token> scTokens = getAndRefreshTokens(user, tokenDAO, client, bitbucketClientID, bitbucketClientSecret).stream().filter(token -> sourceControls.contains(token.getTokenSource().getSourceControl())).collect(Collectors.toList());
scTokens.forEach(token -> {
SourceCodeRepoInterface sourceCodeRepo = SourceCodeRepoFactory.createSourceCodeRepo(token);
Map<String, String> gitUrlToRepositoryId = sourceCodeRepo.getWorkflowGitUrl2RepositoryId();
Set<String> organizations = gitUrlToRepositoryId.values().stream().map(repository -> repository.split("/")[0]).collect(Collectors.toSet());
organizations.forEach(organization -> {
List<Workflow> workflowsWithoutuser = workflowDAO.findByOrganizationWithoutUser(token.getTokenSource().getSourceControl(), organization, user);
workflowsWithoutuser.forEach(workflow -> workflow.addUser(user));
});
});
return convertMyWorkflowsToWorkflow(this.bioWorkflowDAO.findUserBioWorkflows(user.getId()));
}
use of io.dockstore.webservice.resources.ResourceConstants.OPENAPI_JWT_SECURITY_DEFINITION_NAME in project dockstore by dockstore.
the class EntryResource method getVersionsFileTypes.
@GET
@Timed
@UnitOfWork(readOnly = true)
@Path("/{entryId}/versions/{versionId}/fileTypes")
@ApiOperation(value = "Retrieve the file types of a version's sourcefiles", hidden = true)
@Operation(operationId = "getVersionsFileTypes", description = "Retrieve the unique file types of a version's sourcefile", security = @SecurityRequirement(name = OPENAPI_JWT_SECURITY_DEFINITION_NAME))
public SortedSet<DescriptorLanguage.FileType> getVersionsFileTypes(@Parameter(hidden = true, name = "user") @Auth Optional<User> user, @Parameter(name = "entryId", description = "Entry to retrieve the version from", required = true, in = ParameterIn.PATH) @PathParam("entryId") Long entryId, @Parameter(name = "versionId", description = "Version to retrieve the sourcefile types from", required = true, in = ParameterIn.PATH) @PathParam("versionId") Long versionId) {
Entry<? extends Entry, ? extends Version> entry = toolDAO.getGenericEntryById(entryId);
checkEntry(entry);
checkEntryPermissions(user, entry);
Version version = versionDAO.findVersionInEntry(entryId, versionId);
if (version == null) {
throw new CustomWebApplicationException("Version " + versionId + " does not exist for this entry", HttpStatus.SC_BAD_REQUEST);
}
SortedSet<SourceFile> sourceFiles = version.getSourceFiles();
return sourceFiles.stream().map(sourceFile -> sourceFile.getType()).collect(Collectors.toCollection(TreeSet::new));
}
use of io.dockstore.webservice.resources.ResourceConstants.OPENAPI_JWT_SECURITY_DEFINITION_NAME in project dockstore by dockstore.
the class TokenResource method addGitlabToken.
@GET
@Timed
@UnitOfWork
@Path("/gitlab.com")
@JsonView(TokenViews.User.class)
@Operation(operationId = "addGitlabToken", description = "Add a new gitlab.com token.", security = @SecurityRequirement(name = OPENAPI_JWT_SECURITY_DEFINITION_NAME))
@ApiOperation(value = "Add a new gitlab.com token.", authorizations = { @Authorization(value = JWT_SECURITY_DEFINITION_NAME) }, notes = "This is used as part of the OAuth 2 web flow. Once a user has approved permissions for CollaboratoryTheir browser will load the redirect URI which should resolve here", response = Token.class)
public Token addGitlabToken(@ApiParam(hidden = true) @Parameter(hidden = true, name = "user") @Auth User user, @QueryParam("code") String code) {
final AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), HTTP_TRANSPORT, JSON_FACTORY, new GenericUrl(GITLAB_URL + "oauth/token"), new ClientParametersAuthentication(gitlabClientID, gitlabClientSecret), gitlabClientID, GITLAB_URL + "oauth/authorize").build();
LOG.info("About to try and grab access token");
String accessToken;
try {
TokenResponse tokenResponse = flow.newTokenRequest(code).setRequestInitializer(request -> request.getHeaders().setAccept("application/json")).setGrantType("authorization_code").setRedirectUri(gitlabRedirectUri).execute();
accessToken = tokenResponse.getAccessToken();
} catch (IOException e) {
LOG.error("Retrieving accessToken was unsuccessful");
throw new CustomWebApplicationException("Could not retrieve gitlab.com token based on code", HttpStatus.SC_BAD_REQUEST);
}
String url = GITLAB_URL + "api/v3/user";
Optional<String> asString = ResourceUtilities.asString(url, accessToken, client);
String username = getUserName(url, asString);
if (user != null) {
Token token = new Token();
token.setTokenSource(TokenType.GITLAB_COM);
token.setContent(accessToken);
token.setUserId(user.getId());
if (username != null) {
token.setUsername(username);
} else {
LOG.info("Gitlab.com tokenusername is null, did not create token");
throw new CustomWebApplicationException("Username not found from resource call " + url, HttpStatus.SC_CONFLICT);
}
checkIfAccountHasBeenLinked(token, TokenType.GITLAB_COM);
long create = tokenDAO.create(token);
LOG.info("Gitlab token created for {}", user.getUsername());
return tokenDAO.findById(create);
} else {
LOG.info("Could not find user");
throw new CustomWebApplicationException("User not found", HttpStatus.SC_CONFLICT);
}
}
use of io.dockstore.webservice.resources.ResourceConstants.OPENAPI_JWT_SECURITY_DEFINITION_NAME in project dockstore by dockstore.
the class TokenResource method addBitbucketToken.
@GET
@Timed
@UnitOfWork
@Path("/bitbucket.org")
@JsonView(TokenViews.User.class)
@Operation(operationId = "addBitbucketToken", description = "Add a new bitbucket.org token, used by quay.io redirect.", security = @SecurityRequirement(name = OPENAPI_JWT_SECURITY_DEFINITION_NAME))
@ApiOperation(value = "Add a new bitbucket.org token, used by quay.io redirect.", authorizations = { @Authorization(value = JWT_SECURITY_DEFINITION_NAME) }, notes = "This is used as part of the OAuth 2 web flow. " + "Once a user has approved permissions for Collaboratory" + "Their browser will load the redirect URI which should resolve here", response = Token.class)
public Token addBitbucketToken(@ApiParam(hidden = true) @Parameter(hidden = true, name = "user") @Auth User user, @QueryParam("code") String code) {
if (code.isEmpty()) {
throw new CustomWebApplicationException("Please provide an access code", HttpStatus.SC_BAD_REQUEST);
}
final AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), HTTP_TRANSPORT, JSON_FACTORY, new GenericUrl(BITBUCKET_URL + "site/oauth2/access_token"), new ClientParametersAuthentication(bitbucketClientID, bitbucketClientSecret), bitbucketClientID, "https://bitbucket.org/site/oauth2/authorize").build();
String accessToken;
String refreshToken;
try {
TokenResponse tokenResponse = flow.newTokenRequest(code).setScopes(Collections.singletonList("user:email")).setRequestInitializer(request -> request.getHeaders().setAccept("application/json")).execute();
accessToken = tokenResponse.getAccessToken();
refreshToken = tokenResponse.getRefreshToken();
} catch (IOException e) {
LOG.error("Retrieving accessToken was unsuccessful");
throw new CustomWebApplicationException("Could not retrieve bitbucket.org token based on code", HttpStatus.SC_BAD_REQUEST);
}
String url = BITBUCKET_URL + "api/2.0/user";
Optional<String> asString2 = ResourceUtilities.asString(url, accessToken, client);
String username = getUserName(url, asString2);
if (user != null) {
Token token = new Token();
token.setTokenSource(TokenType.BITBUCKET_ORG);
token.setContent(accessToken);
token.setRefreshToken(refreshToken);
token.setUserId(user.getId());
if (username != null) {
token.setUsername(username);
} else {
LOG.info("Bitbucket.org token username is null, did not create token");
throw new CustomWebApplicationException("Username not found from resource call " + url, HttpStatus.SC_CONFLICT);
}
checkIfAccountHasBeenLinked(token, TokenType.BITBUCKET_ORG);
long create = tokenDAO.create(token);
LOG.info("Bitbucket token created for {}", user.getUsername());
return tokenDAO.findById(create);
} else {
LOG.info("Could not find user");
throw new CustomWebApplicationException("User not found", HttpStatus.SC_CONFLICT);
}
}
use of io.dockstore.webservice.resources.ResourceConstants.OPENAPI_JWT_SECURITY_DEFINITION_NAME in project dockstore by dockstore.
the class WorkflowResource method manualRegister.
@POST
@Timed
@UnitOfWork
@Path("/manualRegister")
@SuppressWarnings("checkstyle:ParameterNumber")
@Operation(operationId = "manualRegister", description = "Manually register a workflow.", security = @SecurityRequirement(name = OPENAPI_JWT_SECURITY_DEFINITION_NAME))
@ApiOperation(value = "Manually register a workflow.", authorizations = { @Authorization(value = JWT_SECURITY_DEFINITION_NAME) }, notes = "Manually register workflow (public or private).", response = Workflow.class)
public Workflow manualRegister(@ApiParam(hidden = true) @Parameter(hidden = true, name = "user") @Auth User user, @ApiParam(value = "Workflow registry", required = true) @QueryParam("workflowRegistry") String workflowRegistry, @ApiParam(value = "Workflow repository", required = true) @QueryParam("workflowPath") String workflowPath, @ApiParam(value = "Workflow container new descriptor path (CWL or WDL) and/or name", required = true) @QueryParam("defaultWorkflowPath") String defaultWorkflowPath, @ApiParam(value = "Workflow name, set to empty if none required", required = true) @QueryParam("workflowName") String workflowName, @ApiParam(value = "Descriptor type", required = true) @QueryParam("descriptorType") String descriptorType, @ApiParam(value = "Default test parameter file path") @QueryParam("defaultTestParameterFilePath") String defaultTestParameterFilePath) {
for (DescriptorLanguage typeItem : DescriptorLanguage.values()) {
if (typeItem.getShortName().equalsIgnoreCase(descriptorType)) {
// check that plugin is active
if (typeItem.isPluginLanguage() && !LanguageHandlerFactory.getPluginMap().containsKey(typeItem)) {
throw new CustomWebApplicationException("plugin for " + typeItem.getShortName() + " is not installed", HttpStatus.SC_BAD_REQUEST);
}
if (typeItem.getDefaultPrimaryDescriptorExtensions().stream().noneMatch(defaultWorkflowPath::endsWith)) {
throw new CustomWebApplicationException("Please ensure that the given workflow path '" + defaultWorkflowPath + "' is of type " + descriptorType + " and ends in an extension from" + String.join(",", typeItem.getDefaultPrimaryDescriptorExtensions()), HttpStatus.SC_BAD_REQUEST);
}
}
}
// Validate source control registry
Optional<SourceControl> sourceControlEnum = Arrays.stream(SourceControl.values()).filter(value -> workflowRegistry.equalsIgnoreCase(value.getFriendlyName().toLowerCase())).findFirst();
if (sourceControlEnum.isEmpty()) {
throw new CustomWebApplicationException("The given git registry is not supported.", HttpStatus.SC_BAD_REQUEST);
}
String registryURLPrefix = sourceControlEnum.get().toString();
String gitURL = "git@" + registryURLPrefix + ":" + workflowPath + ".git";
final SourceCodeRepoInterface sourceCodeRepo = getSourceCodeRepoInterface(gitURL, user);
// Create workflow and override defaults
Workflow newWorkflow = sourceCodeRepo.createStubBioworkflow(workflowPath);
newWorkflow.setDescriptorType(DescriptorLanguage.convertShortStringToEnum(descriptorType));
newWorkflow.setDefaultWorkflowPath(defaultWorkflowPath);
newWorkflow.setWorkflowName(Strings.isNullOrEmpty(workflowName) ? null : workflowName);
newWorkflow.setDefaultTestParameterFilePath(defaultTestParameterFilePath);
// Save into database and then pull versions
Workflow workflowFromDB = saveNewWorkflow(newWorkflow, user);
updateDBWorkflowWithSourceControlWorkflow(workflowFromDB, newWorkflow, user, Optional.empty());
return workflowDAO.findById(workflowFromDB.getId());
}
Aggregations