Search in sources :

Example 11 with JsonValue

use of org.forgerock.json.JsonValue in project OpenAM by OpenRock.

the class DefaultAuditServiceProxy method isAuditEnabled.

private boolean isAuditEnabled(CreateRequest createRequest) {
    JsonValue auditEventValue = createRequest.getContent();
    JsonValue eventNameJson = auditEventValue.get("eventName");
    if (eventNameJson == null) {
        return true;
    }
    return !auditServiceConfiguration.isBlacklisted(eventNameJson.asString());
}
Also used : JsonValue(org.forgerock.json.JsonValue)

Example 12 with JsonValue

use of org.forgerock.json.JsonValue in project OpenAM by OpenRock.

the class Auditor method auditAccessFailure.

/**
     * Creates an audit event that captures details of an unsuccessfully completed HTTP call.
     *
     * @return An AuditEvent.
     */
public AuditEvent auditAccessFailure() {
    long endTime = timeService.now();
    long elapsedTime = endTime - startTime;
    String statusCode = Integer.toString(response.getStatusCode());
    JsonValue responseDetail = json(object(field(ACCESS_RESPONSE_DETAIL_REASON, response.getMessage())));
    return accessEvent().forHttpServletRequest(request).timestamp(endTime).transactionId(AuditRequestContext.getTransactionIdValue()).eventName(AM_ACCESS_OUTCOME).component(component).responseWithDetail(FAILED, statusCode, elapsedTime, MILLISECONDS, responseDetail).toEvent();
}
Also used : JsonValue(org.forgerock.json.JsonValue)

Example 13 with JsonValue

use of org.forgerock.json.JsonValue in project OpenAM by OpenRock.

the class AbstractHttpAccessAuditFilter method auditAccessFailure.

private void auditAccessFailure(Request request, Context context, Response response) {
    String realm = getRealm(context);
    if (auditEventPublisher.isAuditing(realm, AuditConstants.ACCESS_TOPIC, EventName.AM_ACCESS_OUTCOME)) {
        long endTime = System.currentTimeMillis();
        String responseCode = Integer.toString(response.getStatus().getCode());
        long elapsedTime = endTime - context.asContext(RequestAuditContext.class).getRequestReceivedTime();
        JsonValue responseDetail = json(object(field(ACCESS_RESPONSE_DETAIL_REASON, response.getStatus().getReasonPhrase())));
        AMAccessAuditEventBuilder builder = auditEventFactory.accessEvent(realm).timestamp(endTime).transactionId(AuditRequestContext.getTransactionIdValue()).eventName(EventName.AM_ACCESS_OUTCOME).component(component).userId(getUserIdForAccessOutcome(response)).trackingIds(getTrackingIdsForAccessOutcome(response)).responseWithDetail(FAILED, responseCode, elapsedTime, MILLISECONDS, responseDetail).forRequest(request, context);
        auditEventPublisher.tryPublish(AuditConstants.ACCESS_TOPIC, builder.toEvent());
    }
}
Also used : JsonValue(org.forgerock.json.JsonValue)

Example 14 with JsonValue

use of org.forgerock.json.JsonValue 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 15 with JsonValue

use of org.forgerock.json.JsonValue 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)

Aggregations

JsonValue (org.forgerock.json.JsonValue)575 Test (org.testng.annotations.Test)333 ResourceException (org.forgerock.json.resource.ResourceException)144 ResourceResponse (org.forgerock.json.resource.ResourceResponse)123 RealmContext (org.forgerock.openam.rest.RealmContext)70 Context (org.forgerock.services.context.Context)63 HashSet (java.util.HashSet)56 SSOException (com.iplanet.sso.SSOException)54 ArrayList (java.util.ArrayList)51 BadRequestException (org.forgerock.json.resource.BadRequestException)47 Privilege (com.sun.identity.entitlement.Privilege)46 InternalServerErrorException (org.forgerock.json.resource.InternalServerErrorException)46 SSOToken (com.iplanet.sso.SSOToken)43 SMSException (com.sun.identity.sm.SMSException)42 HashMap (java.util.HashMap)42 NotFoundException (org.forgerock.json.resource.NotFoundException)41 SSOTokenContext (org.forgerock.openam.rest.resource.SSOTokenContext)41 CreateRequest (org.forgerock.json.resource.CreateRequest)40 OpenSSOPrivilege (com.sun.identity.entitlement.opensso.OpenSSOPrivilege)39 Subject (javax.security.auth.Subject)32