Search in sources :

Example 36 with NoResultException

use of javax.persistence.NoResultException in project ORCID-Source by ORCID.

the class MemberV3ApiServiceDelegator_ServicesTest method testDeleteService.

@Test
public void testDeleteService() {
    SecurityContextTestUtils.setUpSecurityContext("0000-0000-0000-0002", ScopePathType.READ_LIMITED, ScopePathType.ACTIVITIES_UPDATE);
    Response response = serviceDelegator.viewService("0000-0000-0000-0002", 1006L);
    assertNotNull(response);
    Service service = (Service) response.getEntity();
    assertNotNull(service);
    response = serviceDelegator.deleteAffiliation("0000-0000-0000-0002", 1006L);
    assertNotNull(response);
    assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());
    try {
        serviceDelegator.viewService("0000-0000-0000-0002", 1006L);
        fail();
    } catch (NoResultException nre) {
    } catch (Exception e) {
        fail();
    }
}
Also used : Response(javax.ws.rs.core.Response) Service(org.orcid.jaxb.model.v3.dev1.record.Service) NoResultException(javax.persistence.NoResultException) NoResultException(javax.persistence.NoResultException) VisibilityMismatchException(org.orcid.core.exception.VisibilityMismatchException) WrongSourceException(org.orcid.core.exception.WrongSourceException) OrcidDuplicatedActivityException(org.orcid.core.exception.OrcidDuplicatedActivityException) OrcidValidationException(org.orcid.core.exception.OrcidValidationException) OrcidAccessControlException(org.orcid.core.exception.OrcidAccessControlException) OrcidVisibilityException(org.orcid.core.exception.OrcidVisibilityException) OrcidUnauthorizedException(org.orcid.core.exception.OrcidUnauthorizedException) DBUnitTest(org.orcid.test.DBUnitTest) Test(org.junit.Test)

Example 37 with NoResultException

use of javax.persistence.NoResultException in project ORCID-Source by ORCID.

the class PasswordResetController method issuePasswordResetRequest.

@RequestMapping(value = "/reset-password.json", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<EmailRequest> issuePasswordResetRequest(HttpServletRequest request, @RequestBody EmailRequest passwordResetRequest) {
    for (String param : request.getParameterMap().keySet()) {
        if (!RESET_PASSWORD_PARAMS_WHITELIST.contains(param)) {
            // found parameter that has not been white-listed
            return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY);
        }
    }
    List<String> errors = new ArrayList<>();
    passwordResetRequest.setErrors(errors);
    if (!validateEmailAddress(passwordResetRequest.getEmail())) {
        errors.add(getMessage("Email.resetPasswordForm.invalidEmail"));
        return new ResponseEntity<>(passwordResetRequest, HttpStatus.OK);
    }
    try {
        String orcid = emailManager.findOrcidIdByEmail(passwordResetRequest.getEmail());
        ProfileEntity profile = profileEntityCacheManager.retrieve(orcid);
        if (profile == null) {
            String message = getMessage("orcid.frontend.reset.password.email_not_found_1") + " " + passwordResetRequest.getEmail() + " " + getMessage("orcid.frontend.reset.password.email_not_found_2");
            message += "<a href=\"mailto:support@orcid.org\">";
            message += getMessage("orcid.frontend.reset.password.email_not_found_3");
            message += "</a>";
            message += getMessage("orcid.frontend.reset.password.email_not_found_4");
            errors.add(message);
            return new ResponseEntity<>(passwordResetRequest, HttpStatus.OK);
        }
        if (profile.getDeactivationDate() != null) {
            String message = getMessage("orcid.frontend.reset.password.disabled_account_1");
            message += "<a href=\"/help/contact-us\">";
            message += getMessage("orcid.frontend.reset.password.disabled_account_2");
            message += "</a>";
            errors.add(message);
            return new ResponseEntity<>(passwordResetRequest, HttpStatus.OK);
        }
        registrationManager.resetUserPassword(passwordResetRequest.getEmail(), orcid, profile.getClaimed());
        passwordResetRequest.setSuccessMessage(getMessage("orcid.frontend.reset.password.successfulReset") + " " + passwordResetRequest.getEmail());
    } catch (NoResultException nre) {
        errors.add(getMessage("Email.resetPasswordForm.error"));
    }
    return new ResponseEntity<>(passwordResetRequest, HttpStatus.OK);
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) ArrayList(java.util.ArrayList) NoResultException(javax.persistence.NoResultException) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 38 with NoResultException

use of javax.persistence.NoResultException in project ORCID-Source by ORCID.

the class OrcidRefreshTokenChecker method validateRequest.

public void validateRequest(String grantType, TokenRequest tokenRequest, Long requestTimeInMillis) {
    String authorization = tokenRequest.getRequestParameters().get(OrcidOauth2Constants.AUTHORIZATION);
    String clientId = tokenRequest.getClientId();
    String scopes = tokenRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
    Long expireIn = tokenRequest.getRequestParameters().containsKey(OrcidOauth2Constants.EXPIRES_IN) ? Long.valueOf(tokenRequest.getRequestParameters().get(OrcidOauth2Constants.EXPIRES_IN)) : 0L;
    String refreshToken = tokenRequest.getRequestParameters().get(OrcidOauth2Constants.REFRESH_TOKEN);
    OrcidOauth2TokenDetail token = null;
    try {
        token = orcidOauth2TokenDetailDao.findByRefreshTokenValue(refreshToken);
    } catch (NoResultException e) {
        throw new InvalidTokenException("Unable to find refresh token", e);
    }
    // Verify the token belongs to this client
    if (!clientId.equals(token.getClientDetailsId())) {
        throw new IllegalArgumentException("This token does not belong to the given client");
    }
    // Verify client is enabled
    ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
    orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
    // Verify the token is not expired
    if (token.getTokenExpiration() != null) {
        if (token.getTokenExpiration().before(new Date())) {
            throw new InvalidTokenException("Access token expired: " + authorization);
        }
    }
    // Verify access token and refresh token are linked
    if (!refreshToken.equals(token.getRefreshTokenValue())) {
        throw new InvalidTokenException("Token and refresh token does not match");
    }
    // Verify the token is not disabled
    if (token.getTokenDisabled() != null && token.getTokenDisabled()) {
        throw new InvalidTokenException("Parent token is disabled");
    }
    // Verify scopes are not wider than the token scopes
    if (PojoUtil.isEmpty(scopes)) {
        scopes = token.getScope();
    } else {
        Set<ScopePathType> requiredScopes = ScopePathType.getScopesFromSpaceSeparatedString(scopes);
        Set<ScopePathType> simpleTokenScopes = ScopePathType.getScopesFromSpaceSeparatedString(token.getScope());
        // This collection contains all tokens that should be allowed given
        // the scopes that the parent token contains
        Set<ScopePathType> combinedTokenScopes = new HashSet<ScopePathType>();
        for (ScopePathType scope : simpleTokenScopes) {
            combinedTokenScopes.addAll(scope.combined());
        }
        // combinedTokenScopes
        for (ScopePathType scope : requiredScopes) {
            if (!combinedTokenScopes.contains(scope)) {
                throw new InvalidScopeException("The given scope '" + scope.value() + "' is not allowed for the parent token");
            }
        }
    }
    // Validate the expiration for the new token is no later than the parent
    // token expiration.
    long parentTokenExpiration = token.getTokenExpiration() == null ? System.currentTimeMillis() : token.getTokenExpiration().getTime();
    if (expireIn > parentTokenExpiration) {
        throw new IllegalArgumentException("Token expiration can't be after " + token.getTokenExpiration());
    }
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) NoResultException(javax.persistence.NoResultException) Date(java.util.Date) ScopePathType(org.orcid.jaxb.model.message.ScopePathType) InvalidScopeException(org.springframework.security.oauth2.common.exceptions.InvalidScopeException) OrcidOauth2TokenDetail(org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail) HashSet(java.util.HashSet)

Example 39 with NoResultException

use of javax.persistence.NoResultException in project ORCID-Source by ORCID.

the class OrcidSecurityManagerImpl method checkProfile.

/**
 * Checks a record status and throw an exception indicating if the profile
 * have any of the following conditions: - The record is not claimed and is
 * not old enough nor being accessed by its creator - It is locked - It is
 * deprecated - It is deactivated
 *
 * @throws OrcidDeprecatedException
 *             in case the account is deprecated
 * @throws OrcidNotClaimedException
 *             in case the account is not claimed
 * @throws LockedException
 *             in the case the account is locked
 */
@Override
public void checkProfile(String orcid) throws NoResultException, OrcidDeprecatedException, OrcidNotClaimedException, LockedException, DeactivatedException {
    ProfileEntity profile = null;
    try {
        profile = profileEntityCacheManager.retrieve(orcid);
    } catch (IllegalArgumentException e) {
        throw new NoResultException();
    }
    // Check if the user record is deprecated
    if (profile.getPrimaryRecord() != null) {
        StringBuffer primary = new StringBuffer(baseUrl).append("/").append(profile.getPrimaryRecord().getId());
        Map<String, String> params = new HashMap<String, String>();
        params.put(OrcidDeprecatedException.ORCID, primary.toString());
        if (profile.getDeprecatedDate() != null) {
            XMLGregorianCalendar calendar = DateUtils.convertToXMLGregorianCalendar(profile.getDeprecatedDate());
            params.put(OrcidDeprecatedException.DEPRECATED_DATE, calendar.toString());
        }
        throw new OrcidDeprecatedException(params);
    }
    // Check if the user record is not claimed and not old enough
    if ((profile.getClaimed() == null || Boolean.FALSE.equals(profile.getClaimed())) && !isOldEnough(profile)) {
        // Let the creator access the profile even if it is not claimed and
        // not old enough
        SourceEntity currentSourceEntity = sourceManager.retrieveSourceEntity();
        String profileSource = profile.getSource() == null ? null : profile.getSource().getSourceId();
        String currentSource = currentSourceEntity == null ? null : currentSourceEntity.getSourceId();
        // the profile source, throw an exception
        if (profileSource == null || !Objects.equals(profileSource, currentSource)) {
            throw new OrcidNotClaimedException();
        }
    }
    // Check if the user record is locked
    if (!profile.isAccountNonLocked()) {
        LockedException lockedException = new LockedException();
        lockedException.setOrcid(profile.getId());
        throw lockedException;
    }
    // Check if the user record is deactivated
    if (profile.getDeactivationDate() != null) {
        DeactivatedException exception = new DeactivatedException();
        exception.setOrcid(orcid);
        throw exception;
    }
}
Also used : LockedException(org.orcid.core.security.aop.LockedException) HashMap(java.util.HashMap) SourceEntity(org.orcid.persistence.jpa.entities.SourceEntity) NoResultException(javax.persistence.NoResultException) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) DeactivatedException(org.orcid.core.exception.DeactivatedException) XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) OrcidDeprecatedException(org.orcid.core.exception.OrcidDeprecatedException) OrcidNotClaimedException(org.orcid.core.exception.OrcidNotClaimedException)

Example 40 with NoResultException

use of javax.persistence.NoResultException in project ORCID-Source by ORCID.

the class OrcidSecurityManagerImpl method checkProfile.

/**
 * Checks a record status and throw an exception indicating if the profile
 * have any of the following conditions: - The record is not claimed and is
 * not old enough nor being accessed by its creator - It is locked - It is
 * deprecated - It is deactivated
 *
 * @throws OrcidDeprecatedException
 *             in case the account is deprecated
 * @throws OrcidNotClaimedException
 *             in case the account is not claimed
 * @throws LockedException
 *             in the case the account is locked
 */
@Override
public void checkProfile(String orcid) throws NoResultException, OrcidDeprecatedException, OrcidNotClaimedException, LockedException, DeactivatedException {
    ProfileEntity profile = null;
    try {
        profile = profileEntityCacheManager.retrieve(orcid);
    } catch (IllegalArgumentException e) {
        throw new NoResultException();
    }
    // Check if the user record is deprecated
    if (profile.getPrimaryRecord() != null) {
        StringBuffer primary = new StringBuffer(baseUrl).append("/").append(profile.getPrimaryRecord().getId());
        Map<String, String> params = new HashMap<String, String>();
        params.put(OrcidDeprecatedException.ORCID, primary.toString());
        if (profile.getDeprecatedDate() != null) {
            XMLGregorianCalendar calendar = DateUtils.convertToXMLGregorianCalendar(profile.getDeprecatedDate());
            params.put(OrcidDeprecatedException.DEPRECATED_DATE, calendar.toString());
        }
        StringBuffer deprecated = new StringBuffer(baseUrl).append("/").append(profile.getId());
        params.put(OrcidDeprecatedException.DEPRECATED_ORCID, deprecated.toString());
        throw new OrcidDeprecatedException(params);
    }
    // Check if the user record is not claimed and not old enough
    if ((profile.getClaimed() == null || Boolean.FALSE.equals(profile.getClaimed())) && !isOldEnough(profile)) {
        // Let the creator access the profile even if it is not claimed and
        // not old enough
        SourceEntity currentSourceEntity = sourceManager.retrieveSourceEntity();
        String profileSource = profile.getSource() == null ? null : profile.getSource().getSourceId();
        String currentSource = currentSourceEntity == null ? null : currentSourceEntity.getSourceId();
        // the profile source, throw an exception
        if (profileSource == null || !Objects.equals(profileSource, currentSource)) {
            throw new OrcidNotClaimedException();
        }
    }
    // Check if the user record is locked
    if (!profile.isAccountNonLocked()) {
        LockedException lockedException = new LockedException();
        StringBuffer orcidId = new StringBuffer(baseUrl).append("/").append(profile.getId());
        lockedException.setOrcid(orcidId.toString());
        throw lockedException;
    }
    // Check if the user record is deactivated
    if (profile.getDeactivationDate() != null) {
        DeactivatedException exception = new DeactivatedException();
        exception.setOrcid(orcid);
        throw exception;
    }
}
Also used : LockedException(org.orcid.core.security.aop.LockedException) HashMap(java.util.HashMap) SourceEntity(org.orcid.persistence.jpa.entities.SourceEntity) NoResultException(javax.persistence.NoResultException) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) DeactivatedException(org.orcid.core.exception.DeactivatedException) XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) OrcidDeprecatedException(org.orcid.core.exception.OrcidDeprecatedException) OrcidNotClaimedException(org.orcid.core.exception.OrcidNotClaimedException)

Aggregations

NoResultException (javax.persistence.NoResultException)356 Query (javax.persistence.Query)205 EntityManager (javax.persistence.EntityManager)69 NonUniqueResultException (javax.persistence.NonUniqueResultException)33 CriteriaQuery (javax.persistence.criteria.CriteriaQuery)25 TypedQuery (javax.persistence.TypedQuery)22 Transactional (org.springframework.transaction.annotation.Transactional)20 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)19 Test (org.junit.Test)17 IOException (java.io.IOException)16 ArrayList (java.util.ArrayList)15 Session (org.hibernate.Session)13 UnitOfWork (com.google.inject.persist.UnitOfWork)12 Project (de.tudarmstadt.ukp.clarin.webanno.model.Project)11 PersistenceException (javax.persistence.PersistenceException)11 Date (java.util.Date)9 NotFoundException (org.opencastproject.util.NotFoundException)9 TblMle (com.intel.mtwilson.as.data.TblMle)8 List (java.util.List)8 NamedQuery (javax.persistence.NamedQuery)8