Search in sources :

Example 1 with OrcidBadRequestException

use of org.orcid.core.exception.OrcidBadRequestException in project ORCID-Source by ORCID.

the class OrcidApiServiceDelegatorImpl method validateRows.

private void validateRows(Map<String, List<String>> queryMap) {
    List<String> rowsList = queryMap.get("rows");
    if (rowsList != null && !rowsList.isEmpty()) {
        try {
            String rowsString = rowsList.get(0);
            int rows = Integer.valueOf(rowsString);
            if (rows < 0 || rows > MAX_SEARCH_ROWS) {
                throw new OrcidBadRequestException(localeManager.resolveMessage("apiError.badrequest_invalid_search_rows.exception"));
            }
        } catch (NumberFormatException e) {
            throw new OrcidBadRequestException(localeManager.resolveMessage("apiError.badrequest_invalid_search_rows.exception"));
        }
    }
}
Also used : OrcidBadRequestException(org.orcid.core.exception.OrcidBadRequestException)

Example 2 with OrcidBadRequestException

use of org.orcid.core.exception.OrcidBadRequestException in project ORCID-Source by ORCID.

the class T2OrcidApiServiceDelegatorImpl method addExternalIdentifiers.

/**
     * Add new external identifiers to the profile. As with all calls, if the
     * message contains any other elements, a 400 Bad Request will be returned.
     * 
     * @param orcidMessage
     *            the message congtaining the external ids
     * @return If successful, returns a 200 OK with the updated content.
     */
@Override
@AccessControl(requiredScope = ScopePathType.ORCID_BIO_EXTERNAL_IDENTIFIERS_CREATE)
public Response addExternalIdentifiers(UriInfo uriInfo, String orcid, OrcidMessage orcidMessage) {
    OrcidProfile orcidProfile = orcidMessage.getOrcidProfile();
    try {
        ExternalIdentifiers updatedExternalIdentifiers = orcidProfile.getOrcidBio().getExternalIdentifiers();
        // Get the client profile information
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String clientId = null;
        if (OAuth2Authentication.class.isAssignableFrom(authentication.getClass())) {
            OAuth2Request authorizationRequest = ((OAuth2Authentication) authentication).getOAuth2Request();
            clientId = authorizationRequest.getClientId();
        }
        for (ExternalIdentifier ei : updatedExternalIdentifiers.getExternalIdentifier()) {
            // Set the client profile to each external identifier
            if (ei.getSource() == null) {
                Source source = new Source();
                source.setSourceClientId(new SourceClientId(clientId));
                ei.setSource(source);
            } else {
                // Check if the provided external orcid exists
                Source source = ei.getSource();
                String sourceOrcid = source.retrieveSourcePath();
                if (sourceOrcid != null) {
                    if (StringUtils.isBlank(sourceOrcid) || (!profileEntityManager.orcidExists(sourceOrcid) && !clientDetailsManager.exists(sourceOrcid))) {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("orcid", sourceOrcid);
                        throw new OrcidNotFoundException(params);
                    }
                }
            }
        }
        orcidProfile = orcidProfileManager.addExternalIdentifiers(orcidProfile);
        return getOrcidMessageResponse(orcidProfile, orcid);
    } catch (DataAccessException e) {
        throw new OrcidBadRequestException(localeManager.resolveMessage("apiError.badrequest_createorcid.exception"));
    }
}
Also used : ExternalIdentifier(org.orcid.jaxb.model.message.ExternalIdentifier) HashMap(java.util.HashMap) SourceClientId(org.orcid.jaxb.model.message.SourceClientId) Source(org.orcid.jaxb.model.message.Source) OrcidProfile(org.orcid.jaxb.model.message.OrcidProfile) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OrcidBadRequestException(org.orcid.core.exception.OrcidBadRequestException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OrcidNotFoundException(org.orcid.core.exception.OrcidNotFoundException) ExternalIdentifiers(org.orcid.jaxb.model.message.ExternalIdentifiers) DataAccessException(org.springframework.dao.DataAccessException) AccessControl(org.orcid.core.security.visibility.aop.AccessControl)

Example 3 with OrcidBadRequestException

use of org.orcid.core.exception.OrcidBadRequestException in project ORCID-Source by ORCID.

the class T2OrcidApiServiceDelegatorImpl method registerWebhook.

/**
     * Register a new webhook to the profile. As with all calls, if the message
     * contains any other elements, a 400 Bad Request will be returned.
     * 
     * @param orcid
     *            the identifier of the profile to add the webhook
     * @param uriInfo
     *            an uri object containing the webhook
     * @return If successful, returns a 2xx.
     * */
@Override
@AccessControl(requiredScope = ScopePathType.WEBHOOK)
public Response registerWebhook(UriInfo uriInfo, String orcid, String webhookUri) {
    @SuppressWarnings("unused") URI validatedWebhookUri = null;
    try {
        validatedWebhookUri = new URI(webhookUri);
    } catch (URISyntaxException e) {
        Object[] params = { webhookUri };
        throw new OrcidBadRequestException(localeManager.resolveMessage("apiError.badrequest_incorrect_webhook.exception", params));
    }
    ProfileEntity profile = profileEntityCacheManager.retrieve(orcid);
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    ClientDetailsEntity clientDetails = null;
    String clientId = null;
    if (OAuth2Authentication.class.isAssignableFrom(authentication.getClass())) {
        OAuth2Request authorizationRequest = ((OAuth2Authentication) authentication).getOAuth2Request();
        clientId = authorizationRequest.getClientId();
        clientDetails = clientDetailsManager.findByClientId(clientId);
    }
    if (profile != null && clientDetails != null) {
        WebhookEntityPk webhookPk = new WebhookEntityPk(profile, webhookUri);
        WebhookEntity webhook = webhookManager.find(webhookPk);
        boolean isNew = webhook == null;
        if (isNew) {
            webhook = new WebhookEntity();
            webhook.setProfile(profile);
            webhook.setDateCreated(new Date());
            webhook.setEnabled(true);
            webhook.setUri(webhookUri);
            webhook.setClientDetails(clientDetails);
        }
        webhookManager.update(webhook);
        return isNew ? Response.created(uriInfo.getAbsolutePath()).build() : Response.noContent().build();
    } else if (profile == null) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("orcid", orcid);
        throw new OrcidNotFoundException(params);
    } else {
        Map<String, String> params = new HashMap<String, String>();
        params.put("client", clientId);
        throw new OrcidClientNotFoundException(params);
    }
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) WebhookEntityPk(org.orcid.persistence.jpa.entities.keys.WebhookEntityPk) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) Date(java.util.Date) SubmissionDate(org.orcid.jaxb.model.message.SubmissionDate) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OrcidBadRequestException(org.orcid.core.exception.OrcidBadRequestException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) WebhookEntity(org.orcid.persistence.jpa.entities.WebhookEntity) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OrcidNotFoundException(org.orcid.core.exception.OrcidNotFoundException) Map(java.util.Map) HashMap(java.util.HashMap) OrcidClientNotFoundException(org.orcid.core.exception.OrcidClientNotFoundException) AccessControl(org.orcid.core.security.visibility.aop.AccessControl)

Example 4 with OrcidBadRequestException

use of org.orcid.core.exception.OrcidBadRequestException in project ORCID-Source by ORCID.

the class T2OrcidApiServiceDelegatorImpl method createProfile.

/**
     * Creates a new profile and returns the saved representation of it. The
     * response should include the 'location' to retrieve the newly created
     * profile from.
     * 
     * @param orcidMessage
     *            the message to be saved. If the message already contains an
     *            ORCID value a 400 Bad Request
     * @return if the creation was successful, returns a 201 along with the
     *         location of the newly created resource otherwise returns an error
     *         response describing the problem
     */
@Override
@AccessControl(requiredScope = ScopePathType.ORCID_PROFILE_CREATE)
public Response createProfile(UriInfo uriInfo, OrcidMessage orcidMessage) {
    OrcidProfile orcidProfile = orcidMessage.getOrcidProfile();
    try {
        setSponsorFromAuthentication(orcidProfile);
        orcidProfile = orcidProfileManager.createOrcidProfileAndNotify(orcidProfile);
        return getCreatedResponse(uriInfo, PROFILE_GET_PATH, orcidProfile);
    } catch (DataAccessException e) {
        if (e.getCause() != null && ConstraintViolationException.class.isAssignableFrom(e.getCause().getClass())) {
            throw new OrcidBadRequestException(localeManager.resolveMessage("apiError.badrequest_email_exists.exception"));
        }
        throw new OrcidBadRequestException(localeManager.resolveMessage("apiError.badrequest_createorcid.exception"), e);
    }
}
Also used : OrcidProfile(org.orcid.jaxb.model.message.OrcidProfile) OrcidBadRequestException(org.orcid.core.exception.OrcidBadRequestException) DataAccessException(org.springframework.dao.DataAccessException) AccessControl(org.orcid.core.security.visibility.aop.AccessControl)

Example 5 with OrcidBadRequestException

use of org.orcid.core.exception.OrcidBadRequestException in project ORCID-Source by ORCID.

the class ClaimController method submitClaimJson.

@RequestMapping(value = "/claim/{encryptedEmail}.json", method = RequestMethod.POST)
@ResponseBody
public Claim submitClaimJson(HttpServletRequest request, HttpServletResponse response, @PathVariable("encryptedEmail") String encryptedEmail, @RequestBody Claim claim) throws NoSuchRequestHandlingMethodException, UnsupportedEncodingException {
    claim.setErrors(new ArrayList<String>());
    String decryptedEmail = encryptionManager.decryptForExternalUse(new String(Base64.decodeBase64(encryptedEmail), "UTF-8")).trim();
    if (!isEmailOkForCurrentUser(decryptedEmail)) {
        claim.setUrl(getBaseUri() + "/claim/wrong_user");
        return claim;
    }
    String orcid = emailManager.findOrcidIdByEmail(decryptedEmail);
    if (PojoUtil.isEmpty(orcid)) {
        throw new OrcidBadRequestException("Unable to find an ORCID ID for the given email: " + decryptedEmail);
    }
    ProfileEntity profile = profileEntityCacheManager.retrieve(orcid);
    if (profile != null && profile.getClaimed() != null && profile.getClaimed()) {
        // Already claimed so send to sign in page
        claim.setUrl(getBaseUri() + "/signin?alreadyClaimed");
        return claim;
    }
    claimPasswordValidate(claim);
    claimPasswordConfirmValidate(claim);
    claimTermsOfUseValidate(claim);
    copyErrors(claim.getPassword(), claim);
    copyErrors(claim.getPasswordConfirm(), claim);
    copyErrors(claim.getTermsOfUse(), claim);
    if (claim.getErrors().size() > 0) {
        return claim;
    }
    // Do it in a transaction
    try {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {

            public void doInTransactionWithoutResult(TransactionStatus status) {
                Locale requestLocale = RequestContextUtils.getLocale(request);
                org.orcid.jaxb.model.common_v2.Locale userLocale = (requestLocale == null) ? null : org.orcid.jaxb.model.common_v2.Locale.fromValue(requestLocale.toString());
                boolean claimed = profileEntityManager.claimProfileAndUpdatePreferences(orcid, decryptedEmail, userLocale, claim);
                if (!claimed) {
                    throw new IllegalStateException("Unable to claim record " + orcid);
                }
                // Update the password
                profileEntityManager.updatePassword(orcid, claim.getPassword().getValue());
                // Notify
                notificationManager.sendAmendEmail(orcid, AmendedSection.UNKNOWN, null);
            }
        });
    } catch (Exception e) {
        throw new InvalidRequestException("Unable to claim record due: " + e.getMessage(), e.getCause());
    }
    automaticallyLogin(request, claim.getPassword().getValue(), orcid);
    // detech this situation
    String targetUrl = orcidUrlManager.determineFullTargetUrlFromSavedRequest(request, response);
    if (targetUrl == null)
        claim.setUrl(getBaseUri() + "/my-orcid?recordClaimed");
    else
        claim.setUrl(targetUrl);
    return claim;
}
Also used : Locale(java.util.Locale) OrcidBadRequestException(org.orcid.core.exception.OrcidBadRequestException) TransactionStatus(org.springframework.transaction.TransactionStatus) InvalidRequestException(org.springframework.security.oauth2.common.exceptions.InvalidRequestException) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) NoSuchRequestHandlingMethodException(org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException) AuthenticationException(org.springframework.security.core.AuthenticationException) OrcidBadRequestException(org.orcid.core.exception.OrcidBadRequestException) InvalidRequestException(org.springframework.security.oauth2.common.exceptions.InvalidRequestException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) EncryptionOperationNotPossibleException(org.jasypt.exceptions.EncryptionOperationNotPossibleException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Aggregations

OrcidBadRequestException (org.orcid.core.exception.OrcidBadRequestException)12 URI (java.net.URI)3 AccessControl (org.orcid.core.security.visibility.aop.AccessControl)3 InBoundHeaders (com.sun.jersey.core.header.InBoundHeaders)2 ContainerRequest (com.sun.jersey.spi.container.ContainerRequest)2 WebApplication (com.sun.jersey.spi.container.WebApplication)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 HashMap (java.util.HashMap)2 Test (org.junit.Test)2 OrcidNotFoundException (org.orcid.core.exception.OrcidNotFoundException)2 OrcidProfile (org.orcid.jaxb.model.message.OrcidProfile)2 ProfileEntity (org.orcid.persistence.jpa.entities.ProfileEntity)2 DataAccessException (org.springframework.dao.DataAccessException)2 Authentication (org.springframework.security.core.Authentication)2 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)2 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 URISyntaxException (java.net.URISyntaxException)1 Date (java.util.Date)1 Locale (java.util.Locale)1