Search in sources :

Example 1 with OPENAPI_JWT_SECURITY_DEFINITION_NAME

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()));
}
Also used : Arrays(java.util.Arrays) RolesAllowed(javax.annotation.security.RolesAllowed) Produces(javax.ws.rs.Produces) WorkflowDAO(io.dockstore.webservice.jdbi.WorkflowDAO) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) ApiParam(io.swagger.annotations.ApiParam) Registry(io.dockstore.common.Registry) SourceCodeRepoFactory(io.dockstore.webservice.helpers.SourceCodeRepoFactory) MediaType(javax.ws.rs.core.MediaType) Matcher(java.util.regex.Matcher) Map(java.util.Map) PAGINATION_LIMIT_TEXT(io.dockstore.webservice.resources.ResourceConstants.PAGINATION_LIMIT_TEXT) User(io.dockstore.webservice.core.User) OrganizationUpdateTime(io.dockstore.webservice.core.OrganizationUpdateTime) TokenViews(io.dockstore.webservice.core.TokenViews) Collection(io.dockstore.webservice.core.Collection) SessionFactory(org.hibernate.SessionFactory) Set(java.util.Set) Tool(io.dockstore.webservice.core.Tool) Repository(io.dockstore.common.Repository) CloudInstance(io.dockstore.webservice.core.CloudInstance) EntryUpdateTime(io.dockstore.webservice.core.EntryUpdateTime) PATCH(io.swagger.jaxrs.PATCH) UnitOfWork(io.dropwizard.hibernate.UnitOfWork) Tag(io.swagger.v3.oas.annotations.tags.Tag) PrivilegeRequest(io.dockstore.webservice.api.PrivilegeRequest) LambdaEvent(io.dockstore.webservice.core.LambdaEvent) ApiResponses(io.swagger.v3.oas.annotations.responses.ApiResponses) CachingAuthenticator(io.dropwizard.auth.CachingAuthenticator) PAGINATION_LIMIT(io.dockstore.webservice.resources.ResourceConstants.PAGINATION_LIMIT) GET(javax.ws.rs.GET) JWT_SECURITY_DEFINITION_NAME(io.dockstore.webservice.Constants.JWT_SECURITY_DEFINITION_NAME) PublicStateManager(io.dockstore.webservice.helpers.PublicStateManager) ArrayList(java.util.ArrayList) ServiceDAO(io.dockstore.webservice.jdbi.ServiceDAO) Content(io.swagger.v3.oas.annotations.media.Content) Operation(io.swagger.v3.oas.annotations.Operation) Lists(com.google.common.collect.Lists) EntryDAO(io.dockstore.webservice.jdbi.EntryDAO) HttpClient(org.apache.http.client.HttpClient) EventDAO(io.dockstore.webservice.jdbi.EventDAO) ExtendedUserData(io.dockstore.webservice.core.ExtendedUserData) Api(io.swagger.annotations.Api) Token(io.dockstore.webservice.core.Token) Workflow(io.dockstore.webservice.core.Workflow) UserDAO(io.dockstore.webservice.jdbi.UserDAO) LinkedHashSet(java.util.LinkedHashSet) ToolDAO(io.dockstore.webservice.jdbi.ToolDAO) DeletedUserHelper(io.dockstore.webservice.helpers.DeletedUserHelper) DeletedUsernameDAO(io.dockstore.webservice.jdbi.DeletedUsernameDAO) SourceCodeRepoInterface(io.dockstore.webservice.helpers.SourceCodeRepoInterface) ArraySchema(io.swagger.v3.oas.annotations.media.ArraySchema) Organization(io.dockstore.webservice.core.Organization) TokenDAO(io.dockstore.webservice.jdbi.TokenDAO) MyWorkflows(io.dockstore.webservice.core.database.MyWorkflows) PAGINATION_OFFSET_TEXT(io.dockstore.webservice.resources.ResourceConstants.PAGINATION_OFFSET_TEXT) JsonView(com.fasterxml.jackson.annotation.JsonView) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) HttpStatus(org.apache.http.HttpStatus) DockstoreWebserviceConfiguration(io.dockstore.webservice.DockstoreWebserviceConfiguration) BioWorkflowDAO(io.dockstore.webservice.jdbi.BioWorkflowDAO) OrganizationUser(io.dockstore.webservice.core.OrganizationUser) ApiOperation(io.swagger.annotations.ApiOperation) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) DefaultValue(javax.ws.rs.DefaultValue) TokenType(io.dockstore.webservice.core.TokenType) OPENAPI_JWT_SECURITY_DEFINITION_NAME(io.dockstore.webservice.resources.ResourceConstants.OPENAPI_JWT_SECURITY_DEFINITION_NAME) DELETE(javax.ws.rs.DELETE) DeletedUsername(io.dockstore.webservice.core.DeletedUsername) SecurityRequirement(io.swagger.v3.oas.annotations.security.SecurityRequirement) Schema(io.swagger.v3.oas.annotations.media.Schema) Service(io.dockstore.webservice.core.Service) Timestamp(java.sql.Timestamp) Limits(io.dockstore.webservice.api.Limits) Collectors(java.util.stream.Collectors) GoogleHelper(io.dockstore.webservice.helpers.GoogleHelper) Objects(java.util.Objects) Parameter(io.swagger.v3.oas.annotations.Parameter) Timed(com.codahale.metrics.annotation.Timed) List(java.util.List) EntryLite(io.dockstore.webservice.core.database.EntryLite) BioWorkflow(io.dockstore.webservice.core.BioWorkflow) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) PathParam(javax.ws.rs.PathParam) WorkflowMode(io.dockstore.webservice.core.WorkflowMode) Auth(io.dropwizard.auth.Auth) HashMap(java.util.HashMap) ParameterIn(io.swagger.v3.oas.annotations.enums.ParameterIn) MessageFormat(java.text.MessageFormat) HashSet(java.util.HashSet) EntryVersionHelper(io.dockstore.webservice.helpers.EntryVersionHelper) SourceControl(io.dockstore.common.SourceControl) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse) APPEASE_SWAGGER_PATCH(io.dockstore.webservice.resources.ResourceConstants.APPEASE_SWAGGER_PATCH) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) SourceControlOrganization(io.dockstore.webservice.core.SourceControlOrganization) PermissionsInterface(io.dockstore.webservice.permissions.PermissionsInterface) Entry(io.dockstore.webservice.core.Entry) LambdaEventDAO(io.dockstore.webservice.jdbi.LambdaEventDAO) PUT(javax.ws.rs.PUT) GitHubSourceCodeRepo(io.dockstore.webservice.helpers.GitHubSourceCodeRepo) Comparator(java.util.Comparator) Authorization(io.swagger.annotations.Authorization) Hibernate(org.hibernate.Hibernate) User(io.dockstore.webservice.core.User) OrganizationUser(io.dockstore.webservice.core.OrganizationUser) Workflow(io.dockstore.webservice.core.Workflow) BioWorkflow(io.dockstore.webservice.core.BioWorkflow) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) Token(io.dockstore.webservice.core.Token) SourceControl(io.dockstore.common.SourceControl) SourceCodeRepoInterface(io.dockstore.webservice.helpers.SourceCodeRepoInterface) Path(javax.ws.rs.Path) UnitOfWork(io.dropwizard.hibernate.UnitOfWork) Timed(com.codahale.metrics.annotation.Timed) ApiOperation(io.swagger.annotations.ApiOperation) Operation(io.swagger.v3.oas.annotations.Operation) ApiOperation(io.swagger.annotations.ApiOperation) PATCH(io.swagger.jaxrs.PATCH) APPEASE_SWAGGER_PATCH(io.dockstore.webservice.resources.ResourceConstants.APPEASE_SWAGGER_PATCH)

Example 2 with OPENAPI_JWT_SECURITY_DEFINITION_NAME

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));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) SortedSet(java.util.SortedSet) RolesAllowed(javax.annotation.security.RolesAllowed) Produces(javax.ws.rs.Produces) DatatypeConfigurationException(javax.xml.datatype.DatatypeConfigurationException) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) ApiParam(io.swagger.annotations.ApiParam) HttpStatus(org.apache.http.HttpStatus) DockstoreWebserviceConfiguration(io.dockstore.webservice.DockstoreWebserviceConfiguration) ORCIDHelper(io.dockstore.webservice.helpers.ORCIDHelper) SourceFile(io.dockstore.webservice.core.SourceFile) ApiOperation(io.swagger.annotations.ApiOperation) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) TokenScope(io.dockstore.webservice.core.TokenScope) OPENAPI_JWT_SECURITY_DEFINITION_NAME(io.dockstore.webservice.resources.ResourceConstants.OPENAPI_JWT_SECURITY_DEFINITION_NAME) User(io.dockstore.webservice.core.User) HttpResponse(java.net.http.HttpResponse) SecurityRequirement(io.swagger.v3.oas.annotations.security.SecurityRequirement) Schema(io.swagger.v3.oas.annotations.media.Schema) Service(io.dockstore.webservice.core.Service) Configuration(io.swagger.discourse.client.Configuration) Tool(io.dockstore.webservice.core.Tool) Collectors(java.util.stream.Collectors) JAXBException(javax.xml.bind.JAXBException) ApiException(io.swagger.discourse.client.ApiException) Parameter(io.swagger.v3.oas.annotations.Parameter) Timed(com.codahale.metrics.annotation.Timed) List(java.util.List) VersionVerifiedPlatform(io.dockstore.webservice.core.database.VersionVerifiedPlatform) UnitOfWork(io.dropwizard.hibernate.UnitOfWork) InlineResponse2005(io.swagger.discourse.client.model.InlineResponse2005) Tag(io.swagger.v3.oas.annotations.tags.Tag) BioWorkflow(io.dockstore.webservice.core.BioWorkflow) Optional(java.util.Optional) SecuritySchemeType(io.swagger.v3.oas.annotations.enums.SecuritySchemeType) ApiClient(io.swagger.discourse.client.ApiClient) PathParam(javax.ws.rs.PathParam) DescriptorLanguage(io.dockstore.common.DescriptorLanguage) GET(javax.ws.rs.GET) Auth(io.dropwizard.auth.Auth) JWT_SECURITY_DEFINITION_NAME(io.dockstore.webservice.Constants.JWT_SECURITY_DEFINITION_NAME) SecurityScheme(io.swagger.v3.oas.annotations.security.SecurityScheme) TreeSet(java.util.TreeSet) PublicStateManager(io.dockstore.webservice.helpers.PublicStateManager) TopicsApi(io.swagger.discourse.client.api.TopicsApi) ParameterIn(io.swagger.v3.oas.annotations.enums.ParameterIn) Content(io.swagger.v3.oas.annotations.media.Content) Operation(io.swagger.v3.oas.annotations.Operation) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse) ORCIDHelper.getPutCodeFromLocation(io.dockstore.webservice.helpers.ORCIDHelper.getPutCodeFromLocation) Api(io.swagger.annotations.Api) Token(io.dockstore.webservice.core.Token) UserDAO(io.dockstore.webservice.jdbi.UserDAO) SecuritySchemes(io.swagger.v3.oas.annotations.security.SecuritySchemes) ToolDAO(io.dockstore.webservice.jdbi.ToolDAO) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) MalformedURLException(java.net.MalformedURLException) CollectionOrganization(io.dockstore.webservice.core.CollectionOrganization) IOException(java.io.IOException) VersionDAO(io.dockstore.webservice.jdbi.VersionDAO) Version(io.dockstore.webservice.core.Version) Entry(io.dockstore.webservice.core.Entry) TokenDAO(io.dockstore.webservice.jdbi.TokenDAO) Authorization(io.swagger.annotations.Authorization) Version(io.dockstore.webservice.core.Version) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) SourceFile(io.dockstore.webservice.core.SourceFile) Path(javax.ws.rs.Path) UnitOfWork(io.dropwizard.hibernate.UnitOfWork) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiOperation(io.swagger.annotations.ApiOperation) Operation(io.swagger.v3.oas.annotations.Operation)

Example 3 with OPENAPI_JWT_SECURITY_DEFINITION_NAME

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);
    }
}
Also used : JsonObject(com.google.gson.JsonObject) JsonView(com.fasterxml.jackson.annotation.JsonView) Produces(javax.ws.rs.Produces) URL(java.net.URL) Date(java.util.Date) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) ApiParam(io.swagger.annotations.ApiParam) HttpStatus(org.apache.http.HttpStatus) DockstoreWebserviceConfiguration(io.dockstore.webservice.DockstoreWebserviceConfiguration) GitHubBuilder(org.kohsuke.github.GitHubBuilder) SecureRandom(java.security.SecureRandom) SourceCodeRepoFactory(io.dockstore.webservice.helpers.SourceCodeRepoFactory) ApiOperation(io.swagger.annotations.ApiOperation) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) TokenScope(io.dockstore.webservice.core.TokenScope) Gson(com.google.gson.Gson) Map(java.util.Map) GenericUrl(com.google.api.client.http.GenericUrl) TokenType(io.dockstore.webservice.core.TokenType) OPENAPI_JWT_SECURITY_DEFINITION_NAME(io.dockstore.webservice.resources.ResourceConstants.OPENAPI_JWT_SECURITY_DEFINITION_NAME) User(io.dockstore.webservice.core.User) GitHub(org.kohsuke.github.GitHub) DELETE(javax.ws.rs.DELETE) SecurityRequirement(io.swagger.v3.oas.annotations.security.SecurityRequirement) TokenViews(io.dockstore.webservice.core.TokenViews) GitHubHelper(io.dockstore.webservice.helpers.GitHubHelper) HttpTransport(com.google.api.client.http.HttpTransport) Instant(java.time.Instant) Userinfoplus(com.google.api.services.oauth2.model.Userinfoplus) GoogleHelper(io.dockstore.webservice.helpers.GoogleHelper) Parameter(io.swagger.v3.oas.annotations.Parameter) Timed(com.codahale.metrics.annotation.Timed) List(java.util.List) Response(javax.ws.rs.core.Response) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) UnitOfWork(io.dropwizard.hibernate.UnitOfWork) Tag(io.swagger.v3.oas.annotations.tags.Tag) Optional(java.util.Optional) TOSVersion(io.dockstore.webservice.core.TOSVersion) PathParam(javax.ws.rs.PathParam) CachingAuthenticator(io.dropwizard.auth.CachingAuthenticator) GET(javax.ws.rs.GET) Auth(io.dropwizard.auth.Auth) HashMap(java.util.HashMap) Hashing(com.google.common.hash.Hashing) JWT_SECURITY_DEFINITION_NAME(io.dockstore.webservice.Constants.JWT_SECURITY_DEFINITION_NAME) ApiResponses(io.swagger.annotations.ApiResponses) MessageFormat(java.text.MessageFormat) JsonElement(com.google.gson.JsonElement) JacksonFactory(com.google.api.client.json.jackson.JacksonFactory) Operation(io.swagger.v3.oas.annotations.Operation) HttpClient(org.apache.http.client.HttpClient) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) Api(io.swagger.annotations.Api) Token(io.dockstore.webservice.core.Token) UserDAO(io.dockstore.webservice.jdbi.UserDAO) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) Charsets(com.google.common.base.Charsets) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) DeletedUserHelper(io.dockstore.webservice.helpers.DeletedUserHelper) MalformedURLException(java.net.MalformedURLException) BaseEncoding(com.google.common.io.BaseEncoding) BearerToken(com.google.api.client.auth.oauth2.BearerToken) DeletedUsernameDAO(io.dockstore.webservice.jdbi.DeletedUsernameDAO) IOException(java.io.IOException) PrivacyPolicyVersion(io.dockstore.webservice.core.PrivacyPolicyVersion) JsonFactory(com.google.api.client.json.JsonFactory) ApiResponse(io.swagger.annotations.ApiResponse) GitHubSourceCodeRepo(io.dockstore.webservice.helpers.GitHubSourceCodeRepo) TokenDAO(io.dockstore.webservice.jdbi.TokenDAO) Collections(java.util.Collections) Authorization(io.swagger.annotations.Authorization) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) Token(io.dockstore.webservice.core.Token) BearerToken(com.google.api.client.auth.oauth2.BearerToken) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) Path(javax.ws.rs.Path) UnitOfWork(io.dropwizard.hibernate.UnitOfWork) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) JsonView(com.fasterxml.jackson.annotation.JsonView) ApiOperation(io.swagger.annotations.ApiOperation) Operation(io.swagger.v3.oas.annotations.Operation)

Example 4 with OPENAPI_JWT_SECURITY_DEFINITION_NAME

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);
    }
}
Also used : JsonObject(com.google.gson.JsonObject) JsonView(com.fasterxml.jackson.annotation.JsonView) Produces(javax.ws.rs.Produces) URL(java.net.URL) Date(java.util.Date) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) ApiParam(io.swagger.annotations.ApiParam) HttpStatus(org.apache.http.HttpStatus) DockstoreWebserviceConfiguration(io.dockstore.webservice.DockstoreWebserviceConfiguration) GitHubBuilder(org.kohsuke.github.GitHubBuilder) SecureRandom(java.security.SecureRandom) SourceCodeRepoFactory(io.dockstore.webservice.helpers.SourceCodeRepoFactory) ApiOperation(io.swagger.annotations.ApiOperation) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) TokenScope(io.dockstore.webservice.core.TokenScope) Gson(com.google.gson.Gson) Map(java.util.Map) GenericUrl(com.google.api.client.http.GenericUrl) TokenType(io.dockstore.webservice.core.TokenType) OPENAPI_JWT_SECURITY_DEFINITION_NAME(io.dockstore.webservice.resources.ResourceConstants.OPENAPI_JWT_SECURITY_DEFINITION_NAME) User(io.dockstore.webservice.core.User) GitHub(org.kohsuke.github.GitHub) DELETE(javax.ws.rs.DELETE) SecurityRequirement(io.swagger.v3.oas.annotations.security.SecurityRequirement) TokenViews(io.dockstore.webservice.core.TokenViews) GitHubHelper(io.dockstore.webservice.helpers.GitHubHelper) HttpTransport(com.google.api.client.http.HttpTransport) Instant(java.time.Instant) Userinfoplus(com.google.api.services.oauth2.model.Userinfoplus) GoogleHelper(io.dockstore.webservice.helpers.GoogleHelper) Parameter(io.swagger.v3.oas.annotations.Parameter) Timed(com.codahale.metrics.annotation.Timed) List(java.util.List) Response(javax.ws.rs.core.Response) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) UnitOfWork(io.dropwizard.hibernate.UnitOfWork) Tag(io.swagger.v3.oas.annotations.tags.Tag) Optional(java.util.Optional) TOSVersion(io.dockstore.webservice.core.TOSVersion) PathParam(javax.ws.rs.PathParam) CachingAuthenticator(io.dropwizard.auth.CachingAuthenticator) GET(javax.ws.rs.GET) Auth(io.dropwizard.auth.Auth) HashMap(java.util.HashMap) Hashing(com.google.common.hash.Hashing) JWT_SECURITY_DEFINITION_NAME(io.dockstore.webservice.Constants.JWT_SECURITY_DEFINITION_NAME) ApiResponses(io.swagger.annotations.ApiResponses) MessageFormat(java.text.MessageFormat) JsonElement(com.google.gson.JsonElement) JacksonFactory(com.google.api.client.json.jackson.JacksonFactory) Operation(io.swagger.v3.oas.annotations.Operation) HttpClient(org.apache.http.client.HttpClient) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) Api(io.swagger.annotations.Api) Token(io.dockstore.webservice.core.Token) UserDAO(io.dockstore.webservice.jdbi.UserDAO) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) Charsets(com.google.common.base.Charsets) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) DeletedUserHelper(io.dockstore.webservice.helpers.DeletedUserHelper) MalformedURLException(java.net.MalformedURLException) BaseEncoding(com.google.common.io.BaseEncoding) BearerToken(com.google.api.client.auth.oauth2.BearerToken) DeletedUsernameDAO(io.dockstore.webservice.jdbi.DeletedUsernameDAO) IOException(java.io.IOException) PrivacyPolicyVersion(io.dockstore.webservice.core.PrivacyPolicyVersion) JsonFactory(com.google.api.client.json.JsonFactory) ApiResponse(io.swagger.annotations.ApiResponse) GitHubSourceCodeRepo(io.dockstore.webservice.helpers.GitHubSourceCodeRepo) TokenDAO(io.dockstore.webservice.jdbi.TokenDAO) Collections(java.util.Collections) Authorization(io.swagger.annotations.Authorization) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) Token(io.dockstore.webservice.core.Token) BearerToken(com.google.api.client.auth.oauth2.BearerToken) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) Path(javax.ws.rs.Path) UnitOfWork(io.dropwizard.hibernate.UnitOfWork) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) JsonView(com.fasterxml.jackson.annotation.JsonView) ApiOperation(io.swagger.annotations.ApiOperation) Operation(io.swagger.v3.oas.annotations.Operation)

Example 5 with OPENAPI_JWT_SECURITY_DEFINITION_NAME

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());
}
Also used : WorkflowVersion(io.dockstore.webservice.core.WorkflowVersion) Arrays(java.util.Arrays) RolesAllowed(javax.annotation.security.RolesAllowed) Produces(javax.ws.rs.Produces) WorkflowDAO(io.dockstore.webservice.jdbi.WorkflowDAO) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) ApiParam(io.swagger.annotations.ApiParam) ServiceEntryDAO(io.dockstore.webservice.jdbi.ServiceEntryDAO) SourceFile(io.dockstore.webservice.core.SourceFile) StarRequest(io.dockstore.webservice.api.StarRequest) SourceCodeRepoFactory(io.dockstore.webservice.helpers.SourceCodeRepoFactory) MediaType(javax.ws.rs.core.MediaType) Matcher(java.util.regex.Matcher) Map(java.util.Map) LabelDAO(io.dockstore.webservice.jdbi.LabelDAO) User(io.dockstore.webservice.core.User) FileType(io.dockstore.common.DescriptorLanguage.FileType) DescriptorType(io.swagger.model.DescriptorType) SessionFactory(org.hibernate.SessionFactory) Set(java.util.Set) Tool(io.dockstore.webservice.core.Tool) PATCH(io.swagger.jaxrs.PATCH) UnitOfWork(io.dropwizard.hibernate.UnitOfWork) Tag(io.swagger.v3.oas.annotations.tags.Tag) OPTIONAL_AUTH_MESSAGE(io.dockstore.webservice.Constants.OPTIONAL_AUTH_MESSAGE) DOCKSTORE_YML(io.dockstore.webservice.core.WorkflowMode.DOCKSTORE_YML) SharedWorkflows(io.dockstore.webservice.permissions.SharedWorkflows) LambdaEvent(io.dockstore.webservice.core.LambdaEvent) AliasHelper(io.dockstore.webservice.helpers.AliasHelper) DescriptorLanguage(io.dockstore.common.DescriptorLanguage) GET(javax.ws.rs.GET) LocalDateTime(java.time.LocalDateTime) JWT_SECURITY_DEFINITION_NAME(io.dockstore.webservice.Constants.JWT_SECURITY_DEFINITION_NAME) VERSION_PAGINATION_LIMIT(io.dockstore.webservice.resources.ResourceConstants.VERSION_PAGINATION_LIMIT) TreeSet(java.util.TreeSet) PublicStateManager(io.dockstore.webservice.helpers.PublicStateManager) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) Content(io.swagger.v3.oas.annotations.media.Content) Operation(io.swagger.v3.oas.annotations.Operation) EntryDAO(io.dockstore.webservice.jdbi.EntryDAO) LanguageHandlerFactory(io.dockstore.webservice.languages.LanguageHandlerFactory) HttpClient(org.apache.http.client.HttpClient) FileFormatDAO(io.dockstore.webservice.jdbi.FileFormatDAO) SourceControlConverter(io.dockstore.webservice.core.SourceControlConverter) Checksum(io.dockstore.webservice.core.Checksum) Token(io.dockstore.webservice.core.Token) Workflow(io.dockstore.webservice.core.Workflow) ToolDAO(io.dockstore.webservice.jdbi.ToolDAO) FileFormatHelper(io.dockstore.webservice.helpers.FileFormatHelper) URIHelper(io.dockstore.webservice.helpers.URIHelper) MoreObjects(com.google.common.base.MoreObjects) SourceCodeRepoInterface(io.dockstore.webservice.helpers.SourceCodeRepoInterface) VersionDAO(io.dockstore.webservice.jdbi.VersionDAO) WDL(io.dockstore.common.DescriptorLanguage.WDL) ArraySchema(io.swagger.v3.oas.annotations.media.ArraySchema) Paths(java.nio.file.Paths) Version(io.dockstore.webservice.core.Version) SortedSet(java.util.SortedSet) Date(java.util.Date) URISyntaxException(java.net.URISyntaxException) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) HttpStatus(org.apache.http.HttpStatus) DockstoreWebserviceConfiguration(io.dockstore.webservice.DockstoreWebserviceConfiguration) BioWorkflowDAO(io.dockstore.webservice.jdbi.BioWorkflowDAO) ApiOperation(io.swagger.annotations.ApiOperation) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) ZenodoHelper(io.dockstore.webservice.helpers.ZenodoHelper) MutablePair(org.apache.commons.lang3.tuple.MutablePair) DefaultValue(javax.ws.rs.DefaultValue) TokenType(io.dockstore.webservice.core.TokenType) OPENAPI_JWT_SECURITY_DEFINITION_NAME(io.dockstore.webservice.resources.ResourceConstants.OPENAPI_JWT_SECURITY_DEFINITION_NAME) DELETE(javax.ws.rs.DELETE) SecurityRequirement(io.swagger.v3.oas.annotations.security.SecurityRequirement) Schema(io.swagger.v3.oas.annotations.media.Schema) Service(io.dockstore.webservice.core.Service) Context(javax.ws.rs.core.Context) StreamingOutput(javax.ws.rs.core.StreamingOutput) Collectors(java.util.stream.Collectors) CWL(io.dockstore.common.DescriptorLanguage.CWL) Objects(java.util.Objects) Parameter(io.swagger.v3.oas.annotations.Parameter) Timed(com.codahale.metrics.annotation.Timed) List(java.util.List) Response(javax.ws.rs.core.Response) BioWorkflow(io.dockstore.webservice.core.BioWorkflow) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) PublishRequest(io.dockstore.webservice.api.PublishRequest) FilenameUtils(org.apache.commons.io.FilenameUtils) PathParam(javax.ws.rs.PathParam) Image(io.dockstore.webservice.core.Image) MetadataResourceHelper(io.dockstore.webservice.helpers.MetadataResourceHelper) WorkflowMode(io.dockstore.webservice.core.WorkflowMode) Auth(io.dropwizard.auth.Auth) ToolsImplCommon(io.swagger.api.impl.ToolsImplCommon) HashMap(java.util.HashMap) ParameterIn(io.swagger.v3.oas.annotations.enums.ParameterIn) HashSet(java.util.HashSet) EntryVersionHelper(io.dockstore.webservice.helpers.EntryVersionHelper) SourceControl(io.dockstore.common.SourceControl) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse) ApiClient(io.swagger.zenodo.client.ApiClient) FormParam(javax.ws.rs.FormParam) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) HttpServletResponse(javax.servlet.http.HttpServletResponse) StateManagerMode(io.dockstore.webservice.helpers.StateManagerMode) Beta(com.google.common.annotations.Beta) PermissionsInterface(io.dockstore.webservice.permissions.PermissionsInterface) Role(io.dockstore.webservice.permissions.Role) LanguageHandlerInterface(io.dockstore.webservice.languages.LanguageHandlerInterface) Entry(io.dockstore.webservice.core.Entry) PUT(javax.ws.rs.PUT) Permission(io.dockstore.webservice.permissions.Permission) Authorization(io.swagger.annotations.Authorization) Hibernate(org.hibernate.Hibernate) DescriptorLanguage(io.dockstore.common.DescriptorLanguage) Workflow(io.dockstore.webservice.core.Workflow) BioWorkflow(io.dockstore.webservice.core.BioWorkflow) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) SourceControl(io.dockstore.common.SourceControl) SourceCodeRepoInterface(io.dockstore.webservice.helpers.SourceCodeRepoInterface) Path(javax.ws.rs.Path) UnitOfWork(io.dropwizard.hibernate.UnitOfWork) POST(javax.ws.rs.POST) Timed(com.codahale.metrics.annotation.Timed) ApiOperation(io.swagger.annotations.ApiOperation) Operation(io.swagger.v3.oas.annotations.Operation) ApiOperation(io.swagger.annotations.ApiOperation)

Aggregations

Timed (com.codahale.metrics.annotation.Timed)9 JWT_SECURITY_DEFINITION_NAME (io.dockstore.webservice.Constants.JWT_SECURITY_DEFINITION_NAME)9 CustomWebApplicationException (io.dockstore.webservice.CustomWebApplicationException)9 DockstoreWebserviceConfiguration (io.dockstore.webservice.DockstoreWebserviceConfiguration)9 Token (io.dockstore.webservice.core.Token)9 User (io.dockstore.webservice.core.User)9 OPENAPI_JWT_SECURITY_DEFINITION_NAME (io.dockstore.webservice.resources.ResourceConstants.OPENAPI_JWT_SECURITY_DEFINITION_NAME)9 Auth (io.dropwizard.auth.Auth)9 UnitOfWork (io.dropwizard.hibernate.UnitOfWork)9 ApiOperation (io.swagger.annotations.ApiOperation)9 ApiParam (io.swagger.annotations.ApiParam)9 Authorization (io.swagger.annotations.Authorization)9 Operation (io.swagger.v3.oas.annotations.Operation)9 Parameter (io.swagger.v3.oas.annotations.Parameter)9 SecurityRequirement (io.swagger.v3.oas.annotations.security.SecurityRequirement)9 List (java.util.List)9 Optional (java.util.Optional)9 GET (javax.ws.rs.GET)9 POST (javax.ws.rs.POST)9 Path (javax.ws.rs.Path)9