Search in sources :

Example 66 with BadRequestException

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

the class IdentityResourceV2 method confirmationIdCheck.

/**
     * Will validate confirmationId is correct
     * @param request Request from client to confirm registration
     */
private Promise<ActionResponse, ResourceException> confirmationIdCheck(final ActionRequest request, final String realm) {
    final String METHOD = "IdentityResource.confirmationIdCheck";
    final JsonValue jVal = request.getContent();
    String tokenID = "";
    String confirmationId;
    String email;
    String username;
    //email or username value used to create confirmationId
    String hashComponent = null;
    String hashComponentAttr = null;
    JsonValue result = new JsonValue(new LinkedHashMap<String, Object>(1));
    try {
        tokenID = jVal.get(TOKEN_ID).asString();
        confirmationId = jVal.get(CONFIRMATION_ID).asString();
        email = jVal.get(EMAIL).asString();
        username = jVal.get(USERNAME).asString();
        if (StringUtils.isBlank(confirmationId)) {
            if (debug.errorEnabled()) {
                debug.error("{} :: Bad Request - confirmationId not found in request.", METHOD);
            }
            throw new BadRequestException("confirmationId not provided");
        }
        if (StringUtils.isBlank(email) && !StringUtils.isBlank(username)) {
            hashComponent = username;
            hashComponentAttr = USERNAME;
        }
        if (!StringUtils.isBlank(email) && StringUtils.isBlank(username)) {
            hashComponent = email;
            hashComponentAttr = EMAIL;
        }
        if (StringUtils.isBlank(hashComponent)) {
            if (debug.errorEnabled()) {
                debug.error("{} :: Bad Request - hashComponent not found in request.", METHOD);
            }
            throw new BadRequestException("Required information not provided");
        }
        if (StringUtils.isBlank(tokenID)) {
            if (debug.errorEnabled()) {
                debug.error("{} :: Bad Request - tokenID not found in request.", METHOD);
            }
            throw new BadRequestException("tokenId not provided");
        }
        validateToken(tokenID, realm, hashComponent, confirmationId);
        // build resource
        result.put(hashComponentAttr, hashComponent);
        result.put(TOKEN_ID, tokenID);
        result.put(CONFIRMATION_ID, confirmationId);
        if (debug.messageEnabled()) {
            debug.message("{} :: Confirmed for token '{}' with confirmation '{}'", METHOD, tokenID, confirmationId);
        }
        return newResultPromise(newActionResponse(result));
    } catch (BadRequestException bre) {
        debug.warning("{} :: Cannot confirm registration/forgotPassword for : {}", METHOD, hashComponent, bre);
        return bre.asPromise();
    } catch (ResourceException re) {
        debug.warning("{} :: Resource error for : {}", METHOD, hashComponent, re);
        return re.asPromise();
    } catch (CoreTokenException cte) {
        debug.error("{} :: CTE error for : {}", METHOD, hashComponent, cte);
        return new InternalServerErrorException(cte).asPromise();
    }
}
Also used : JsonValue(org.forgerock.json.JsonValue) BadRequestException(org.forgerock.json.resource.BadRequestException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ResourceException(org.forgerock.json.resource.ResourceException)

Example 67 with BadRequestException

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

the class IdentityResourceV1 method anonymousUpdate.

/**
     * Perform an anonymous update of a user's password using the provided token.
     *
     * The token must match a token placed in the CTS in order for the request
     * to proceed.
     *
     * @param context Non null
     * @param request Non null
     * @param realm Non null
     */
private Promise<ActionResponse, ResourceException> anonymousUpdate(final Context context, final ActionRequest request, final String realm) {
    final String tokenID;
    String confirmationId;
    String username;
    String nwpassword;
    final JsonValue jVal = request.getContent();
    try {
        tokenID = jVal.get(TOKEN_ID).asString();
        jVal.remove(TOKEN_ID);
        confirmationId = jVal.get(CONFIRMATION_ID).asString();
        jVal.remove(CONFIRMATION_ID);
        username = jVal.get(USERNAME).asString();
        nwpassword = jVal.get("userpassword").asString();
        if (username == null || username.isEmpty()) {
            throw new BadRequestException("username not provided");
        }
        if (nwpassword == null || username.isEmpty()) {
            throw new BadRequestException("new password not provided");
        }
        validateToken(tokenID, realm, username, confirmationId);
        // update Identity
        SSOToken admin = RestUtils.getToken();
        // Update instance with new password value
        return updateInstance(admin, jVal, realm).thenAsync(new AsyncFunction<ActionResponse, ActionResponse, ResourceException>() {

            @Override
            public Promise<ActionResponse, ResourceException> apply(ActionResponse response) {
                // Only remove the token if the update was successful, errors will be set in the handler.
                try {
                    // Even though the generated token will eventually timeout, delete it after a successful read
                    // so that the reset password request cannot be made again using the same token.
                    CTSHolder.getCTS().deleteAsync(tokenID);
                } catch (DeleteFailedException e) {
                    // reading and deleting, the token has expired.
                    if (debug.messageEnabled()) {
                        debug.message("Deleting token " + tokenID + " after a successful " + "read failed due to " + e.getMessage(), e);
                    }
                } catch (CoreTokenException cte) {
                    // For any unexpected CTS error
                    debug.error("Error performing anonymousUpdate", cte);
                    return new InternalServerErrorException(cte.getMessage(), cte).asPromise();
                }
                return newResultPromise(response);
            }
        });
    } catch (BadRequestException bre) {
        // For any malformed request.
        debug.warning("Bad request received for anonymousUpdate " + bre.getMessage());
        return bre.asPromise();
    } catch (ResourceException re) {
        debug.warning("Error performing anonymousUpdate", re);
        return re.asPromise();
    } catch (CoreTokenException cte) {
        // For any unexpected CTS error
        debug.error("Error performing anonymousUpdate", cte);
        return new InternalServerErrorException(cte).asPromise();
    }
}
Also used : Promises.newResultPromise(org.forgerock.util.promise.Promises.newResultPromise) Promise(org.forgerock.util.promise.Promise) IdentityRestUtils.getSSOToken(org.forgerock.openam.core.rest.IdentityRestUtils.getSSOToken) SSOToken(com.iplanet.sso.SSOToken) DeleteFailedException(org.forgerock.openam.cts.exceptions.DeleteFailedException) IdentityRestUtils.identityDetailsToJsonValue(org.forgerock.openam.core.rest.IdentityRestUtils.identityDetailsToJsonValue) JsonValue(org.forgerock.json.JsonValue) BadRequestException(org.forgerock.json.resource.BadRequestException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ResourceException(org.forgerock.json.resource.ResourceException) ActionResponse(org.forgerock.json.resource.ActionResponse)

Example 68 with BadRequestException

use of org.forgerock.json.resource.BadRequestException 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 69 with BadRequestException

use of org.forgerock.json.resource.BadRequestException 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 70 with BadRequestException

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

the class SmsServerPropertiesResource method updateInstance.

@Override
public Promise<ResourceResponse, ResourceException> updateInstance(Context serverContext, UpdateRequest updateRequest) {
    Map<String, String> uriVariables = getUriTemplateVariables(serverContext);
    final String tabName = getTabName(uriVariables);
    if (tabName == null) {
        return new BadRequestException("Tab name not specified.").asPromise();
    }
    final String serverName = getServerName(uriVariables);
    if (serverName == null) {
        return new BadRequestException("Server name not specified.").asPromise();
    }
    try {
        ServiceConfigManager scm = getServiceConfigManager(serverContext);
        ServiceConfig serverConfigs = getServerConfigs(scm);
        final ServiceConfig serverConfig = serverConfigs.getSubConfig(serverName);
        final JsonValue jsonValue = updateRequest.toJsonValue();
        final Map newAttributeValues = (Map) ((Map) jsonValue.getObject()).get("content");
        Set<String> attributesToBeAlteredNames = newAttributeValues.keySet();
        final Map allAttributes = serverConfig.getAttributes();
        Set<String> currentAttributes = (Set) allAttributes.get(SERVER_CONFIG);
        Set<String> newAttributes = new HashSet<>();
        for (String attribute : currentAttributes) {
            String attributeName = attribute.split("=")[0];
            if (attributesToBeAlteredNames.contains(attributeName)) {
                newAttributes.add(attributeName + "=" + newAttributeValues.get(attributeName));
            } else {
                newAttributes.add(attribute);
            }
        }
        allAttributes.put(SERVER_CONFIG, newAttributes);
        serverConfig.setAttributes(allAttributes);
        return newResultPromise(newResourceResponse(tabName, String.valueOf(jsonValue.hashCode()), jsonValue.get("content")));
    } catch (SSOException e) {
        logger.error("Error getting SSOToken", e);
    } catch (SMSException e) {
        logger.error("Error getting service config manager", e);
    }
    return new BadRequestException("Error updating values for " + tabName).asPromise();
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) ServiceConfig(com.sun.identity.sm.ServiceConfig) SMSException(com.sun.identity.sm.SMSException) JsonValue(org.forgerock.json.JsonValue) BadRequestException(org.forgerock.json.resource.BadRequestException) SSOException(com.iplanet.sso.SSOException) Map(java.util.Map) HashMap(java.util.HashMap) ServiceConfigManager(com.sun.identity.sm.ServiceConfigManager) HashSet(java.util.HashSet)

Aggregations

BadRequestException (org.forgerock.json.resource.BadRequestException)82 JsonValue (org.forgerock.json.JsonValue)44 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)40 ResourceException (org.forgerock.json.resource.ResourceException)39 SSOException (com.iplanet.sso.SSOException)37 NotFoundException (org.forgerock.json.resource.NotFoundException)37 SMSException (com.sun.identity.sm.SMSException)31 ForbiddenException (org.forgerock.json.resource.ForbiddenException)26 ResourceResponse (org.forgerock.json.resource.ResourceResponse)25 IdRepoException (com.sun.identity.idm.IdRepoException)23 PermanentException (org.forgerock.json.resource.PermanentException)22 ConflictException (org.forgerock.json.resource.ConflictException)21 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)20 SSOToken (com.iplanet.sso.SSOToken)19 NotSupportedException (org.forgerock.json.resource.NotSupportedException)17 RealmContext (org.forgerock.openam.rest.RealmContext)17 ServiceNotFoundException (com.sun.identity.sm.ServiceNotFoundException)16 DeleteFailedException (org.forgerock.openam.cts.exceptions.DeleteFailedException)16 IdentityDetails (com.sun.identity.idsvcs.IdentityDetails)14 MessagingException (javax.mail.MessagingException)13