Search in sources :

Example 11 with HttpContext

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

the class IdentityResourceV1 method createRegistrationEmail.

/**
     * This method will create a confirmation email that contains a {@link org.forgerock.openam.cts.api.tokens.Token},
     * confirmationId and email that was provided in the request.
     * @param context Current Server Context
     * @param request Request from client to retrieve id
     */
private Promise<ActionResponse, ResourceException> createRegistrationEmail(final Context context, final ActionRequest request, final String realm, final RestSecurity restSecurity) {
    JsonValue result = new JsonValue(new LinkedHashMap<String, Object>(1));
    final JsonValue jVal = request.getContent();
    String emailAddress = null;
    String confirmationLink;
    String tokenID;
    try {
        if (restSecurity == null) {
            if (debug.warningEnabled()) {
                debug.warning("IdentityResource.createRegistrationEmail(): Rest Security not created. " + "restSecurity={}", restSecurity);
            }
            throw new NotFoundException("Rest Security Service not created");
        }
        if (!restSecurity.isSelfRegistration()) {
            if (debug.warningEnabled()) {
                debug.warning("IdentityResource.createRegistrationEmail(): Self-Registration set to : {}", restSecurity.isSelfRegistration());
            }
            throw new NotSupportedException("Self Registration is not enabled.");
        }
        // Get full deployment URL
        HttpContext header = context.asContext(HttpContext.class);
        StringBuilder deploymentURL = RestUtils.getFullDeploymentURI(header.getPath());
        // Get the email address provided from registration page
        emailAddress = jVal.get(EMAIL).asString();
        if (StringUtils.isBlank(emailAddress)) {
            throw new BadRequestException("Email not provided");
        }
        String subject = jVal.get("subject").asString();
        String message = jVal.get("message").asString();
        // Retrieve email registration token life time
        Long tokenLifeTime = restSecurity.getSelfRegTLT();
        // Create CTS Token
        org.forgerock.openam.cts.api.tokens.Token ctsToken = generateToken(emailAddress, "anonymous", tokenLifeTime, realm);
        // Store token in datastore
        CTSHolder.getCTS().createAsync(ctsToken);
        tokenID = ctsToken.getTokenId();
        // Create confirmationId
        String confirmationId = Hash.hash(tokenID + emailAddress + SystemProperties.get(AM_ENCRYPTION_PWD));
        // Build Confirmation URL
        String confURL = restSecurity.getSelfRegistrationConfirmationUrl();
        StringBuilder confURLBuilder = new StringBuilder(100);
        if (StringUtils.isBlank(confURL)) {
            confURLBuilder.append(deploymentURL.append("/json/confirmation/register").toString());
        } else {
            confURLBuilder.append(confURL);
        }
        confirmationLink = confURLBuilder.append("?confirmationId=").append(requestParamEncode(confirmationId)).append("&email=").append(requestParamEncode(emailAddress)).append("&tokenId=").append(requestParamEncode(tokenID)).append("&realm=").append(realm).toString();
        // Send Registration
        sendNotification(emailAddress, subject, message, realm, confirmationLink);
        if (debug.messageEnabled()) {
            debug.message("IdentityResource.createRegistrationEmail() :: Sent notification to={} with subject={}. " + "In realm={} for token ID={}", emailAddress, subject, realm, tokenID);
        }
        return newResultPromise(newActionResponse(result));
    } catch (BadRequestException | NotFoundException be) {
        debug.warning("IdentityResource.createRegistrationEmail: Cannot send email to {}", emailAddress, be);
        return be.asPromise();
    } catch (NotSupportedException nse) {
        debug.error("IdentityResource.createRegistrationEmail: Operation not enabled", nse);
        return nse.asPromise();
    } catch (Exception e) {
        debug.error("IdentityResource.createRegistrationEmail: Cannot send email to {}", emailAddress, e);
        return new NotFoundException("Email not sent").asPromise();
    }
}
Also used : IdentityRestUtils.identityDetailsToJsonValue(org.forgerock.openam.core.rest.IdentityRestUtils.identityDetailsToJsonValue) JsonValue(org.forgerock.json.JsonValue) HttpContext(org.forgerock.json.resource.http.HttpContext) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) 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) BadRequestException(org.forgerock.json.resource.BadRequestException) NotSupportedException(org.forgerock.json.resource.NotSupportedException)

Example 12 with HttpContext

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

the class IdentityResourceV2 method generateNewPasswordEmail.

/**
     * Generates the e-mail contents based on the incoming request.
     *
     * Will only send the e-mail if all the following conditions are true:
     *
     * - Forgotten Password service is enabled
     * - User exists
     * - User has an e-mail address in their profile
     * - E-mail service is correctly configured.
     *
     * @param context Non null.
     * @param request Non null.
     * @param realm Used as part of user lookup.
     * @param restSecurity Non null.
     */
private Promise<ActionResponse, ResourceException> generateNewPasswordEmail(final Context context, final ActionRequest request, final String realm, final RestSecurity restSecurity) {
    JsonValue result = new JsonValue(new LinkedHashMap<String, Object>(1));
    final JsonValue jsonBody = request.getContent();
    try {
        // Check to make sure forgotPassword enabled
        if (restSecurity == null) {
            if (debug.warningEnabled()) {
                debug.warning("Rest Security not created. restSecurity={}", restSecurity);
            }
            throw getException(UNAVAILABLE, "Rest Security Service not created");
        }
        if (!restSecurity.isSelfServiceRestEndpointEnabled()) {
            if (debug.warningEnabled()) {
                debug.warning("Forgot Password set to : {}", restSecurity.isSelfServiceRestEndpointEnabled());
            }
            throw getException(UNAVAILABLE, "Legacy Self Service REST Endpoint is not enabled.");
        }
        if (!restSecurity.isForgotPassword()) {
            if (debug.warningEnabled()) {
                debug.warning("Forgot Password set to : {}", restSecurity.isForgotPassword());
            }
            throw getException(UNAVAILABLE, "Forgot password is not accessible.");
        }
        // Generate Admin Token
        SSOToken adminToken = getSSOToken(RestUtils.getToken().getTokenID().toString());
        Map<String, Set<String>> searchAttributes = getIdentityServicesAttributes(realm, objectType);
        searchAttributes.putAll(getAttributeFromRequest(jsonBody));
        List<String> searchResults = identityServices.search(new CrestQuery("*"), searchAttributes, adminToken);
        if (searchResults.isEmpty()) {
            throw new NotFoundException("User not found");
        } else if (searchResults.size() > 1) {
            throw new ConflictException("Multiple users found");
        } else {
            String username = searchResults.get(0);
            IdentityDetails identityDetails = identityServices.read(username, getIdentityServicesAttributes(realm, objectType), adminToken);
            String email = null;
            String uid = null;
            for (Map.Entry<String, Set<String>> attribute : asMap(identityDetails.getAttributes()).entrySet()) {
                String attributeName = attribute.getKey();
                if (MAIL.equalsIgnoreCase(attributeName)) {
                    if (attribute.getValue() != null && !attribute.getValue().isEmpty()) {
                        email = attribute.getValue().iterator().next();
                    }
                } else if (UNIVERSAL_ID.equalsIgnoreCase(attributeName)) {
                    if (attribute.getValue() != null && !attribute.getValue().isEmpty()) {
                        uid = attribute.getValue().iterator().next();
                    }
                }
            }
            // Check to see if user is Active/Inactive
            if (!isUserActive(uid)) {
                throw new ForbiddenException("Request is forbidden for this user");
            }
            // Check if email is provided
            if (email == null || email.isEmpty()) {
                throw new BadRequestException("No email provided in profile.");
            }
            // Get full deployment URL
            HttpContext header = context.asContext(HttpContext.class);
            String baseURL = baseURLProviderFactory.get(realm).getRootURL(header);
            String subject = jsonBody.get("subject").asString();
            String message = jsonBody.get("message").asString();
            // Retrieve email registration token life time
            if (restSecurity == null) {
                if (debug.warningEnabled()) {
                    debug.warning("Rest Security not created. restSecurity={}", restSecurity);
                }
                throw new NotFoundException("Rest Security Service not created");
            }
            Long tokenLifeTime = restSecurity.getForgotPassTLT();
            // Generate Token
            org.forgerock.openam.cts.api.tokens.Token ctsToken = generateToken(email, username, tokenLifeTime, realm);
            // Store token in datastore
            CTSHolder.getCTS().createAsync(ctsToken);
            // Create confirmationId
            String confirmationId = Hash.hash(ctsToken.getTokenId() + username + SystemProperties.get(AM_ENCRYPTION_PWD));
            // Build Confirmation URL
            String confURL = restSecurity.getForgotPasswordConfirmationUrl();
            StringBuilder confURLBuilder = new StringBuilder(100);
            if (StringUtils.isEmpty(confURL)) {
                confURLBuilder.append(baseURL).append("/json/confirmation/forgotPassword");
            } else if (confURL.startsWith("/")) {
                confURLBuilder.append(baseURL).append(confURL);
            } else {
                confURLBuilder.append(confURL);
            }
            String confirmationLink = confURLBuilder.append("?confirmationId=").append(requestParamEncode(confirmationId)).append("&tokenId=").append(requestParamEncode(ctsToken.getTokenId())).append("&username=").append(requestParamEncode(username)).append("&realm=").append(realm).toString();
            // Send Registration
            sendNotification(email, subject, message, realm, confirmationLink);
            String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
            if (debug.messageEnabled()) {
                debug.message("IdentityResource.generateNewPasswordEmail :: ACTION of generate new password email " + " for username={} in realm={} performed by principalName={}", username, realm, principalName);
            }
        }
        return newResultPromise(newActionResponse(result));
    } catch (ResourceException re) {
        // Service not available, Neither or both Username/Email provided, User inactive
        debug.warning(re.getMessage(), re);
        return re.asPromise();
    } catch (Exception e) {
        // Intentional - all other errors are considered Internal Error.
        debug.error("Internal error", e);
        return new InternalServerErrorException("Failed to send mail", e).asPromise();
    }
}
Also used : SSOToken(com.iplanet.sso.SSOToken) Set(java.util.Set) HashSet(java.util.HashSet) ConflictException(org.forgerock.json.resource.ConflictException) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) SSOToken(com.iplanet.sso.SSOToken) ResourceException(org.forgerock.json.resource.ResourceException) CrestQuery(org.forgerock.openam.utils.CrestQuery) ForbiddenException(org.forgerock.json.resource.ForbiddenException) JsonValue(org.forgerock.json.JsonValue) HttpContext(org.forgerock.json.resource.http.HttpContext) 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) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails) BadRequestException(org.forgerock.json.resource.BadRequestException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException)

Example 13 with HttpContext

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

the class ServerInfoResource method getAllServerInfo.

/**
     * Retrieves all server info set on the server.
     *
     * @param context
     *         Current Server Context.
     * @param realm
     *         realm in whose security context we use.
     */
private Promise<ResourceResponse, ResourceException> getAllServerInfo(Context context, String realm) {
    JsonValue result = new JsonValue(new LinkedHashMap<String, Object>(1));
    Set<String> cookieDomains;
    ResourceResponse resource;
    //added for the XUI to be able to understand its locale to request the appropriate translations to cache
    ISLocaleContext localeContext = new ISLocaleContext();
    HttpContext httpContext = context.asContext(HttpContext.class);
    //we have nothing else to go on at this point other than their request
    localeContext.setLocale(httpContext);
    SelfServiceInfo selfServiceInfo = configHandler.getConfig(realm, SelfServiceInfoBuilder.class);
    RestSecurity restSecurity = restSecurityProvider.get(realm);
    Set<String> protectedUserAttributes = new HashSet<>();
    protectedUserAttributes.addAll(selfServiceInfo.getProtectedUserAttributes());
    protectedUserAttributes.addAll(restSecurity.getProtectedUserAttributes());
    try {
        cookieDomains = AuthClientUtils.getCookieDomains();
        result.put("domains", cookieDomains);
        result.put("protectedUserAttributes", protectedUserAttributes);
        result.put("cookieName", SystemProperties.get(Constants.AM_COOKIE_NAME, "iPlanetDirectoryPro"));
        result.put("secureCookie", CookieUtils.isCookieSecure());
        result.put("forgotPassword", String.valueOf(selfServiceInfo.isForgottenPasswordEnabled()));
        result.put("forgotUsername", String.valueOf(selfServiceInfo.isForgottenUsernameEnabled()));
        result.put("kbaEnabled", String.valueOf(selfServiceInfo.isKbaEnabled()));
        result.put("selfRegistration", String.valueOf(selfServiceInfo.isUserRegistrationEnabled()));
        result.put("lang", getJsLocale(localeContext.getLocale()));
        result.put("successfulUserRegistrationDestination", "default");
        result.put("socialImplementations", getSocialAuthnImplementations(realm));
        result.put("referralsEnabled", Boolean.FALSE.toString());
        result.put("zeroPageLogin", AuthUtils.getZeroPageLoginConfig(realm));
        result.put("realm", realm);
        result.put("xuiUserSessionValidationEnabled", SystemProperties.getAsBoolean(Constants.XUI_USER_SESSION_VALIDATION_ENABLED, true));
        if (debug.messageEnabled()) {
            debug.message("ServerInfoResource.getAllServerInfo ::" + " Added resource to response: " + ALL_SERVER_INFO);
        }
        resource = newResourceResponse(ALL_SERVER_INFO, Integer.toString(result.asMap().hashCode()), result);
        return newResultPromise(resource);
    } catch (Exception e) {
        debug.error("ServerInfoResource.getAllServerInfo : Cannot retrieve all server info domains.", e);
        return new NotFoundException(e.getMessage()).asPromise();
    }
}
Also used : JsonValue(org.forgerock.json.JsonValue) HttpContext(org.forgerock.json.resource.http.HttpContext) NotFoundException(org.forgerock.json.resource.NotFoundException) SSOException(com.iplanet.sso.SSOException) NotFoundException(org.forgerock.json.resource.NotFoundException) NotSupportedException(org.forgerock.json.resource.NotSupportedException) SMSException(com.sun.identity.sm.SMSException) ResourceException(org.forgerock.json.resource.ResourceException) Responses.newResourceResponse(org.forgerock.json.resource.Responses.newResourceResponse) ResourceResponse(org.forgerock.json.resource.ResourceResponse) RestSecurity(org.forgerock.openam.services.RestSecurity) ISLocaleContext(com.sun.identity.common.ISLocaleContext) HashSet(java.util.HashSet)

Example 14 with HttpContext

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

the class UmaUrisFactory method get.

/**
     * <p>Gets the instance of the UmaProviderSettings.</p>
     *
     * <p>Cache each provider settings on the realm it was created for.</p>
     *
     * @param context The context instance from which the base URL can be deduced.
     * @param realmInfo The realm.
     * @return The OAuth2ProviderSettings instance.
     */
public UmaUris get(Context context, RealmInfo realmInfo) throws NotFoundException, ServerException {
    String absoluteRealm = realmInfo.getAbsoluteRealm();
    HttpContext httpContext = context.asContext(HttpContext.class);
    String baseUrl;
    try {
        baseUrl = baseURLProviderFactory.get(absoluteRealm).getRealmURL(httpContext, "/uma", absoluteRealm);
    } catch (InvalidBaseUrlException e) {
        throw new ServerException("Configuration error");
    }
    UmaUris uris = urisMap.get(baseUrl);
    if (uris == null) {
        OAuth2Uris oAuth2Uris = oAuth2UriFactory.get(context, realmInfo);
        uris = get(absoluteRealm, oAuth2Uris, baseUrl);
    }
    return uris;
}
Also used : ServerException(org.forgerock.oauth2.core.exceptions.ServerException) OAuth2Uris(org.forgerock.oauth2.core.OAuth2Uris) HttpContext(org.forgerock.json.resource.http.HttpContext) InvalidBaseUrlException(org.forgerock.openam.services.baseurl.InvalidBaseUrlException)

Example 15 with HttpContext

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

the class OAuth2UserApplications method getLocale.

private Locale getLocale(Context context) {
    ISLocaleContext locale = new ISLocaleContext();
    HttpContext httpContext = context.asContext(HttpContext.class);
    locale.setLocale(httpContext);
    return locale.getLocale();
}
Also used : HttpContext(org.forgerock.json.resource.http.HttpContext) ISLocaleContext(com.sun.identity.common.ISLocaleContext)

Aggregations

HttpContext (org.forgerock.json.resource.http.HttpContext)26 Test (org.testng.annotations.Test)8 SSOException (com.iplanet.sso.SSOException)7 List (java.util.List)6 ResourceException (org.forgerock.json.resource.ResourceException)6 SMSException (com.sun.identity.sm.SMSException)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 HashMap (java.util.HashMap)5 JsonValue (org.forgerock.json.JsonValue)5 NotFoundException (org.forgerock.json.resource.NotFoundException)5 NotSupportedException (org.forgerock.json.resource.NotSupportedException)5 SSOToken (com.iplanet.sso.SSOToken)4 ISLocaleContext (com.sun.identity.common.ISLocaleContext)4 IdRepoException (com.sun.identity.idm.IdRepoException)4 ServiceNotFoundException (com.sun.identity.sm.ServiceNotFoundException)4 MessagingException (javax.mail.MessagingException)4 Subject (javax.security.auth.Subject)4 BadRequestException (org.forgerock.json.resource.BadRequestException)4 ConflictException (org.forgerock.json.resource.ConflictException)4 ForbiddenException (org.forgerock.json.resource.ForbiddenException)4