Search in sources :

Example 6 with RealmContext

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

the class IdentityResourceV1 method updateInstance.

@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 jsonValue = request.getContent();
    final String rev = request.getRevision();
    IdentityDetails dtls, newDtls;
    ResourceResponse resource;
    try {
        SSOToken admin = getSSOToken(getCookieFromServerContext(context));
        // Retrieve details about user to be updated
        dtls = identityServices.read(resourceId, getIdentityServicesAttributes(realm), admin);
        //be removed from the IdentityDetails object.
        if (!isAdmin(context)) {
            for (String attrName : jsonValue.keys()) {
                if ("userpassword".equalsIgnoreCase(attrName)) {
                    String newPassword = jsonValue.get(attrName).asString();
                    if (!StringUtils.isBlank(newPassword)) {
                        String oldPassword = RestUtils.getMimeHeaderValue(context, OLD_PASSWORD);
                        if (StringUtils.isBlank(oldPassword)) {
                            throw new BadRequestException("The old password is missing from the request");
                        }
                        //This is an end-user trying to change the password, so let's change the password by
                        //verifying that the provided old password is correct. We also remove the password from the
                        //list of attributes to prevent the administrative password reset via the update call.
                        jsonValue.remove(attrName);
                        IdentityRestUtils.changePassword(context, realm, resourceId, oldPassword, newPassword);
                    }
                    break;
                }
            }
        }
        newDtls = jsonValueToIdentityDetails(objectType, jsonValue, realm);
        if (newDtls.getName() != null && !resourceId.equalsIgnoreCase(newDtls.getName())) {
            throw new BadRequestException("id in path does not match id in request body");
        }
        newDtls.setName(resourceId);
        // update resource with new details
        identityServices.update(newDtls, admin);
        // read updated identity back to client
        IdentityDetails checkIdent = identityServices.read(dtls.getName(), getIdentityServicesAttributes(realm), admin);
        // handle updated resource
        resource = newResourceResponse(resourceId, "0", identityDetailsToJsonValue(checkIdent));
        return newResultPromise(resource);
    } 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 (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 (SSOException ssoe) {
        debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={}", resourceId, ssoe);
        return new ForbiddenException(ssoe).asPromise();
    } catch (final Exception e) {
        debug.error("IdentityResource.updateInstance() :: Cannot UPDATE resourceId={}", resourceId, e);
        return new NotFoundException(e).asPromise();
    }
}
Also used : ForbiddenException(org.forgerock.json.resource.ForbiddenException) IdentityRestUtils.getSSOToken(org.forgerock.openam.core.rest.IdentityRestUtils.getSSOToken) SSOToken(com.iplanet.sso.SSOToken) NeedMoreCredentials(com.sun.identity.idsvcs.NeedMoreCredentials) 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) AccessDenied(com.sun.identity.idsvcs.AccessDenied) 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) ResourceResponse(org.forgerock.json.resource.ResourceResponse) ObjectNotFound(com.sun.identity.idsvcs.ObjectNotFound) PermanentException(org.forgerock.json.resource.PermanentException) GeneralFailure(com.sun.identity.idsvcs.GeneralFailure) IdentityRestUtils.jsonValueToIdentityDetails(org.forgerock.openam.core.rest.IdentityRestUtils.jsonValueToIdentityDetails) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails) BadRequestException(org.forgerock.json.resource.BadRequestException) TokenExpired(com.sun.identity.idsvcs.TokenExpired) ResourceException(org.forgerock.json.resource.ResourceException)

Example 7 with RealmContext

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

the class IdentityResourceV2 method getRelativeRealmFromSession.

private String getRelativeRealmFromSession(Context context, AMIdentity amIdentity) {
    RealmContext realmContext = context.asContext(RealmContext.class);
    String sessionRealm = com.sun.identity.sm.DNMapper.orgNameToRealmName(amIdentity.getRealm());
    String baseRealm = realmContext.getDnsAliasRealm();
    if (sessionRealm.startsWith(baseRealm)) {
        String realm = sessionRealm.substring(baseRealm.length());
        if (!realm.startsWith("/")) {
            realm = "/" + realm;
        }
        return realm;
    }
    return sessionRealm;
}
Also used : RealmContext(org.forgerock.openam.rest.RealmContext)

Example 8 with RealmContext

use of org.forgerock.openam.rest.RealmContext 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 9 with RealmContext

use of org.forgerock.openam.rest.RealmContext 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 10 with RealmContext

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

the class RealmResource method updateInstance.

/**
     * {@inheritDoc}
     */
@Override
public Promise<ResourceResponse, ResourceException> updateInstance(Context context, String resourceId, UpdateRequest request) {
    RealmContext realmContext = context.asContext(RealmContext.class);
    String realmPath = realmContext.getResolvedRealm();
    final JsonValue realmDetails = request.getContent();
    ResourceResponse resource;
    String realm;
    OrganizationConfigManager ocm;
    OrganizationConfigManager realmCreatedOcm;
    String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
    try {
        hasPermission(context);
        realm = checkForTopLevelRealm(resourceId);
        if (realm != null && !realm.startsWith("/")) {
            realm = "/" + realm;
        }
        if (!realmPath.equalsIgnoreCase("/")) {
            realm = realmPath + realm;
        }
        // Update a realm - if it's not found, error out.
        ocm = new OrganizationConfigManager(getSSOToken(), realm);
        List newServiceNames;
        // update ID_REPO attributes
        updateConfiguredServices(ocm, createServicesMap(realmDetails));
        newServiceNames = realmDetails.get(SERVICE_NAMES).asList();
        if (newServiceNames == null || newServiceNames.isEmpty()) {
            debug.error("RealmResource.updateInstance() : No Services defined.");
        } else {
            //assign services to realm
            assignServices(ocm, newServiceNames);
        }
        // READ THE REALM
        realmCreatedOcm = new OrganizationConfigManager(getSSOToken(), realm);
        debug.message("RealmResource.updateInstance :: UPDATE of realm " + realm + " performed by " + principalName);
        // create a resource for handler to return
        resource = newResourceResponse(realm, String.valueOf(System.currentTimeMillis()), createJsonMessage("realmUpdated", realmCreatedOcm.getOrganizationName()));
        return newResultPromise(resource);
    } catch (SMSException e) {
        try {
            configureErrorMessage(e);
            return new NotFoundException(e.getMessage(), e).asPromise();
        } catch (ForbiddenException fe) {
            // User does not have authorization
            debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, fe);
            return fe.asPromise();
        } catch (PermanentException pe) {
            debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, pe);
            // Cannot recover from this exception
            return pe.asPromise();
        } catch (ConflictException ce) {
            debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, ce);
            return ce.asPromise();
        } catch (BadRequestException be) {
            debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, be);
            return be.asPromise();
        } catch (Exception ex) {
            debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, ex);
            return new NotFoundException("Cannot update realm.", ex).asPromise();
        }
    } catch (SSOException sso) {
        debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, sso);
        return new PermanentException(401, "Access Denied", null).asPromise();
    } catch (ForbiddenException fe) {
        debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, fe);
        return fe.asPromise();
    } catch (PermanentException pe) {
        debug.error("RealmResource.Instance() : Cannot UPDATE " + resourceId, pe);
        // Cannot recover from this exception
        return pe.asPromise();
    } catch (Exception ex) {
        debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, ex);
        return new NotFoundException("Cannot update realm.", ex).asPromise();
    }
}
Also used : ForbiddenException(org.forgerock.json.resource.ForbiddenException) RealmContext(org.forgerock.openam.rest.RealmContext) SMSException(com.sun.identity.sm.SMSException) ConflictException(org.forgerock.json.resource.ConflictException) JsonValue(org.forgerock.json.JsonValue) NotFoundException(org.forgerock.json.resource.NotFoundException) SSOException(com.iplanet.sso.SSOException) NotFoundException(org.forgerock.json.resource.NotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) ConflictException(org.forgerock.json.resource.ConflictException) PermanentException(org.forgerock.json.resource.PermanentException) SMSException(com.sun.identity.sm.SMSException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ForbiddenException(org.forgerock.json.resource.ForbiddenException) JsonValueException(org.forgerock.json.JsonValueException) ResourceException(org.forgerock.json.resource.ResourceException) SSOException(com.iplanet.sso.SSOException) Responses.newResourceResponse(org.forgerock.json.resource.Responses.newResourceResponse) ResourceResponse(org.forgerock.json.resource.ResourceResponse) OrganizationConfigManager(com.sun.identity.sm.OrganizationConfigManager) PermanentException(org.forgerock.json.resource.PermanentException) BadRequestException(org.forgerock.json.resource.BadRequestException) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

RealmContext (org.forgerock.openam.rest.RealmContext)94 ResourceException (org.forgerock.json.resource.ResourceException)63 ResourceResponse (org.forgerock.json.resource.ResourceResponse)58 Context (org.forgerock.services.context.Context)53 Test (org.testng.annotations.Test)53 Subject (javax.security.auth.Subject)42 ClientContext (org.forgerock.services.context.ClientContext)41 SSOTokenContext (org.forgerock.openam.rest.resource.SSOTokenContext)40 JsonValue (org.forgerock.json.JsonValue)35 Matchers.anyString (org.mockito.Matchers.anyString)27 SubjectContext (org.forgerock.openam.rest.resource.SubjectContext)20 BadRequestException (org.forgerock.json.resource.BadRequestException)19 SSOException (com.iplanet.sso.SSOException)17 Application (com.sun.identity.entitlement.Application)16 ForbiddenException (org.forgerock.json.resource.ForbiddenException)16 NotFoundException (org.forgerock.json.resource.NotFoundException)15 PermanentException (org.forgerock.json.resource.PermanentException)15 QueryResourceHandler (org.forgerock.json.resource.QueryResourceHandler)15 ReadRequest (org.forgerock.json.resource.ReadRequest)15 SSOToken (com.iplanet.sso.SSOToken)14