Search in sources :

Example 1 with ResourceException

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

the class IdentityResourceV2 method sendNotification.

/**
     * Sends email notification to end user
     * @param to Resource receiving notification
     * @param subject Notification subject
     * @param message Notification Message
     * @param confirmationLink Confirmation Link to be sent
     * @throws Exception when message cannot be sent
     */
private void sendNotification(String to, String subject, String message, String realm, String confirmationLink) throws ResourceException {
    try {
        mailmgr = new ServiceConfigManager(RestUtils.getToken(), MailServerImpl.SERVICE_NAME, MailServerImpl.SERVICE_VERSION);
        mailscm = mailmgr.getOrganizationConfig(realm, null);
        mailattrs = mailscm.getAttributes();
    } catch (SMSException smse) {
        if (debug.errorEnabled()) {
            debug.error("{} :: Cannot create service {}", SEND_NOTIF_TAG, MailServerImpl.SERVICE_NAME, smse);
        }
        throw new InternalServerErrorException("Cannot create the service: " + MailServerImpl.SERVICE_NAME, smse);
    } catch (SSOException ssoe) {
        if (debug.errorEnabled()) {
            debug.error("{} :: Invalid SSOToken ", SEND_NOTIF_TAG, ssoe);
        }
        throw new InternalServerErrorException("Cannot create the service: " + MailServerImpl.SERVICE_NAME, ssoe);
    }
    if (mailattrs == null || mailattrs.isEmpty()) {
        if (debug.errorEnabled()) {
            debug.error("{} :: no attrs set {}", SEND_NOTIF_TAG, mailattrs);
        }
        throw new NotFoundException("No service Config Manager found for realm " + realm);
    }
    // Get MailServer Implementation class
    String attr = mailattrs.get(MAIL_IMPL_CLASS).iterator().next();
    MailServer mailServer;
    try {
        mailServer = mailServerLoader.load(attr, realm);
    } catch (IllegalStateException e) {
        debug.error("{} :: Failed to load mail server implementation: {}", SEND_NOTIF_TAG, attr, e);
        throw new InternalServerErrorException("Failed to load mail server implementation: " + attr, e);
    }
    try {
        // Check if subject has not  been included
        if (StringUtils.isBlank(subject)) {
            // Use default email service subject
            subject = mailattrs.get(MAIL_SUBJECT).iterator().next();
        }
    } catch (Exception e) {
        if (debug.warningEnabled()) {
            debug.warning("{} no subject found ", SEND_NOTIF_TAG, e);
        }
        subject = "";
    }
    try {
        // Check if Custom Message has been included
        if (StringUtils.isBlank(message)) {
            // Use default email service message
            message = mailattrs.get(MAIL_MESSAGE).iterator().next();
        }
        message = message + System.getProperty("line.separator") + confirmationLink;
    } catch (Exception e) {
        if (debug.warningEnabled()) {
            debug.warning("{} no message found", SEND_NOTIF_TAG, e);
        }
        message = confirmationLink;
    }
    // Send the emails via the implementation class
    try {
        mailServer.sendEmail(to, subject, message);
    } catch (MessagingException e) {
        if (debug.errorEnabled()) {
            debug.error("{} Failed to send mail", SEND_NOTIF_TAG, e);
        }
        throw new InternalServerErrorException("Failed to send mail", e);
    }
}
Also used : MailServer(org.forgerock.openam.services.email.MailServer) SMSException(com.sun.identity.sm.SMSException) MessagingException(javax.mail.MessagingException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) SSOException(com.iplanet.sso.SSOException) ServiceConfigManager(com.sun.identity.sm.ServiceConfigManager) 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)

Example 2 with ResourceException

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

the class IdentityResourceV2 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.isSelfServiceRestEndpointEnabled()) {
            if (debug.warningEnabled()) {
                debug.warning("IdentityResource.createRegistrationEmail(): Self-Registration set to : {}", restSecurity.isSelfServiceRestEndpointEnabled());
            }
            throw new NotSupportedException("Legacy Self Service REST Endpoint is not enabled.");
        }
        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);
        String baseURL = baseURLProviderFactory.get(realm).getRootURL(header);
        // 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.isEmpty(confURL)) {
            confURLBuilder.append(baseURL).append("/json/confirmation/register");
        } else if (confURL.startsWith("/")) {
            confURLBuilder.append(baseURL).append(confURL);
        } 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 be) {
        debug.warning("IdentityResource.createRegistrationEmail: Cannot send email to {}", emailAddress, be);
        return be.asPromise();
    } catch (NotFoundException nfe) {
        debug.warning("IdentityResource.createRegistrationEmail: Cannot send email to {}", emailAddress, nfe);
        return nfe.asPromise();
    } catch (NotSupportedException nse) {
        if (debug.warningEnabled()) {
            debug.warning("IdentityResource.createRegistrationEmail(): Operation not enabled. email={}", emailAddress, 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 : JsonValue(org.forgerock.json.JsonValue) HttpContext(org.forgerock.json.resource.http.HttpContext) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) 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) BadRequestException(org.forgerock.json.resource.BadRequestException) NotSupportedException(org.forgerock.json.resource.NotSupportedException)

Example 3 with ResourceException

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

the class IdentityResourceV2 method actionInstance.

/**
     * {@inheritDoc}
     */
@Override
public Promise<ActionResponse, ResourceException> actionInstance(final Context context, final String resourceId, final ActionRequest request) {
    String action = request.getAction();
    if ("changePassword".equalsIgnoreCase(action)) {
        RealmContext realmContext = context.asContext(RealmContext.class);
        final String realm = realmContext.getResolvedRealm();
        JsonValue value = request.getContent();
        try {
            String userPassword = value.get(USER_PASSWORD).asString();
            if (StringUtils.isBlank(userPassword)) {
                throw new BadRequestException("'" + USER_PASSWORD + "' attribute not set in JSON content.");
            }
            String currentPassword = value.get(CURRENT_PASSWORD).asString();
            if (StringUtils.isBlank(currentPassword)) {
                throw new BadRequestException("'" + CURRENT_PASSWORD + "' attribute not set in JSON content.");
            }
            IdentityRestUtils.changePassword(context, realm, resourceId, currentPassword, userPassword);
            if (debug.messageEnabled()) {
                String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
                debug.message("IdentityResource.actionInstance :: ACTION of change password for " + resourceId + " in realm " + realm + " performed by " + principalName);
            }
            return newResultPromise(newActionResponse(json(object())));
        } catch (ResourceException re) {
            debug.warning("Cannot change password! " + resourceId + ":" + re);
            return re.asPromise();
        }
    } else {
        return new NotSupportedException(action + " not supported for resource instances").asPromise();
    }
}
Also used : RealmContext(org.forgerock.openam.rest.RealmContext) JsonValue(org.forgerock.json.JsonValue) BadRequestException(org.forgerock.json.resource.BadRequestException) ResourceException(org.forgerock.json.resource.ResourceException) NotSupportedException(org.forgerock.json.resource.NotSupportedException)

Example 4 with ResourceException

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

the class IdentityResourceV2 method createInstance.

/**
     * {@inheritDoc}
     */
@Override
public Promise<ResourceResponse, ResourceException> createInstance(final Context context, final CreateRequest request) {
    RealmContext realmContext = context.asContext(RealmContext.class);
    final String realm = realmContext.getResolvedRealm();
    try {
        // anyone can create an account add
        SSOToken admin = getSSOToken(getCookieFromServerContext(context));
        final JsonValue jVal = request.getContent();
        String resourceId = request.getNewResourceId();
        IdentityDetails identity = jsonValueToIdentityDetails(objectType, jVal, realm);
        // check to see if request has included resource ID
        if (resourceId != null) {
            if (identity.getName() != null) {
                if (!resourceId.equalsIgnoreCase(identity.getName())) {
                    ResourceException be = new BadRequestException("id in path does not match id in request body");
                    debug.error("IdentityResource.createInstance() :: Cannot CREATE ", be);
                    return be.asPromise();
                }
            }
            identity.setName(resourceId);
        } else {
            resourceId = identity.getName();
        }
        UserAttributeInfo userAttributeInfo = configHandler.getConfig(realm, UserAttributeInfoBuilder.class);
        enforceWhiteList(context, request.getContent(), objectType, userAttributeInfo.getValidCreationAttributes());
        final String id = resourceId;
        return attemptResourceCreation(realm, admin, identity, resourceId).thenAsync(new AsyncFunction<IdentityDetails, ResourceResponse, ResourceException>() {

            @Override
            public Promise<ResourceResponse, ResourceException> apply(IdentityDetails dtls) {
                if (dtls != null) {
                    String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
                    debug.message("IdentityResource.createInstance :: CREATE of resourceId={} in realm={} " + "performed by principalName={}", id, realm, principalName);
                    ResourceResponse resource = newResourceResponse(id, "0", identityDetailsToJsonValue(dtls));
                    return newResultPromise(resource);
                } else {
                    debug.error("IdentityResource.createInstance() :: Identity not found");
                    return new NotFoundException("Identity not found").asPromise();
                }
            }
        });
    } catch (SSOException e) {
        return new ForbiddenException(e).asPromise();
    } catch (BadRequestException bre) {
        return bre.asPromise();
    }
}
Also used : UserAttributeInfo(org.forgerock.openam.core.rest.UserAttributeInfo) ForbiddenException(org.forgerock.json.resource.ForbiddenException) SSOToken(com.iplanet.sso.SSOToken) RealmContext(org.forgerock.openam.rest.RealmContext) JsonValue(org.forgerock.json.JsonValue) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) SSOException(com.iplanet.sso.SSOException) Promises.newResultPromise(org.forgerock.util.promise.Promises.newResultPromise) Promise(org.forgerock.util.promise.Promise) Responses.newResourceResponse(org.forgerock.json.resource.Responses.newResourceResponse) ResourceResponse(org.forgerock.json.resource.ResourceResponse) IdentityDetails(com.sun.identity.idsvcs.IdentityDetails) BadRequestException(org.forgerock.json.resource.BadRequestException) ResourceException(org.forgerock.json.resource.ResourceException)

Example 5 with ResourceException

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

the class IdentityResourceV1 method sendNotification.

/**
     * Sends email notification to end user
     * @param to Resource receiving notification
     * @param subject Notification subject
     * @param message Notification Message
     * @param confirmationLink Confirmation Link to be sent
     * @throws Exception when message cannot be sent
     */
private void sendNotification(String to, String subject, String message, String realm, String confirmationLink) throws ResourceException {
    try {
        mailmgr = new ServiceConfigManager(RestUtils.getToken(), MailServerImpl.SERVICE_NAME, MailServerImpl.SERVICE_VERSION);
        mailscm = mailmgr.getOrganizationConfig(realm, null);
        mailattrs = mailscm.getAttributes();
    } catch (SMSException smse) {
        if (debug.errorEnabled()) {
            debug.error("{} :: Cannot create service {}", SEND_NOTIF_TAG, MailServerImpl.SERVICE_NAME, smse);
        }
        throw new InternalServerErrorException("Cannot create the service: " + MailServerImpl.SERVICE_NAME, smse);
    } catch (SSOException ssoe) {
        if (debug.errorEnabled()) {
            debug.error("{} :: Invalid SSOToken ", SEND_NOTIF_TAG, ssoe);
        }
        throw new InternalServerErrorException("Cannot create the service: " + MailServerImpl.SERVICE_NAME, ssoe);
    }
    if (mailattrs == null || mailattrs.isEmpty()) {
        if (debug.errorEnabled()) {
            debug.error("{} :: no attrs set {}", SEND_NOTIF_TAG, mailattrs);
        }
        throw new NotFoundException("No service Config Manager found for realm " + realm);
    }
    // Get MailServer Implementation class
    String attr = mailattrs.get(MAIL_IMPL_CLASS).iterator().next();
    MailServer mailServer;
    try {
        mailServer = mailServerLoader.load(attr, realm);
    } catch (IllegalStateException e) {
        debug.error("{} :: Failed to load mail server implementation: {}", SEND_NOTIF_TAG, attr, e);
        throw new InternalServerErrorException("Failed to load mail server implementation: " + attr, e);
    }
    try {
        // Check if subject has not  been included
        if (StringUtils.isBlank(subject)) {
            // Use default email service subject
            subject = mailattrs.get(MAIL_SUBJECT).iterator().next();
        }
    } catch (Exception e) {
        if (debug.warningEnabled()) {
            debug.warning("{} no subject found ", SEND_NOTIF_TAG, e);
        }
        subject = "";
    }
    try {
        // Check if Custom Message has been included
        if (StringUtils.isBlank(message)) {
            // Use default email service message
            message = mailattrs.get(MAIL_MESSAGE).iterator().next();
        }
        message = message + System.getProperty("line.separator") + confirmationLink;
    } catch (Exception e) {
        if (debug.warningEnabled()) {
            debug.warning("{} no message found", SEND_NOTIF_TAG, e);
        }
        message = confirmationLink;
    }
    // Send the emails via the implementation class
    try {
        mailServer.sendEmail(to, subject, message);
    } catch (MessagingException e) {
        if (debug.errorEnabled()) {
            debug.error("{} Failed to send mail", SEND_NOTIF_TAG, e);
        }
        throw new InternalServerErrorException("Failed to send mail", e);
    }
}
Also used : MailServer(org.forgerock.openam.services.email.MailServer) SMSException(com.sun.identity.sm.SMSException) MessagingException(javax.mail.MessagingException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) NotFoundException(org.forgerock.json.resource.NotFoundException) ServiceNotFoundException(com.sun.identity.sm.ServiceNotFoundException) SSOException(com.iplanet.sso.SSOException) ServiceConfigManager(com.sun.identity.sm.ServiceConfigManager) 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)

Aggregations

ResourceException (org.forgerock.json.resource.ResourceException)323 Test (org.testng.annotations.Test)233 ResourceResponse (org.forgerock.json.resource.ResourceResponse)179 JsonValue (org.forgerock.json.JsonValue)145 Context (org.forgerock.services.context.Context)145 RealmContext (org.forgerock.openam.rest.RealmContext)110 SSOTokenContext (org.forgerock.openam.rest.resource.SSOTokenContext)71 Subject (javax.security.auth.Subject)58 ClientContext (org.forgerock.services.context.ClientContext)56 NotFoundException (org.forgerock.json.resource.NotFoundException)47 BadRequestException (org.forgerock.json.resource.BadRequestException)44 QueryResponse (org.forgerock.json.resource.QueryResponse)43 HashSet (java.util.HashSet)42 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)42 CreateRequest (org.forgerock.json.resource.CreateRequest)40 SSOException (com.iplanet.sso.SSOException)38 ActionResponse (org.forgerock.json.resource.ActionResponse)37 SubjectContext (org.forgerock.openam.rest.resource.SubjectContext)37 Matchers.anyString (org.mockito.Matchers.anyString)37 ArrayList (java.util.ArrayList)35