Search in sources :

Example 26 with CoreTokenException

use of org.forgerock.openam.cts.exceptions.CoreTokenException in project OpenAM by OpenRock.

the class IdentityResourceV1 method confirmationIdCheck.

/**
     * Will validate confirmationId is correct
     * @param context Current Server Context
     * @param request Request from client to confirm registration
     */
private Promise<ActionResponse, ResourceException> confirmationIdCheck(final Context context, final ActionRequest request, final String realm) {
    final String METHOD = "IdentityResource.confirmationIdCheck";
    final JsonValue jVal = request.getContent();
    String tokenID;
    String confirmationId;
    String email = null;
    String username = null;
    //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 : 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)

Example 27 with CoreTokenException

use of org.forgerock.openam.cts.exceptions.CoreTokenException in project OpenAM by OpenRock.

the class IdentityResourceV2 method anonymousCreate.

private Promise<ActionResponse, ResourceException> anonymousCreate(final Context context, final ActionRequest request, final String realm, RestSecurity restSecurity) {
    final JsonValue jVal = request.getContent();
    String tokenID = null;
    String confirmationId;
    String email;
    try {
        if (!restSecurity.isSelfRegistration()) {
            throw new BadRequestException("Self-registration disabled");
        }
        tokenID = jVal.get(TOKEN_ID).asString();
        jVal.remove(TOKEN_ID);
        confirmationId = jVal.get(CONFIRMATION_ID).asString();
        jVal.remove(CONFIRMATION_ID);
        email = jVal.get(EMAIL).asString();
        if (email == null || email.isEmpty()) {
            throw new BadRequestException("Email not provided");
        }
        // Convert to IDRepo Attribute schema
        jVal.put("mail", email);
        if (confirmationId == null || confirmationId.isEmpty()) {
            throw new BadRequestException("confirmationId not provided");
        }
        if (tokenID == null || tokenID.isEmpty()) {
            throw new BadRequestException("tokenId not provided");
        }
        validateToken(tokenID, realm, email, confirmationId);
        // create an Identity
        SSOToken admin = RestUtils.getToken();
        final String finalTokenID = tokenID;
        return createInstance(admin, jVal, realm).thenAsync(new AsyncFunction<ActionResponse, ActionResponse, ResourceException>() {

            @Override
            public Promise<ActionResponse, ResourceException> apply(ActionResponse response) {
                // Only remove the token if the create 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 completed registration request cannot be made again using the same token.
                    CTSHolder.getCTS().deleteAsync(finalTokenID);
                } catch (DeleteFailedException e) {
                    // reading and deleting, the token has expired.
                    if (debug.messageEnabled()) {
                        debug.message("IdentityResource.anonymousCreate: Deleting token " + finalTokenID + " after a successful read failed due to " + e.getMessage(), e);
                    }
                } catch (CoreTokenException cte) {
                    // For any unexpected CTS error
                    debug.error("IdentityResource.anonymousCreate(): CTS Error : " + cte.getMessage());
                    return new InternalServerErrorException(cte.getMessage(), cte).asPromise();
                }
                return newResultPromise(response);
            }
        });
    } catch (BadRequestException bre) {
        debug.warning("IdentityResource.anonymousCreate() :: Invalid Parameter", bre);
        return bre.asPromise();
    } catch (ResourceException re) {
        debug.warning("IdentityResource.anonymousCreate() :: Resource error", re);
        return re.asPromise();
    } catch (CoreTokenException cte) {
        // For any unexpected CTS error
        debug.error("IdentityResource.anonymousCreate() :: CTS error", cte);
        return new InternalServerErrorException(cte).asPromise();
    } catch (ServiceNotFoundException snfe) {
        // Failure from RestSecurity
        debug.error("IdentityResource.anonymousCreate() :: Internal error", snfe);
        return new InternalServerErrorException(snfe).asPromise();
    }
}
Also used : SSOToken(com.iplanet.sso.SSOToken) JsonValue(org.forgerock.json.JsonValue) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) ActionResponse(org.forgerock.json.resource.ActionResponse) Responses.newActionResponse(org.forgerock.json.resource.Responses.newActionResponse) Promises.newResultPromise(org.forgerock.util.promise.Promises.newResultPromise) Promise(org.forgerock.util.promise.Promise) DeleteFailedException(org.forgerock.openam.cts.exceptions.DeleteFailedException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ResourceException(org.forgerock.json.resource.ResourceException)

Example 28 with CoreTokenException

use of org.forgerock.openam.cts.exceptions.CoreTokenException in project OpenAM by OpenRock.

the class IdentityResourceV1 method anonymousCreate.

private Promise<ActionResponse, ResourceException> anonymousCreate(final Context context, final ActionRequest request, final String realm, RestSecurity restSecurity) {
    final JsonValue jVal = request.getContent();
    String confirmationId;
    String email;
    try {
        if (!restSecurity.isSelfRegistration()) {
            throw new BadRequestException("Self-registration disabled");
        }
        final String tokenID = jVal.get(TOKEN_ID).asString();
        jVal.remove(TOKEN_ID);
        confirmationId = jVal.get(CONFIRMATION_ID).asString();
        jVal.remove(CONFIRMATION_ID);
        email = jVal.get(EMAIL).asString();
        if (email == null || email.isEmpty()) {
            throw new BadRequestException("Email not provided");
        }
        // Convert to IDRepo Attribute schema
        jVal.put("mail", email);
        if (confirmationId == null || confirmationId.isEmpty()) {
            throw new BadRequestException("confirmationId not provided");
        }
        if (tokenID == null || tokenID.isEmpty()) {
            throw new BadRequestException("tokenId not provided");
        }
        validateToken(tokenID, realm, email, confirmationId);
        // create an Identity
        SSOToken admin = RestUtils.getToken();
        return createInstance(admin, jVal, realm).thenAsync(new AsyncFunction<ActionResponse, ActionResponse, ResourceException>() {

            @Override
            public Promise<ActionResponse, ResourceException> apply(ActionResponse response) {
                // Only remove the token if the create 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 completed registration 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("IdentityResource.anonymousCreate: Deleting token {} after a" + " successful read failed.", tokenID, e);
                    }
                } catch (CoreTokenException cte) {
                    // For any unexpected CTS error
                    debug.error("IdentityResource.anonymousCreate(): CTS Error", cte);
                    return new InternalServerErrorException(cte.getMessage(), cte).asPromise();
                }
                return newResultPromise(response);
            }
        });
    } catch (BadRequestException bre) {
        debug.warning("IdentityResource.anonymousCreate() :: Invalid Parameter", bre);
        return bre.asPromise();
    } catch (ResourceException re) {
        debug.warning("IdentityResource.anonymousCreate() :: Resource error", re);
        return re.asPromise();
    } catch (CoreTokenException cte) {
        // For any unexpected CTS error
        debug.error("IdentityResource.anonymousCreate() :: CTS error", cte);
        return new InternalServerErrorException(cte).asPromise();
    } catch (ServiceNotFoundException snfe) {
        // Failure from RestSecurity
        debug.error("IdentityResource.anonymousCreate() :: Internal error", snfe);
        return new InternalServerErrorException(snfe).asPromise();
    }
}
Also used : IdentityRestUtils.getSSOToken(org.forgerock.openam.core.rest.IdentityRestUtils.getSSOToken) SSOToken(com.iplanet.sso.SSOToken) IdentityRestUtils.identityDetailsToJsonValue(org.forgerock.openam.core.rest.IdentityRestUtils.identityDetailsToJsonValue) JsonValue(org.forgerock.json.JsonValue) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) ActionResponse(org.forgerock.json.resource.ActionResponse) Promises.newResultPromise(org.forgerock.util.promise.Promises.newResultPromise) Promise(org.forgerock.util.promise.Promise) DeleteFailedException(org.forgerock.openam.cts.exceptions.DeleteFailedException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ResourceException(org.forgerock.json.resource.ResourceException)

Example 29 with CoreTokenException

use of org.forgerock.openam.cts.exceptions.CoreTokenException in project OpenAM by OpenRock.

the class CTSSessionBlacklist method blacklist.

@Override
public void blacklist(final Session session) throws SessionException {
    DEBUG.message("CTSSessionBlacklist: Blacklisting session: {}", session);
    try {
        final Token token = new Token(session.getStableStorageID(), TokenType.SESSION_BLACKLIST);
        token.setExpiryTimestamp(timeOf(session.getBlacklistExpiryTime(purgeDelayMs)));
        token.setAttribute(BLACKLIST_TIME_FIELD, now());
        token.setAttribute(SERVER_ID_FIELD, localServerId);
        cts.create(token);
    } catch (CoreTokenException ex) {
        DEBUG.error("CTSSessionBlacklist: Error blacklisting session", ex);
        throw new SessionException(ex);
    }
    notifyListeners(session);
}
Also used : CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) SessionException(com.iplanet.dpro.session.SessionException) PartialToken(org.forgerock.openam.sm.datalayer.api.query.PartialToken) Token(org.forgerock.openam.cts.api.tokens.Token)

Example 30 with CoreTokenException

use of org.forgerock.openam.cts.exceptions.CoreTokenException in project OpenAM by OpenRock.

the class LdapQueryBuilder method getEntries.

private Collection<Entry> getEntries(Connection connection) throws CoreTokenException {
    // Prepare the search
    Filter ldapFilter = getLDAPFilter();
    SearchRequest searchRequest = LDAPRequests.newSearchRequest(dataLayerConfiguration.getTokenStoreRootSuffix(), SearchScope.WHOLE_SUBTREE, ldapFilter, requestedAttributes);
    searchRequest.setSizeLimit(sizeLimit);
    if (isPagingResults()) {
        searchRequest = searchRequest.addControl(SimplePagedResultsControl.newControl(true, pageSize, pagingCookie));
    }
    // Perform the search
    Collection<Entry> entries = createResultsList();
    final Result result = handler.performSearch(connection, searchRequest, entries);
    if (isPagingResults()) {
        try {
            SimplePagedResultsControl control = result.getControl(SimplePagedResultsControl.DECODER, new DecodeOptions());
            if (control == null) {
                if (debug.warningEnabled()) {
                    debug.warning("There was no paged result control in the search response, it is recommended to " + "set the CTS user's size-limit at least to " + (pageSize + 1));
                }
                pagingCookie = getEmptyPagingCookie();
            } else {
                pagingCookie = control.getCookie();
            }
        } catch (DecodeException e) {
            throw new CoreTokenException("Failed to decode Paging Cookie", e);
        }
    }
    if (debug.messageEnabled()) {
        debug.message(MessageFormat.format(CoreTokenConstants.DEBUG_HEADER + "Query: matched {0} results\n" + "Search Request: {1}\n" + "Filter: {2}\n" + "Result: {3}", entries.size(), searchRequest, ldapFilter.toString(), result));
    }
    return entries;
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) Entry(org.forgerock.opendj.ldap.Entry) Filter(org.forgerock.opendj.ldap.Filter) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) SimplePagedResultsControl(org.forgerock.opendj.ldap.controls.SimplePagedResultsControl) DecodeException(org.forgerock.opendj.ldap.DecodeException) DecodeOptions(org.forgerock.opendj.ldap.DecodeOptions) Result(org.forgerock.opendj.ldap.responses.Result)

Aggregations

CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)59 JsonValue (org.forgerock.json.JsonValue)21 ServerException (org.forgerock.oauth2.core.exceptions.ServerException)19 Token (org.forgerock.openam.cts.api.tokens.Token)14 Test (org.testng.annotations.Test)11 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)10 ResourceException (org.forgerock.json.resource.ResourceException)9 PartialToken (org.forgerock.openam.sm.datalayer.api.query.PartialToken)9 BadRequestException (org.forgerock.json.resource.BadRequestException)8 ArrayList (java.util.ArrayList)7 ResourceResponse (org.forgerock.json.resource.ResourceResponse)7 SSOException (com.iplanet.sso.SSOException)6 SSOToken (com.iplanet.sso.SSOToken)6 IdRepoException (com.sun.identity.idm.IdRepoException)6 HashMap (java.util.HashMap)5 Responses.newResourceResponse (org.forgerock.json.resource.Responses.newResourceResponse)5 OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)5 TokenFilter (org.forgerock.openam.cts.api.filter.TokenFilter)5 TokenFilterBuilder (org.forgerock.openam.cts.api.filter.TokenFilterBuilder)5 DeleteFailedException (org.forgerock.openam.cts.exceptions.DeleteFailedException)5