Search in sources :

Example 16 with PermanentException

use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.

the class RealmResource method createInstance.

/**
     * {@inheritDoc}
     */
@Override
public Promise<ResourceResponse, ResourceException> createInstance(Context context, CreateRequest request) {
    RealmContext realmContext = context.asContext(RealmContext.class);
    String realmPath = realmContext.getResolvedRealm();
    ResourceResponse resource;
    String parentRealm;
    String childRealm;
    String realm = null;
    try {
        hasPermission(context);
        final JsonValue jVal = request.getContent();
        // get the realm
        realm = jVal.get("realm").asString();
        if (StringUtils.isBlank(realm)) {
            realm = request.getNewResourceId();
        }
        realm = checkForTopLevelRealm(realm);
        if (StringUtils.isBlank(realm)) {
            throw new BadRequestException("No realm name provided.");
        } else if (!realm.startsWith("/")) {
            realm = "/" + realm;
        }
        if (!realmPath.equalsIgnoreCase("/")) {
            // build realm to comply with format if not top level
            realm = realmPath + realm;
        }
        parentRealm = RealmUtils.getParentRealm(realm);
        childRealm = RealmUtils.getChildRealm(realm);
        OrganizationConfigManager ocm = new OrganizationConfigManager(getSSOToken(), parentRealm);
        Map defaultValues = createServicesMap(jVal);
        ocm.createSubOrganization(childRealm, defaultValues);
        String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
        debug.message("RealmResource.createInstance :: CREATE of realm " + childRealm + " in realm " + parentRealm + " performed by " + principalName);
        // create a resource for handler to return
        OrganizationConfigManager realmCreated = new OrganizationConfigManager(getSSOToken(), realm);
        resource = newResourceResponse(childRealm, String.valueOf(System.currentTimeMillis()), createJsonMessage("realmCreated", realmCreated.getOrganizationName()));
        return newResultPromise(resource);
    } catch (SMSException smse) {
        debug.error("RealmResource.createInstance() : Cannot find " + realm, smse);
        try {
            configureErrorMessage(smse);
            return new BadRequestException(smse.getMessage(), smse).asPromise();
        } catch (NotFoundException nf) {
            debug.error("RealmResource.createInstance() : Cannot find " + realm, nf);
            return nf.asPromise();
        } catch (ForbiddenException fe) {
            // User does not have authorization
            debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, fe);
            return fe.asPromise();
        } catch (PermanentException pe) {
            debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, pe);
            // Cannot recover from this exception
            return pe.asPromise();
        } catch (ConflictException ce) {
            debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, ce);
            return ce.asPromise();
        } catch (BadRequestException be) {
            debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, be);
            return be.asPromise();
        } catch (Exception e) {
            debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, e);
            return new BadRequestException(e.getMessage(), e).asPromise();
        }
    } catch (SSOException sso) {
        debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, sso);
        return new PermanentException(401, "Access Denied", null).asPromise();
    } catch (ForbiddenException fe) {
        debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, fe);
        return fe.asPromise();
    } catch (BadRequestException be) {
        debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, be);
        return be.asPromise();
    } catch (PermanentException pe) {
        debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, pe);
        // Cannot recover from this exception
        return pe.asPromise();
    } catch (Exception e) {
        debug.error("RealmResource.createInstance()" + realm + ":" + e);
        return new BadRequestException(e.getMessage(), e).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) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 17 with PermanentException

use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.

the class IdentityResourceV2 method attemptResourceCreation.

private Promise<IdentityDetails, ResourceException> attemptResourceCreation(String realm, SSOToken admin, IdentityDetails identity, String resourceId) {
    IdentityDetails dtls = null;
    try {
        // Create the resource
        identityServices.create(identity, admin);
        // Read created resource
        dtls = identityServices.read(resourceId, getIdentityServicesAttributes(realm, objectType), admin);
        if (debug.messageEnabled()) {
            debug.message("IdentityResource.createInstance() :: Created resourceId={} in realm={} by AdminID={}", resourceId, realm, admin.getTokenID());
        }
    } catch (final ObjectNotFound notFound) {
        debug.error("IdentityResource.createInstance() :: Cannot READ resourceId={} : Resource cannot be found.", resourceId, notFound);
        return new NotFoundException("Resource not found.", notFound).asPromise();
    } catch (final TokenExpired tokenExpired) {
        debug.error("IdentityResource.createInstance() :: Cannot CREATE resourceId={} : Unauthorized", resourceId, tokenExpired);
        return new PermanentException(401, "Unauthorized", null).asPromise();
    } catch (final NeedMoreCredentials needMoreCredentials) {
        debug.error("IdentityResource.createInstance() :: Cannot CREATE resourceId={} : Token is not authorized", resourceId, needMoreCredentials);
        return new ForbiddenException("Token is not authorized", needMoreCredentials).asPromise();
    } catch (final GeneralAccessDeniedError accessDenied) {
        debug.error("IdentityResource.createInstance() :: Cannot CREATE " + accessDenied);
        return new ForbiddenException().asPromise();
    } catch (GeneralFailure generalFailure) {
        debug.error("IdentityResource.createInstance() :: Cannot CREATE " + generalFailure);
        return new BadRequestException("Resource cannot be created: " + generalFailure.getMessage(), generalFailure).asPromise();
    } catch (AccessDenied accessDenied) {
        debug.error("IdentityResource.createInstance() :: Cannot CREATE " + accessDenied);
        return new ForbiddenException("Token is not authorized: " + accessDenied.getMessage(), accessDenied).asPromise();
    } catch (ResourceException re) {
        debug.warning("IdentityResource.createInstance() :: Cannot CREATE resourceId={}", resourceId, re);
        return re.asPromise();
    } catch (final Exception e) {
        debug.error("IdentityResource.createInstance() :: Cannot CREATE resourceId={}", resourceId, e);
        return new NotFoundException(e.getMessage(), e).asPromise();
    }
    return newResultPromise(dtls);
}
Also used : GeneralAccessDeniedError(com.sun.identity.idsvcs.opensso.GeneralAccessDeniedError) ForbiddenException(org.forgerock.json.resource.ForbiddenException) NeedMoreCredentials(com.sun.identity.idsvcs.NeedMoreCredentials) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) 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) ObjectNotFound(com.sun.identity.idsvcs.ObjectNotFound) PermanentException(org.forgerock.json.resource.PermanentException) GeneralFailure(com.sun.identity.idsvcs.GeneralFailure) 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 18 with PermanentException

use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.

the class SmsRealmProvider method handleCreate.

@Override
public Promise<ResourceResponse, ResourceException> handleCreate(Context serverContext, CreateRequest createRequest) {
    final JsonValue jsonContent = createRequest.getContent();
    final String realmName = jsonContent.get(REALM_NAME_ATTRIBUTE_NAME).asString();
    try {
        if (StringUtils.isBlank(realmName)) {
            throw new BadRequestException("No realm name provided");
        }
        if (containsBlacklistedCharacters(realmName)) {
            throw new BadRequestException("Realm names cannot contain: " + BLACKLIST_CHARACTERS.toString());
        }
        RealmContext realmContext = serverContext.asContext(RealmContext.class);
        StringBuilder realmPath = new StringBuilder(realmContext.getResolvedRealm());
        String location = jsonContent.get(new JsonPointer(PATH_ATTRIBUTE_NAME)).asString();
        if (realmPath.length() > 1) {
            if (realmPath.charAt(realmPath.length() - 1) != '/' && !location.startsWith("/")) {
                realmPath.append('/');
            }
            realmPath.append(location);
        } else {
            realmPath = new StringBuilder(location);
        }
        if (realmPath.charAt(realmPath.length() - 1) != '/') {
            realmPath.append('/');
        }
        realmPath.append(realmName);
        String path = realmPath.toString();
        String parentRealm = RealmUtils.getParentRealm(path);
        String childRealm = RealmUtils.getChildRealm(path);
        OrganizationConfigManager realmManager = new OrganizationConfigManager(getUserSsoToken(serverContext), parentRealm);
        Map<String, Map<String, Set>> serviceAttributes = new HashMap<>();
        serviceAttributes.put(IdConstants.REPO_SERVICE, getAttributeMap(jsonContent));
        realmManager.createSubOrganization(childRealm, serviceAttributes);
        if (debug.messageEnabled()) {
            debug.message("RealmResource.createInstance :: CREATE of realm {} in realm {} performed by {}", childRealm, parentRealm, PrincipalRestUtils.getPrincipalNameFromServerContext(serverContext));
        }
        JsonValue jsonValue = getJsonValue(path, parentRealm);
        return newResultPromise(getResource(jsonValue));
    } catch (SMSException e) {
        return configureErrorMessage(e).asPromise();
    } catch (SSOException sso) {
        debug.error("RealmResource.createInstance() : Cannot CREATE " + realmName, sso);
        return new PermanentException(401, "Access Denied", null).asPromise();
    } catch (BadRequestException fe) {
        debug.error("RealmResource.createInstance() : Cannot CREATE " + realmName, fe);
        return fe.asPromise();
    }
}
Also used : RealmContext(org.forgerock.openam.rest.RealmContext) HashMap(java.util.HashMap) SMSException(com.sun.identity.sm.SMSException) JsonValue(org.forgerock.json.JsonValue) SSOException(com.iplanet.sso.SSOException) JsonPointer(org.forgerock.json.JsonPointer) OrganizationConfigManager(com.sun.identity.sm.OrganizationConfigManager) PermanentException(org.forgerock.json.resource.PermanentException) BadRequestException(org.forgerock.json.resource.BadRequestException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 19 with PermanentException

use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.

the class SmsRealmProvider method handleUpdate.

@Override
public Promise<ResourceResponse, ResourceException> handleUpdate(Context context, UpdateRequest request) {
    RealmContext realmContext = context.asContext(RealmContext.class);
    String realmPath = realmContext.getResolvedRealm();
    try {
        checkValues(request.getContent());
    } catch (BadRequestException e) {
        debug.error("RealmResource.updateInstance() : Cannot UPDATE " + realmPath, e);
        return new BadRequestException("Invalid attribute values").asPromise();
    }
    // protect against attempts to change a realm that does not exist as this results in unexpected behaviour
    try {
        String requestPath = getExpectedPathFromRequestContext(request);
        if (!realmPath.equals(requestPath)) {
            return new BadRequestException(BAD_REQUEST_REALM_NAME_ERROR_MESSAGE).asPromise();
        }
    } catch (org.forgerock.oauth2.core.exceptions.NotFoundException e) {
        return new BadRequestException(BAD_REQUEST_REALM_NAME_ERROR_MESSAGE).asPromise();
    }
    final JsonValue realmDetails = request.getContent();
    try {
        hasPermission(context);
        OrganizationConfigManager realmManager = new OrganizationConfigManager(getSSOToken(), realmPath);
        realmManager.setAttributes(IdConstants.REPO_SERVICE, getAttributeMap(realmDetails));
        final List<Object> newServiceNames = realmDetails.get(SERVICE_NAMES).asList();
        if (newServiceNames != null) {
            assignServices(realmManager, newServiceNames);
        }
        debug.message("RealmResource.updateInstance :: UPDATE of realm " + realmPath + " performed by " + PrincipalRestUtils.getPrincipalNameFromServerContext(context));
        return newResultPromise(getResource(getJsonValue(realmPath)));
    } catch (SMSException e) {
        debug.error("RealmResource.updateInstance() : Cannot UPDATE " + realmPath, e);
        return configureErrorMessage(e).asPromise();
    } catch (SSOException | ForbiddenException | IdRepoException e) {
        debug.error("RealmResource.updateInstance() : Cannot UPDATE " + realmPath, e);
        return new PermanentException(401, "Access Denied", null).asPromise();
    }
}
Also used : ForbiddenException(org.forgerock.json.resource.ForbiddenException) RealmContext(org.forgerock.openam.rest.RealmContext) SMSException(com.sun.identity.sm.SMSException) JsonValue(org.forgerock.json.JsonValue) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException) OrganizationConfigManager(com.sun.identity.sm.OrganizationConfigManager) PermanentException(org.forgerock.json.resource.PermanentException) BadRequestException(org.forgerock.json.resource.BadRequestException)

Example 20 with PermanentException

use of org.forgerock.json.resource.PermanentException in project OpenAM by OpenRock.

the class TokenResource method queryCollection.

@Override
public Promise<QueryResponse, ResourceException> queryCollection(Context context, QueryRequest queryRequest, QueryResourceHandler handler) {
    try {
        JsonValue response;
        Collection<QueryFilter<CoreTokenField>> query = new ArrayList<QueryFilter<CoreTokenField>>();
        //get uid of submitter
        AMIdentity uid;
        try {
            uid = getUid(context);
            if (!uid.equals(adminUserId)) {
                query.add(QueryFilter.equalTo(USERNAME_FIELD, uid.getName()));
                query.add(QueryFilter.equalTo(REALM_FIELD, DNMapper.orgNameToRealmName(uid.getRealm())));
            }
        } catch (Exception e) {
            if (debug.errorEnabled()) {
                debug.error("TokenResource :: QUERY : Unable to query collection as no UID discovered " + "for requesting user.");
            }
            return new PermanentException(401, "Unauthorized", e).asPromise();
        }
        String id = queryRequest.getQueryId();
        String queryString;
        if (id.equals("access_token")) {
            queryString = "tokenName=access_token";
        } else {
            queryString = id;
        }
        String[] constraints = queryString.split(",");
        boolean userNamePresent = false;
        for (String constraint : constraints) {
            String[] params = constraint.split("=");
            if (params.length == 2) {
                if (OAuthTokenField.USER_NAME.getOAuthField().equals(params[0])) {
                    userNamePresent = true;
                }
                query.add(QueryFilter.equalTo(getOAuth2TokenField(params[0]), params[1]));
            }
        }
        if (adminUserId.equals(uid)) {
            if (!userNamePresent) {
                return new BadRequestException("userName field MUST be set in _queryId").asPromise();
            }
        } else if (userNamePresent) {
            return new BadRequestException("userName field MUST NOT be set in _queryId").asPromise();
        }
        response = tokenStore.query(QueryFilter.and(query));
        return handleResponse(handler, response, context);
    } catch (UnauthorizedClientException e) {
        debug.error("TokenResource :: QUERY : Unable to query collection as the client is not authorized.", e);
        return new PermanentException(401, e.getMessage(), e).asPromise();
    } catch (CoreTokenException e) {
        debug.error("TokenResource :: QUERY : Unable to query collection as the token store is not available.", e);
        return new ServiceUnavailableException(e.getMessage(), e).asPromise();
    } catch (InternalServerErrorException e) {
        debug.error("TokenResource :: QUERY : Unable to query collection as writing the response failed.", e);
        return e.asPromise();
    } catch (NotFoundException e) {
        debug.error("TokenResource :: QUERY : Unable to query collection as realm does not have OAuth 2 provider.", e);
        return e.asPromise();
    }
}
Also used : JsonValue(org.forgerock.json.JsonValue) ArrayList(java.util.ArrayList) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) NotFoundException(org.forgerock.json.resource.NotFoundException) CoreTokenField(org.forgerock.openam.tokens.CoreTokenField) ServiceUnavailableException(org.forgerock.json.resource.ServiceUnavailableException) PermanentException(org.forgerock.json.resource.PermanentException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) ServiceUnavailableException(org.forgerock.json.resource.ServiceUnavailableException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) SSOException(com.iplanet.sso.SSOException) NotFoundException(org.forgerock.json.resource.NotFoundException) 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) QueryFilter(org.forgerock.util.query.QueryFilter) AMIdentity(com.sun.identity.idm.AMIdentity) PermanentException(org.forgerock.json.resource.PermanentException) UnauthorizedClientException(org.forgerock.oauth2.core.exceptions.UnauthorizedClientException) BadRequestException(org.forgerock.json.resource.BadRequestException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException)

Aggregations

PermanentException (org.forgerock.json.resource.PermanentException)21 SSOException (com.iplanet.sso.SSOException)19 ResourceException (org.forgerock.json.resource.ResourceException)17 BadRequestException (org.forgerock.json.resource.BadRequestException)16 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)16 NotFoundException (org.forgerock.json.resource.NotFoundException)16 SMSException (com.sun.identity.sm.SMSException)15 IdRepoException (com.sun.identity.idm.IdRepoException)14 JsonValue (org.forgerock.json.JsonValue)14 ForbiddenException (org.forgerock.json.resource.ForbiddenException)14 RealmContext (org.forgerock.openam.rest.RealmContext)13 ConflictException (org.forgerock.json.resource.ConflictException)12 ResourceResponse (org.forgerock.json.resource.ResourceResponse)10 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)9 NotSupportedException (org.forgerock.json.resource.NotSupportedException)8 IdentityDetails (com.sun.identity.idsvcs.IdentityDetails)7 ObjectNotFound (com.sun.identity.idsvcs.ObjectNotFound)7 TokenExpired (com.sun.identity.idsvcs.TokenExpired)7 OrganizationConfigManager (com.sun.identity.sm.OrganizationConfigManager)7 SSOToken (com.iplanet.sso.SSOToken)6