Search in sources :

Example 1 with UserAttributeInfo

use of org.forgerock.openam.core.rest.UserAttributeInfo in project OpenAM by OpenRock.

the class IdentityResourceV2 method createInstance.

/**
     * {@inheritDoc}
     */
@Override
public Promise<ResourceResponse, ResourceException> createInstance(final Context context, final CreateRequest request) {
    RealmContext realmContext = context.asContext(RealmContext.class);
    final String realm = realmContext.getResolvedRealm();
    try {
        // anyone can create an account add
        SSOToken admin = getSSOToken(getCookieFromServerContext(context));
        final JsonValue jVal = request.getContent();
        String resourceId = request.getNewResourceId();
        IdentityDetails identity = jsonValueToIdentityDetails(objectType, jVal, realm);
        // check to see if request has included resource ID
        if (resourceId != null) {
            if (identity.getName() != null) {
                if (!resourceId.equalsIgnoreCase(identity.getName())) {
                    ResourceException be = new BadRequestException("id in path does not match id in request body");
                    debug.error("IdentityResource.createInstance() :: Cannot CREATE ", be);
                    return be.asPromise();
                }
            }
            identity.setName(resourceId);
        } else {
            resourceId = identity.getName();
        }
        UserAttributeInfo userAttributeInfo = configHandler.getConfig(realm, UserAttributeInfoBuilder.class);
        enforceWhiteList(context, request.getContent(), objectType, userAttributeInfo.getValidCreationAttributes());
        final String id = resourceId;
        return attemptResourceCreation(realm, admin, identity, resourceId).thenAsync(new AsyncFunction<IdentityDetails, ResourceResponse, ResourceException>() {

            @Override
            public Promise<ResourceResponse, ResourceException> apply(IdentityDetails dtls) {
                if (dtls != null) {
                    String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
                    debug.message("IdentityResource.createInstance :: CREATE of resourceId={} in realm={} " + "performed by principalName={}", id, realm, principalName);
                    ResourceResponse resource = newResourceResponse(id, "0", identityDetailsToJsonValue(dtls));
                    return newResultPromise(resource);
                } else {
                    debug.error("IdentityResource.createInstance() :: Identity not found");
                    return new NotFoundException("Identity not found").asPromise();
                }
            }
        });
    } catch (SSOException e) {
        return new ForbiddenException(e).asPromise();
    } catch (BadRequestException bre) {
        return bre.asPromise();
    }
}
Also used : UserAttributeInfo(org.forgerock.openam.core.rest.UserAttributeInfo) ForbiddenException(org.forgerock.json.resource.ForbiddenException) SSOToken(com.iplanet.sso.SSOToken) RealmContext(org.forgerock.openam.rest.RealmContext) JsonValue(org.forgerock.json.JsonValue) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) SSOException(com.iplanet.sso.SSOException) Promises.newResultPromise(org.forgerock.util.promise.Promises.newResultPromise) Promise(org.forgerock.util.promise.Promise) Responses.newResourceResponse(org.forgerock.json.resource.Responses.newResourceResponse) ResourceResponse(org.forgerock.json.resource.ResourceResponse) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails) BadRequestException(org.forgerock.json.resource.BadRequestException) ResourceException(org.forgerock.json.resource.ResourceException)

Example 2 with UserAttributeInfo

use of org.forgerock.openam.core.rest.UserAttributeInfo in project OpenAM by OpenRock.

the class IdentityResourceV1 method createInstance.

/**
     * {@inheritDoc}
     */
@Override
public Promise<ResourceResponse, ResourceException> createInstance(final Context context, final CreateRequest request) {
    RealmContext realmContext = context.asContext(RealmContext.class);
    final String realm = realmContext.getResolvedRealm();
    try {
        // anyone can create an account add
        SSOToken admin = getSSOToken(getCookieFromServerContext(context));
        final JsonValue jVal = request.getContent();
        String resourceId = request.getNewResourceId();
        UserAttributeInfo userAttributeInfo = configHandler.getConfig(realm, UserAttributeInfoBuilder.class);
        enforceWhiteList(context, request.getContent(), objectType, userAttributeInfo.getValidCreationAttributes());
        IdentityDetails identity = jsonValueToIdentityDetails(objectType, jVal, realm);
        // check to see if request has included resource ID
        if (resourceId != null) {
            if (identity.getName() != null) {
                if (!resourceId.equalsIgnoreCase(identity.getName())) {
                    ResourceException be = new BadRequestException("id in path does not match id in request body");
                    debug.error("IdentityResource.createInstance() :: Cannot CREATE ", be);
                    return be.asPromise();
                }
            }
            identity.setName(resourceId);
        } else {
            resourceId = identity.getName();
        }
        final String id = resourceId;
        return attemptResourceCreation(realm, admin, identity, resourceId).thenAsync(new AsyncFunction<IdentityDetails, ResourceResponse, ResourceException>() {

            @Override
            public Promise<ResourceResponse, ResourceException> apply(IdentityDetails dtls) {
                if (dtls != null) {
                    String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
                    debug.message("IdentityResource.createInstance :: CREATE of resourceId={} in realm={} performed by " + "principalName={}", id, realm, principalName);
                    return newResultPromise(newResourceResponse(id, "0", identityDetailsToJsonValue(dtls)));
                } else {
                    debug.error("IdentityResource.createInstance :: Identity not found ");
                    return new NotFoundException("Identity not found").asPromise();
                }
            }
        });
    } catch (SSOException e) {
        debug.error("IdentityResource.createInstance() :: failed.", e);
        return new NotFoundException(e.getMessage(), e).asPromise();
    } catch (BadRequestException bre) {
        return bre.asPromise();
    }
}
Also used : UserAttributeInfo(org.forgerock.openam.core.rest.UserAttributeInfo) IdentityRestUtils.getSSOToken(org.forgerock.openam.core.rest.IdentityRestUtils.getSSOToken) SSOToken(com.iplanet.sso.SSOToken) RealmContext(org.forgerock.openam.rest.RealmContext) IdentityRestUtils.identityDetailsToJsonValue(org.forgerock.openam.core.rest.IdentityRestUtils.identityDetailsToJsonValue) JsonValue(org.forgerock.json.JsonValue) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) SSOException(com.iplanet.sso.SSOException) Promises.newResultPromise(org.forgerock.util.promise.Promises.newResultPromise) Promise(org.forgerock.util.promise.Promise) ResourceResponse(org.forgerock.json.resource.ResourceResponse) IdentityRestUtils.jsonValueToIdentityDetails(org.forgerock.openam.core.rest.IdentityRestUtils.jsonValueToIdentityDetails) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails) BadRequestException(org.forgerock.json.resource.BadRequestException) ResourceException(org.forgerock.json.resource.ResourceException)

Example 3 with UserAttributeInfo

use of org.forgerock.openam.core.rest.UserAttributeInfo in project OpenAM by OpenRock.

the class IdentityResourceV2 method updateInstance.

/**
     * {@inheritDoc}
     */
@Override
public Promise<ResourceResponse, ResourceException> updateInstance(final Context context, final String resourceId, final UpdateRequest request) {
    RealmContext realmContext = context.asContext(RealmContext.class);
    final String realm = realmContext.getResolvedRealm();
    final JsonValue jVal = request.getContent();
    final String rev = request.getRevision();
    IdentityDetails dtls, newDtls;
    ResourceResponse resource;
    try {
        SSOToken token = getSSOToken(getCookieFromServerContext(context));
        // Retrieve details about user to be updated
        dtls = identityServices.read(resourceId, getIdentityServicesAttributes(realm, objectType), token);
        // Continue modifying the identity if read success
        boolean isUpdatingHisOwnPassword = SystemProperties.getAsBoolean(Constants.CASE_SENSITIVE_UUID) ? token.getProperty(ISAuthConstants.USER_ID).equals(resourceId) : token.getProperty(ISAuthConstants.USER_ID).equalsIgnoreCase(resourceId);
        // If the user wants to modify his password, he should use a different action.
        if (isUpdatingHisOwnPassword) {
            for (String key : jVal.keys()) {
                if (USER_PASSWORD.equalsIgnoreCase(key)) {
                    return new BadRequestException("Cannot update user password via PUT. " + "Use POST with _action=changePassword or _action=forgotPassword.").asPromise();
                }
            }
        }
        newDtls = jsonValueToIdentityDetails(objectType, jVal, realm);
        if (newDtls.getAttributes() == null || newDtls.getAttributes().length < 1) {
            throw new BadRequestException("Illegal arguments: One or more required arguments is null or empty");
        }
        if (newDtls.getName() != null && !resourceId.equalsIgnoreCase(newDtls.getName())) {
            throw new BadRequestException("id in path does not match id in request body");
        }
        newDtls.setName(resourceId);
        UserAttributeInfo userAttributeInfo = configHandler.getConfig(realm, UserAttributeInfoBuilder.class);
        // Handle attribute change when password is required
        // Get restSecurity for this realm
        RestSecurity restSecurity = restSecurityProvider.get(realm);
        // Make sure user is not admin and check to see if we are requiring a password to change any attributes
        Set<String> protectedUserAttributes = new HashSet<>();
        protectedUserAttributes.addAll(restSecurity.getProtectedUserAttributes());
        protectedUserAttributes.addAll(userAttributeInfo.getProtectedUpdateAttributes());
        if (!protectedUserAttributes.isEmpty() && !isAdmin(context)) {
            boolean hasReauthenticated = false;
            for (String protectedAttr : protectedUserAttributes) {
                JsonValue jValAttr = jVal.get(protectedAttr);
                if (!jValAttr.isNull()) {
                    // If attribute is not available set newAttr variable to empty string for use in comparison
                    String newAttr = (jValAttr.isString()) ? jValAttr.asString() : "";
                    // Get the value of current attribute
                    String currentAttr = "";
                    Map<String, Set<String>> attrs = asMap(dtls.getAttributes());
                    for (Map.Entry<String, Set<String>> attribute : attrs.entrySet()) {
                        String attributeName = attribute.getKey();
                        if (protectedAttr.equalsIgnoreCase(attributeName)) {
                            currentAttr = attribute.getValue().iterator().next();
                        }
                    }
                    // Compare newAttr and currentAttr
                    if (!currentAttr.equals(newAttr) && !hasReauthenticated) {
                        // check header to make sure that password is there then check to see if it's correct
                        String strCurrentPass = RestUtils.getMimeHeaderValue(context, CURRENT_PASSWORD);
                        if (strCurrentPass != null && !strCurrentPass.isEmpty() && checkValidPassword(resourceId, strCurrentPass.toCharArray(), realm)) {
                            //set a boolean value so we know reauth has been done
                            hasReauthenticated = true;
                        //continue will allow attribute(s) change(s)
                        } else {
                            throw new BadRequestException("Must provide a valid confirmation password to change " + "protected attribute (" + protectedAttr + ") from '" + currentAttr + "' to '" + newAttr + "'");
                        }
                    }
                }
            }
        }
        // update resource with new details
        identityServices.update(newDtls, token);
        String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
        debug.message("IdentityResource.updateInstance :: UPDATE of resourceId={} in realm={} performed " + "by principalName={}", resourceId, realm, principalName);
        // read updated identity back to client
        IdentityDetails checkIdent = identityServices.read(dtls.getName(), getIdentityServicesAttributes(realm, objectType), token);
        return newResultPromise(this.identityResourceV1.buildResourceResponse(resourceId, context, checkIdent));
    } catch (final ObjectNotFound onf) {
        debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={} : Could not find the " + "resource", resourceId, onf);
        return new NotFoundException("Could not find the resource [ " + resourceId + " ] to update", onf).asPromise();
    } catch (final NeedMoreCredentials needMoreCredentials) {
        debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={} : Token is not authorized", resourceId, needMoreCredentials);
        return new ForbiddenException("Token is not authorized", needMoreCredentials).asPromise();
    } catch (final TokenExpired tokenExpired) {
        debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={} : Unauthorized", resourceId, tokenExpired);
        return new PermanentException(401, "Unauthorized", null).asPromise();
    } catch (final AccessDenied accessDenied) {
        debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={} : Access denied", resourceId, accessDenied);
        return new ForbiddenException(accessDenied.getMessage(), accessDenied).asPromise();
    } catch (final GeneralFailure generalFailure) {
        debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={}", resourceId, generalFailure);
        return new BadRequestException(generalFailure.getMessage(), generalFailure).asPromise();
    } catch (BadRequestException bre) {
        debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={}", resourceId, bre);
        return bre.asPromise();
    } catch (NotFoundException e) {
        debug.warning("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={} : Could not find the " + "resource", resourceId, e);
        return new NotFoundException("Could not find the resource [ " + resourceId + " ] to update", e).asPromise();
    } catch (ResourceException re) {
        debug.warning("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={} ", resourceId, re);
        return re.asPromise();
    } catch (final Exception e) {
        debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={}", resourceId, e);
        return new NotFoundException(e.getMessage(), e).asPromise();
    }
}
Also used : UserAttributeInfo(org.forgerock.openam.core.rest.UserAttributeInfo) SSOToken(com.iplanet.sso.SSOToken) Set(java.util.Set) HashSet(java.util.HashSet) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) ObjectNotFound(com.sun.identity.idsvcs.ObjectNotFound) PermanentException(org.forgerock.json.resource.PermanentException) RestSecurity(org.forgerock.openam.services.RestSecurity) TokenExpired(com.sun.identity.idsvcs.TokenExpired) ResourceException(org.forgerock.json.resource.ResourceException) HashSet(java.util.HashSet) ForbiddenException(org.forgerock.json.resource.ForbiddenException) NeedMoreCredentials(com.sun.identity.idsvcs.NeedMoreCredentials) RealmContext(org.forgerock.openam.rest.RealmContext) JsonValue(org.forgerock.json.JsonValue) AccessDenied(com.sun.identity.idsvcs.AccessDenied) MessagingException(javax.mail.MessagingException) ConflictException(org.forgerock.json.resource.ConflictException) PermanentException(org.forgerock.json.resource.PermanentException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ForbiddenException(org.forgerock.json.resource.ForbiddenException) DeleteFailedException(org.forgerock.openam.cts.exceptions.DeleteFailedException) SSOException(com.iplanet.sso.SSOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) NotSupportedException(org.forgerock.json.resource.NotSupportedException) BadRequestException(org.forgerock.json.resource.BadRequestException) IdRepoException(com.sun.identity.idm.IdRepoException) SMSException(com.sun.identity.sm.SMSException) ResourceException(org.forgerock.json.resource.ResourceException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) Responses.newResourceResponse(org.forgerock.json.resource.Responses.newResourceResponse) ResourceResponse(org.forgerock.json.resource.ResourceResponse) GeneralFailure(com.sun.identity.idsvcs.GeneralFailure) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails) BadRequestException(org.forgerock.json.resource.BadRequestException) Map(java.util.Map) IdentityServicesImpl.asMap(com.sun.identity.idsvcs.opensso.IdentityServicesImpl.asMap) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

SSOException (com.iplanet.sso.SSOException)3 SSOToken (com.iplanet.sso.SSOToken)3 IdentityDetails (com.sun.identity.idsvcs.IdentityDetails)3 ServiceNotFoundException (com.sun.identity.sm.ServiceNotFoundException)3 JsonValue (org.forgerock.json.JsonValue)3 BadRequestException (org.forgerock.json.resource.BadRequestException)3 NotFoundException (org.forgerock.json.resource.NotFoundException)3 ResourceException (org.forgerock.json.resource.ResourceException)3 ResourceResponse (org.forgerock.json.resource.ResourceResponse)3 UserAttributeInfo (org.forgerock.openam.core.rest.UserAttributeInfo)3 RealmContext (org.forgerock.openam.rest.RealmContext)3 ForbiddenException (org.forgerock.json.resource.ForbiddenException)2 Responses.newResourceResponse (org.forgerock.json.resource.Responses.newResourceResponse)2 Promise (org.forgerock.util.promise.Promise)2 Promises.newResultPromise (org.forgerock.util.promise.Promises.newResultPromise)2 IdRepoException (com.sun.identity.idm.IdRepoException)1 AccessDenied (com.sun.identity.idsvcs.AccessDenied)1 GeneralFailure (com.sun.identity.idsvcs.GeneralFailure)1 NeedMoreCredentials (com.sun.identity.idsvcs.NeedMoreCredentials)1 ObjectNotFound (com.sun.identity.idsvcs.ObjectNotFound)1