Search in sources :

Example 6 with IdentityDetails

use of com.sun.identity.idsvcs.IdentityDetails in project OpenAM by OpenRock.

the class IdentityResourceV3 method patchInstance.

/**
     * Patch the user's password and only the password.  No other value may be patched.  The old value of the
     * password does not have to be known.  Admin only.  The only patch operation supported is "replace", i.e. not
     * "add" or "move", etc.
     *
     * @param context The context
     * @param resourceId The username we're patching
     * @param request The patch request
     */
@Override
public Promise<ResourceResponse, ResourceException> patchInstance(final Context context, final String resourceId, final PatchRequest request) {
    if (!objectType.equals(IdentityRestUtils.USER_TYPE)) {
        return new BadRequestException("Cannot patch object type " + objectType).asPromise();
    }
    RealmContext realmContext = context.asContext(RealmContext.class);
    final String realm = realmContext.getResolvedRealm();
    try {
        if (!isAdmin(context)) {
            return new ForbiddenException("Only admin can patch user values").asPromise();
        }
        SSOToken ssoToken = getSSOToken(RestUtils.getToken().getTokenID().toString());
        IdentityServicesImpl identityServices = getIdentityServices();
        IdentityDetails identityDetails = identityServices.read(resourceId, getIdentityServicesAttributes(realm, objectType), ssoToken);
        Attribute[] existingAttributes = identityDetails.getAttributes();
        Map<String, Set<String>> existingAttributeMap = attributesToMap(existingAttributes);
        Map<String, Set<String>> newAttributeMap = new HashMap<>();
        if (existingAttributeMap.containsKey(IdentityRestUtils.UNIVERSAL_ID)) {
            Set<String> values = existingAttributeMap.get(IdentityRestUtils.UNIVERSAL_ID);
            if (isNotEmpty(values) && !isUserActive(values.iterator().next())) {
                return new ForbiddenException("User " + resourceId + " is not active: Request is forbidden").asPromise();
            }
        }
        boolean updateNeeded = false;
        for (PatchOperation patchOperation : request.getPatchOperations()) {
            switch(patchOperation.getOperation()) {
                case PatchOperation.OPERATION_REPLACE:
                    {
                        String name = getFieldName(patchOperation.getField());
                        if (!patchableAttributes.contains(name)) {
                            return new BadRequestException("For the object type " + IdentityRestUtils.USER_TYPE + ", field \"" + name + "\" cannot be altered by PATCH").asPromise();
                        }
                        JsonValue value = patchOperation.getValue();
                        newAttributeMap.put(name, identityAttributeJsonToSet(value));
                        updateNeeded = true;
                        break;
                    }
                default:
                    return new BadRequestException("PATCH of " + IdentityRestUtils.USER_TYPE + " does not support operation " + patchOperation.getOperation()).asPromise();
            }
        }
        if (updateNeeded) {
            identityDetails.setAttributes(mapToAttributes(newAttributeMap));
            identityServices.update(identityDetails, ssoToken);
            // re-read the altered identity details from the repo.
            identityDetails = identityServices.read(resourceId, getIdentityServicesAttributes(realm, objectType), ssoToken);
        }
        return newResultPromise(newResourceResponse("result", "1", identityDetailsToJsonValue(identityDetails)));
    } catch (final ObjectNotFound notFound) {
        logger.error("IdentityResourceV3.patchInstance cannot find resource " + resourceId, notFound);
        return new NotFoundException("Resource cannot be found.", notFound).asPromise();
    } catch (final TokenExpired tokenExpired) {
        logger.error("IdentityResourceV3.patchInstance, token expired", tokenExpired);
        return new PermanentException(401, "Unauthorized", null).asPromise();
    } catch (final AccessDenied accessDenied) {
        logger.error("IdentityResourceV3.patchInstance, access denied", accessDenied);
        return new ForbiddenException(accessDenied.getMessage(), accessDenied).asPromise();
    } catch (final GeneralFailure generalFailure) {
        logger.error("IdentityResourceV3.patchInstance, general failure " + generalFailure.getMessage());
        return new BadRequestException(generalFailure.getMessage(), generalFailure).asPromise();
    } catch (ForbiddenException fex) {
        logger.warning("IdentityResourceV3.patchInstance, insufficient privileges.", fex);
        return fex.asPromise();
    } catch (NotFoundException notFound) {
        logger.warning("IdentityResourceV3.patchInstance " + resourceId + " not found", notFound);
        return new NotFoundException("Resource " + resourceId + " cannot be found.", notFound).asPromise();
    } catch (ResourceException resourceException) {
        logger.warning("IdentityResourceV3.patchInstance caught ResourceException", resourceException);
        return resourceException.asPromise();
    } catch (Exception exception) {
        logger.error("IdentityResourceV3.patchInstance caught exception", exception);
        return new InternalServerErrorException(exception.getMessage(), exception).asPromise();
    }
}
Also used : SSOToken(com.iplanet.sso.SSOToken) Set(java.util.Set) HashSet(java.util.HashSet) Attribute(com.sun.identity.idsvcs.Attribute) HashMap(java.util.HashMap) NotFoundException(org.forgerock.json.resource.NotFoundException) IdentityServicesImpl(com.sun.identity.idsvcs.opensso.IdentityServicesImpl) ObjectNotFound(com.sun.identity.idsvcs.ObjectNotFound) PermanentException(org.forgerock.json.resource.PermanentException) PatchOperation(org.forgerock.json.resource.PatchOperation) TokenExpired(com.sun.identity.idsvcs.TokenExpired) ResourceException(org.forgerock.json.resource.ResourceException) ForbiddenException(org.forgerock.json.resource.ForbiddenException) RealmContext(org.forgerock.openam.rest.RealmContext) JsonValue(org.forgerock.json.JsonValue) AccessDenied(com.sun.identity.idsvcs.AccessDenied) PermanentException(org.forgerock.json.resource.PermanentException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ForbiddenException(org.forgerock.json.resource.ForbiddenException) NotFoundException(org.forgerock.json.resource.NotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) ResourceException(org.forgerock.json.resource.ResourceException) GeneralFailure(com.sun.identity.idsvcs.GeneralFailure) BadRequestException(org.forgerock.json.resource.BadRequestException) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException)

Example 7 with IdentityDetails

use of com.sun.identity.idsvcs.IdentityDetails in project OpenAM by OpenRock.

the class IdentityResourceV3 method queryCollection.

/*******************************************************************************************************************
     * {@inheritDoc}
     */
public Promise<QueryResponse, ResourceException> queryCollection(final Context context, final QueryRequest request, final QueryResourceHandler handler) {
    RealmContext realmContext = context.asContext(RealmContext.class);
    final String realm = realmContext.getResolvedRealm();
    try {
        SSOToken admin = getSSOToken(RestUtils.getToken().getTokenID().toString());
        IdentityServicesImpl identityServices = getIdentityServices();
        List<IdentityDetails> userDetails = null;
        // If the user specified _queryFilter, then (convert and) use that, otherwise look for _queryID
        // and if that isn't there either, pretend the user gave a _queryID of "*"
        //
        QueryFilter<JsonPointer> queryFilter = request.getQueryFilter();
        if (queryFilter != null) {
            CrestQuery crestQuery = new CrestQuery(queryFilter);
            userDetails = identityServices.searchIdentityDetails(crestQuery, getIdentityServicesAttributes(realm, objectType), admin);
        } else {
            String queryId = request.getQueryId();
            if (queryId == null || queryId.isEmpty()) {
                queryId = "*";
            }
            CrestQuery crestQuery = new CrestQuery(queryId);
            userDetails = identityServices.searchIdentityDetails(crestQuery, getIdentityServicesAttributes(realm, objectType), admin);
        }
        String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
        logger.message("IdentityResourceV3.queryCollection :: QUERY performed on realm " + realm + " by " + principalName);
        for (IdentityDetails userDetail : userDetails) {
            ResourceResponse resource;
            resource = newResourceResponse(userDetail.getName(), "0", identityResourceV2.addRoleInformation(context, userDetail.getName(), identityDetailsToJsonValue(userDetail)));
            handler.handleResource(resource);
        }
    } catch (ResourceException resourceException) {
        logger.warning("IdentityResourceV3.queryCollection caught ResourceException", resourceException);
        return resourceException.asPromise();
    } catch (Exception exception) {
        logger.error("IdentityResourceV3.queryCollection caught exception", exception);
        return new InternalServerErrorException(exception.getMessage(), exception).asPromise();
    }
    return newResultPromise(newQueryResponse());
}
Also used : CrestQuery(org.forgerock.openam.utils.CrestQuery) SSOToken(com.iplanet.sso.SSOToken) RealmContext(org.forgerock.openam.rest.RealmContext) JsonPointer(org.forgerock.json.JsonPointer) PermanentException(org.forgerock.json.resource.PermanentException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ForbiddenException(org.forgerock.json.resource.ForbiddenException) NotFoundException(org.forgerock.json.resource.NotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) ResourceException(org.forgerock.json.resource.ResourceException) IdentityServicesImpl(com.sun.identity.idsvcs.opensso.IdentityServicesImpl) Responses.newResourceResponse(org.forgerock.json.resource.Responses.newResourceResponse) ResourceResponse(org.forgerock.json.resource.ResourceResponse) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ResourceException(org.forgerock.json.resource.ResourceException)

Example 8 with IdentityDetails

use of com.sun.identity.idsvcs.IdentityDetails in project OpenAM by OpenRock.

the class IdentityRestUtils method jsonValueToIdentityDetails.

/**
     * Returns an IdentityDetails from a JsonValue.
     *
     * @param objectType the object type, eg. user, group, etc.
     * @param jVal The JsonValue Object to be converted
     * @param realm The realm
     * @return The IdentityDetails object
     */
public static IdentityDetails jsonValueToIdentityDetails(final String objectType, final JsonValue jVal, final String realm) {
    IdentityDetails identity = new IdentityDetails();
    Map<String, Set<String>> identityAttrList = new HashMap<>();
    try {
        //set type ex. user
        identity.setType(objectType);
        //set realm
        identity.setRealm(realm);
        //set name from JsonValue object
        identity.setName(jVal.get(USERNAME).asString());
        if (AGENT_TYPE.equals(objectType)) {
            jVal.remove(USERNAME);
            jVal.remove(REALM);
            jVal.remove(UNIVERSAL_ID);
        }
        try {
            for (String s : jVal.keys()) {
                identityAttrList.put(s, identityAttributeJsonToSet(jVal.get(s)));
            }
        } catch (Exception e) {
            debug.error("IdentityResource.jsonValueToIdentityDetails() :: Cannot Traverse JsonValue. ", e);
        }
        identity.setAttributes(asAttributeArray(identityAttrList));
    } catch (final Exception e) {
        debug.error("IdentityResource.jsonValueToIdentityDetails() :: Cannot convert JsonValue to IdentityDetails" + ".", e);
    //deal with better exceptions
    }
    return identity;
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails) NotFoundException(org.forgerock.json.resource.NotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) IdRepoException(com.sun.identity.idm.IdRepoException) PermanentException(org.forgerock.json.resource.PermanentException) JsonValueException(org.forgerock.json.JsonValueException) ResourceException(org.forgerock.json.resource.ResourceException) SSOException(com.iplanet.sso.SSOException)

Example 9 with IdentityDetails

use of com.sun.identity.idsvcs.IdentityDetails in project OpenAM by OpenRock.

the class IdentityRestUtils method enforceWhiteList.

/**
     * When an instance of a user is created via self service, we impose additional rules for security purposes.
     * Namely, we strictly apply a whitelist of valid attribute names to each attribute in the incoming JSON
     * representation of the user object.  This ensures a hacker can't manipulate the request and thereby pretend
     * to be a manager, demigod or individual they are not.
     *
     * There is no return value.  If you survive calling this function without an exception being thrown, there
     * are no illegal values in the incoming JSON
     *
     * @param context The context
     * @param jsonValue The request
     * @param objectType The type of object we're creating, user, group, etc.
     * @param validUserAttributes The set of valid user attributes
     * @throws BadRequestException If any attribute is found in the JSON representation of the user object containing
     * an attribute that is not in our whitelist
     */
public static void enforceWhiteList(final Context context, final JsonValue jsonValue, final String objectType, final Set<String> validUserAttributes) throws BadRequestException {
    if (!context.containsContext(SelfServiceContext.class) || !objectType.equals(USER_TYPE)) {
        return;
    }
    final String realm = RealmContext.getRealm(context);
    if (validUserAttributes == null || validUserAttributes.isEmpty()) {
        throw new BadRequestException("Null/empty whitelist of valid attributes for self service user creation");
    }
    IdentityDetails identityDetails = jsonValueToIdentityDetails(objectType, jsonValue, realm);
    Attribute[] attributes = identityDetails.getAttributes();
    for (Attribute attribute : attributes) {
        if (!validUserAttributes.contains(attribute.getName())) {
            throw new BadRequestException("User attribute " + attribute.getName() + " is not valid for self service creation");
        }
    }
}
Also used : Attribute(com.sun.identity.idsvcs.Attribute) BadRequestException(org.forgerock.json.resource.BadRequestException) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails)

Example 10 with IdentityDetails

use of com.sun.identity.idsvcs.IdentityDetails in project OpenAM by OpenRock.

the class IdentityResourceV1 method updateInstance.

/**
     * Updates an instance given a JSON object with User Attributes
     * @param admin Token that has administrative privileges
     * @param details Json Value containing details of user identity
     * @return A successful promise if the update was successful
     */
private Promise<ActionResponse, ResourceException> updateInstance(SSOToken admin, final JsonValue details, final String realm) {
    JsonValue jVal = details;
    IdentityDetails newDtls;
    String resourceId = jVal.get(USERNAME).asString();
    try {
        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");
        }
        newDtls.setName(resourceId);
        // update resource with new details
        identityServices.update(newDtls, admin);
        debug.message("IdentityResource.updateInstance :: Anonymous UPDATE in realm={} for resourceId={}", realm, resourceId);
        // read updated identity back to client
        IdentityDetails checkIdent = identityServices.read(resourceId, getIdentityServicesAttributes(realm), admin);
        // handle updated resource
        return newResultPromise(newActionResponse(identityDetailsToJsonValue(checkIdent)));
    } catch (ResourceException re) {
        debug.warning("IdentityResource.updateInstance() :: Cannot UPDATE in realm={} for resourceId={}", realm, resourceId, re);
        return re.asPromise();
    } catch (final Exception e) {
        debug.error("IdentityResource.updateInstance() :: Cannot UPDATE in realm={} for resourceId={}", realm, resourceId, e);
        return new NotFoundException(e.getMessage(), e).asPromise();
    }
}
Also used : IdentityRestUtils.identityDetailsToJsonValue(org.forgerock.openam.core.rest.IdentityRestUtils.identityDetailsToJsonValue) JsonValue(org.forgerock.json.JsonValue) IdentityRestUtils.jsonValueToIdentityDetails(org.forgerock.openam.core.rest.IdentityRestUtils.jsonValueToIdentityDetails) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails) BadRequestException(org.forgerock.json.resource.BadRequestException) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) ResourceException(org.forgerock.json.resource.ResourceException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) DeleteFailedException(org.forgerock.openam.cts.exceptions.DeleteFailedException) SSOException(com.iplanet.sso.SSOException) NotFoundException(org.forgerock.json.resource.NotFoundException) NotSupportedException(org.forgerock.json.resource.NotSupportedException) BadRequestException(org.forgerock.json.resource.BadRequestException) MessagingException(javax.mail.MessagingException) ConflictException(org.forgerock.json.resource.ConflictException) PermanentException(org.forgerock.json.resource.PermanentException) ForbiddenException(org.forgerock.json.resource.ForbiddenException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) 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)

Aggregations

IdentityDetails (com.sun.identity.idsvcs.IdentityDetails)21 NotFoundException (org.forgerock.json.resource.NotFoundException)18 BadRequestException (org.forgerock.json.resource.BadRequestException)17 ResourceException (org.forgerock.json.resource.ResourceException)17 SSOException (com.iplanet.sso.SSOException)15 ServiceNotFoundException (com.sun.identity.sm.ServiceNotFoundException)14 IdRepoException (com.sun.identity.idm.IdRepoException)13 ForbiddenException (org.forgerock.json.resource.ForbiddenException)13 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)13 PermanentException (org.forgerock.json.resource.PermanentException)13 JsonValue (org.forgerock.json.JsonValue)12 SSOToken (com.iplanet.sso.SSOToken)10 SMSException (com.sun.identity.sm.SMSException)10 UnsupportedEncodingException (java.io.UnsupportedEncodingException)10 MessagingException (javax.mail.MessagingException)10 ConflictException (org.forgerock.json.resource.ConflictException)10 NotSupportedException (org.forgerock.json.resource.NotSupportedException)10 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)10 DeleteFailedException (org.forgerock.openam.cts.exceptions.DeleteFailedException)10 ObjectNotFound (com.sun.identity.idsvcs.ObjectNotFound)9