use of io.dockstore.webservice.core.User in project dockstore by dockstore.
the class AbstractWorkflowResource method syncEntities.
/**
* Syncs entities based on GitHub app installation, optionally limiting to orgs in the GitHub organization <code>organization</code>.
*
* 1. Finds all repos that have the Dockstore GitHub app installed
* 2. For existing entities, ensures that <code>user</code> is one of the entity's users
*
* @param user
* @param gitHubToken
*/
private void syncEntities(User user, Token gitHubToken) {
GitHubSourceCodeRepo gitHubSourceCodeRepo = (GitHubSourceCodeRepo) SourceCodeRepoFactory.createSourceCodeRepo(gitHubToken);
// Get all GitHub repositories for the user
final Map<String, String> workflowGitUrl2Name = gitHubSourceCodeRepo.getWorkflowGitUrl2RepositoryId();
// Filter by organization if necessary
final Collection<String> repositories = workflowGitUrl2Name.values();
// Add user to any services they should have access to that already exist on Dockstore
final List<Workflow> existingWorkflows = findDockstoreWorkflowsForGitHubRepos(repositories);
existingWorkflows.stream().filter(workflow -> !workflow.getUsers().contains(user)).forEach(workflow -> workflow.getUsers().add(user));
// No longer adds stub services, though code could be useful
// final Set<String> existingWorkflowPaths = existingWorkflows.stream()
// .map(workflow -> workflow.getWorkflowPath()).collect(Collectors.toSet());
//
// GitHubHelper.checkJWT(gitHubAppId, gitHubPrivateKeyFile);
//
// GitHubHelper.reposToCreateEntitiesFor(repositories, organization, existingWorkflowPaths).stream()
// .forEach(repositoryName -> {
// final T entity = initializeEntity(repositoryName, gitHubSourceCodeRepo);
// entity.addUser(user);
// final long entityId = workflowDAO.create(entity);
// final Workflow createdEntity = workflowDAO.findById(entityId);
// final Workflow updatedEntity = gitHubSourceCodeRepo.getWorkflow(repositoryName, Optional.of(createdEntity));
// updateDBWorkflowWithSourceControlWorkflow(createdEntity, updatedEntity, user);
// });
}
use of io.dockstore.webservice.core.User in project dockstore by dockstore.
the class AbstractWorkflowResource method githubWebhookDelete.
/**
* Handle webhooks from GitHub apps after branch deletion (redirected from AWS Lambda)
* - Delete version for corresponding service and workflow
* @param repository Repository path (ex. dockstore/dockstore-ui2)
* @param gitReference Git reference from GitHub (ex. refs/tags/1.0)
* @param username Git user who triggered the event
* @param installationId GitHub App installation ID
* @return List of updated workflows
*/
protected List<Workflow> githubWebhookDelete(String repository, String gitReference, String username, String installationId) {
// Retrieve name from gitReference
Optional<String> gitReferenceName = GitHelper.parseGitHubReference(gitReference);
if (gitReferenceName.isEmpty()) {
String msg = "Reference " + gitReference + " is not of the valid form";
LOG.error(msg);
sessionFactory.getCurrentSession().clear();
LambdaEvent lambdaEvent = createBasicEvent(repository, gitReference, username, LambdaEvent.LambdaEventType.DELETE);
lambdaEvent.setMessage(msg);
lambdaEvent.setSuccess(false);
lambdaEventDAO.create(lambdaEvent);
sessionFactory.getCurrentSession().getTransaction().commit();
throw new CustomWebApplicationException(msg, LAMBDA_FAILURE);
}
// Find all workflows and services that are github apps and use the given repo
List<Workflow> workflows = workflowDAO.findAllByPath("github.com/" + repository, false).stream().filter(workflow -> Objects.equals(workflow.getMode(), DOCKSTORE_YML)).collect(Collectors.toList());
// When the git reference to delete is the default version, set it to the next latest version
workflows.forEach(workflow -> {
if (workflow.getActualDefaultVersion() != null && workflow.getActualDefaultVersion().getName().equals(gitReferenceName.get())) {
Optional<WorkflowVersion> max = workflow.getWorkflowVersions().stream().filter(v -> !Objects.equals(v.getName(), gitReferenceName.get())).max(Comparator.comparingLong(ver -> ver.getDate().getTime()));
workflow.setActualDefaultVersion(max.orElse(null));
}
});
// Delete all non-frozen versions that have the same git reference name and then update the file formats of the entry.
workflows.forEach(workflow -> {
workflow.getWorkflowVersions().removeIf(workflowVersion -> Objects.equals(workflowVersion.getName(), gitReferenceName.get()) && !workflowVersion.isFrozen());
FileFormatHelper.updateEntryLevelFileFormats(workflow);
});
LambdaEvent lambdaEvent = createBasicEvent(repository, gitReference, username, LambdaEvent.LambdaEventType.DELETE);
lambdaEventDAO.create(lambdaEvent);
return workflows;
}
use of io.dockstore.webservice.core.User in project dockstore by dockstore.
the class CollectionResource method createCollection.
@POST
@Timed
@UnitOfWork
@Path("{organizationId}/collections")
@ApiOperation(value = "Create a collection in the given organization.", authorizations = { @Authorization(value = JWT_SECURITY_DEFINITION_NAME) }, response = Collection.class)
@Operation(operationId = "createCollection", summary = "Create a collection in the given organization.", description = "Create a collection in the given organization.", security = @SecurityRequirement(name = "bearer"))
public Collection createCollection(@ApiParam(hidden = true) @Parameter(hidden = true, name = "user") @Auth User user, @ApiParam(value = "Organization ID.", required = true) @Parameter(description = "Organization ID.", name = "organizationId", in = ParameterIn.PATH, required = true) @PathParam("organizationId") Long organizationId, @ApiParam(value = "Collection to register.", required = true) @Parameter(description = "Collection to register.", name = "collection", required = true) Collection collection) {
// First check if the organization exists and that the user is an admin or maintainer
boolean isUserAdminOrMaintainer = OrganizationResource.isUserAdminOrMaintainer(organizationId, user.getId(), organizationDAO);
if (!isUserAdminOrMaintainer) {
String msg = "Organization not found.";
LOG.info(msg);
throw new CustomWebApplicationException(msg, HttpStatus.SC_NOT_FOUND);
}
// Check if any other collections in the organization exist with that name
Collection matchingCollection = collectionDAO.findByNameAndOrg(collection.getName(), organizationId);
if (matchingCollection != null) {
String msg = "A collection already exists with the name '" + collection.getName() + "' in the specified organization.";
LOG.info(msg);
throw new CustomWebApplicationException(msg, HttpStatus.SC_BAD_REQUEST);
}
// Get the organization
Organization organization = organizationDAO.findById(organizationId);
// Save the collection
long id = collectionDAO.create(collection);
organization.addCollection(collection);
// Event for creation
User foundUser = userDAO.findById(user.getId());
Event createCollectionEvent = new Event.Builder().withOrganization(organization).withCollection(collection).withInitiatorUser(foundUser).withType(Event.EventType.CREATE_COLLECTION).build();
eventDAO.create(createCollectionEvent);
return collectionDAO.findById(id);
}
use of io.dockstore.webservice.core.User in project dockstore by dockstore.
the class CollectionResource method deleteEntryFromCollection.
@DELETE
@Timed
@UnitOfWork
@Path("{organizationId}/collections/{collectionId}/entry")
@ApiOperation(value = "Delete an entry from a collection.", authorizations = { @Authorization(value = JWT_SECURITY_DEFINITION_NAME) }, response = Collection.class)
@Operation(operationId = "deleteEntryFromCollection", summary = "Delete an entry to a collection.", description = "Delete an entry to a collection.", security = @SecurityRequirement(name = "bearer"))
public Collection deleteEntryFromCollection(@ApiParam(hidden = true) @Parameter(hidden = true, name = "user") @Auth User user, @ApiParam(value = "Organization ID.", required = true) @Parameter(description = "Organization ID.", name = "organizationId", in = ParameterIn.PATH, required = true) @PathParam("organizationId") Long organizationId, @ApiParam(value = "Collection ID.", required = true) @Parameter(description = "Collection ID.", name = "collectionId", in = ParameterIn.PATH, required = true) @PathParam("collectionId") Long collectionId, @ApiParam(value = "Entry ID", required = true) @Parameter(description = "Entry ID.", name = "entryId", in = ParameterIn.QUERY, required = true) @QueryParam("entryId") Long entryId, @ApiParam(value = "Version ID", required = false) @Parameter(description = "Version ID.", name = "versionId", in = ParameterIn.QUERY, required = false) @QueryParam("versionName") String versionName) {
// Call common code to check if entry and collection exist and return them
ImmutablePair<Entry, Collection> entryAndCollection = commonModifyCollection(organizationId, entryId, collectionId, user);
Long versionId = null;
if (versionName != null) {
Set<Version> workflowVersions = entryAndCollection.getLeft().getWorkflowVersions();
Optional<Version> first = workflowVersions.stream().filter(version -> version.getName().equals(versionName)).findFirst();
if (first.isPresent()) {
versionId = first.get().getId();
} else {
throw new CustomWebApplicationException("Version not found", HttpStatus.SC_NOT_FOUND);
}
}
// Remove the entry from the organization,
// This silently fails if the user somehow manages to give a non-existent entryId and versionId pair
entryAndCollection.getRight().removeEntry(entryAndCollection.getLeft().getId(), versionId);
// Event for deletion
Organization organization = organizationDAO.findById(organizationId);
Event.Builder eventBuild = new Event.Builder().withOrganization(organization).withCollection(entryAndCollection.getRight()).withInitiatorUser(user).withType(Event.EventType.REMOVE_FROM_COLLECTION);
if (entryAndCollection.getLeft() instanceof BioWorkflow) {
eventBuild = eventBuild.withBioWorkflow((BioWorkflow) entryAndCollection.getLeft());
} else if (entryAndCollection.getLeft() instanceof Service) {
eventBuild = eventBuild.withService((Service) entryAndCollection.getLeft());
} else if (entryAndCollection.getLeft() instanceof Tool) {
eventBuild = eventBuild.withTool((Tool) entryAndCollection.getLeft());
}
Event removeFromCollectionEvent = eventBuild.build();
eventDAO.create(removeFromCollectionEvent);
return collectionDAO.findById(collectionId);
}
use of io.dockstore.webservice.core.User in project dockstore by dockstore.
the class SamPermissionsImpl method getApiClient.
private ApiClient getApiClient(User user) {
ApiClient apiClient = new ApiClient() {
@Override
protected void performAdditionalClientConfiguration(ClientConfig clientConfig) {
// Calling ResourcesApi.addUserToPolicy invokes PUT without a body, which will fail
// without this:
clientConfig.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
}
};
apiClient.setBasePath(config.getSamConfiguration().getBasepath());
return googleAccessToken(user).map(credentials -> {
apiClient.setAccessToken(credentials);
return apiClient;
}).orElseThrow(() -> new CustomWebApplicationException("Could not get Google access token. Try relinking your Google account.", HttpStatus.SC_UNAUTHORIZED));
}
Aggregations