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);
}
}
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();
}
}
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();
}
}
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();
}
}
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);
}
}
Aggregations