Search in sources :

Example 1 with TokenScope

use of io.dockstore.webservice.core.TokenScope in project dockstore by dockstore.

the class TokenResource method addOrcidToken.

@POST
@Timed
@UnitOfWork
@Path("/orcid.org")
@JsonView(TokenViews.User.class)
@ApiOperation(value = orcidSummary, authorizations = { @Authorization(value = JWT_SECURITY_DEFINITION_NAME) }, notes = orcidDescription, response = Token.class)
@Operation(operationId = "addOrcidToken", summary = orcidSummary, description = orcidDescription, security = @SecurityRequirement(name = "bearer"))
public Token addOrcidToken(@ApiParam(hidden = true) @Parameter(hidden = true, name = "user") @Auth final User user, @QueryParam("code") final String code) {
    String accessToken;
    String refreshToken;
    String username;
    String orcid;
    String scope;
    long expirationTime;
    if (code == null || 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(orcidUrl + "oauth/token"), new ClientParametersAuthentication(orcidClientID, orcidClientSecret), orcidClientID, orcidUrl + "/authorize").build();
    try {
        TokenResponse tokenResponse = flow.newTokenRequest(code).setScopes(Collections.singletonList(orcidScope)).setRequestInitializer(request -> request.getHeaders().setAccept(MediaType.APPLICATION_JSON)).execute();
        accessToken = tokenResponse.getAccessToken();
        refreshToken = tokenResponse.getRefreshToken();
        // ORCID API returns the username and orcid id along with the tokens
        // get them to store in the token and user tables
        username = tokenResponse.get("name").toString();
        orcid = tokenResponse.get("orcid").toString();
        scope = tokenResponse.getScope();
        Instant instant = Instant.now();
        instant.plusSeconds(tokenResponse.getExpiresInSeconds());
        expirationTime = instant.getEpochSecond();
    } catch (IOException e) {
        LOG.error("Retrieving accessToken was unsuccessful" + e.getMessage(), e);
        throw new CustomWebApplicationException(e.getMessage(), HttpStatus.SC_BAD_REQUEST);
    }
    if (user != null) {
        // save the ORCID to the enduser table
        User byId = userDAO.findById(user.getId());
        byId.setOrcid(orcid);
        Token token = new Token();
        token.setTokenSource(TokenType.ORCID_ORG);
        token.setContent(accessToken);
        token.setRefreshToken(refreshToken);
        token.setUserId(user.getId());
        token.setUsername(username);
        TokenScope tokenScope = TokenScope.getEnumByString(scope);
        if (tokenScope == null) {
            LOG.error("Could not convert scope string to enum: " + scope);
            throw new CustomWebApplicationException("Could not save ORCID token, contact Dockstore team", HttpStatus.SC_INTERNAL_SERVER_ERROR);
        }
        token.setScope(tokenScope);
        token.setExpirationTime(expirationTime);
        checkIfAccountHasBeenLinked(token, TokenType.ORCID_ORG);
        long create = tokenDAO.create(token);
        LOG.info("ORCID 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) User(io.dockstore.webservice.core.User) Instant(java.time.Instant) 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) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) TokenScope(io.dockstore.webservice.core.TokenScope) 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) JsonView(com.fasterxml.jackson.annotation.JsonView) ApiOperation(io.swagger.annotations.ApiOperation) Operation(io.swagger.v3.oas.annotations.Operation)

Aggregations

Timed (com.codahale.metrics.annotation.Timed)1 JsonView (com.fasterxml.jackson.annotation.JsonView)1 AuthorizationCodeFlow (com.google.api.client.auth.oauth2.AuthorizationCodeFlow)1 BearerToken (com.google.api.client.auth.oauth2.BearerToken)1 ClientParametersAuthentication (com.google.api.client.auth.oauth2.ClientParametersAuthentication)1 TokenResponse (com.google.api.client.auth.oauth2.TokenResponse)1 GenericUrl (com.google.api.client.http.GenericUrl)1 HttpTransport (com.google.api.client.http.HttpTransport)1 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)1 JsonFactory (com.google.api.client.json.JsonFactory)1 JacksonFactory (com.google.api.client.json.jackson.JacksonFactory)1 Userinfoplus (com.google.api.services.oauth2.model.Userinfoplus)1 Charsets (com.google.common.base.Charsets)1 Hashing (com.google.common.hash.Hashing)1 BaseEncoding (com.google.common.io.BaseEncoding)1 Gson (com.google.gson.Gson)1 JsonElement (com.google.gson.JsonElement)1 JsonObject (com.google.gson.JsonObject)1 JWT_SECURITY_DEFINITION_NAME (io.dockstore.webservice.Constants.JWT_SECURITY_DEFINITION_NAME)1 CustomWebApplicationException (io.dockstore.webservice.CustomWebApplicationException)1