use of com.evolveum.midpoint.xml.ns._public.common.common_3.MailConfigurationType in project midpoint by Evolveum.
the class PageSecurityQuestions method resetPassword.
private void resetPassword(UserType user, AjaxRequestTarget target) {
Task task = createAnonymousTask(OPERATION_RESET_PASSWORD);
OperationResult result = task.getResult();
LOGGER.debug("Resetting password for {}", user);
ProtectedStringType password = new ProtectedStringType();
Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(GetOperationOptions.createResolve(), SystemConfigurationType.F_DEFAULT_USER_TEMPLATE, SystemConfigurationType.F_GLOBAL_PASSWORD_POLICY);
PrismObject<SystemConfigurationType> systemConfig = null;
String newPassword = "";
PageBase page = (PageBase) getPage();
ModelService modelService = page.getModelService();
try {
systemConfig = modelService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), options, task, result);
LOGGER.trace("system config {}", systemConfig);
if (systemConfig.asObjectable().getNotificationConfiguration() != null) {
// Security policy with the minumum number of chars
if (systemConfig.asObjectable().getGlobalPasswordPolicyRef() != null) {
PrismObject<ValuePolicyType> valPolicy = modelService.getObject(ValuePolicyType.class, systemConfig.asObjectable().getGlobalPasswordPolicyRef().getOid(), options, task, result);
LOGGER.trace("password policy {}", valPolicy);
newPassword = getModelInteractionService().generateValue(valPolicy.asObjectable().getStringPolicy(), valPolicy.asObjectable().getStringPolicy().getLimitations().getMinLength(), false, user.asPrismObject(), "security questions password generation", task, result);
} else {
// TODO What if there is no policy? What should be done to
// provide a new automatic password
warn(getString("pageSecurityQuestions.message.noPolicySet"));
target.add(getFeedbackPanel());
return;
}
} else {
// TODO localization
getSession().error(getString("pageSecurityQuestions.message.notificationsNotSet"));
LOGGER.trace("Notificatons not set, returning to login page");
throw new RestartResponseException(PageLogin.class);
}
} catch (ObjectNotFoundException | ExpressionEvaluationException e1) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't reset password", e1);
} catch (SchemaException e1) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't reset password", e1);
e1.printStackTrace();
} catch (SecurityViolationException e1) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't reset password", e1);
} catch (CommunicationException e1) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't reset password", e1);
} catch (ConfigurationException e1) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't reset password", e1);
}
password.setClearValue(newPassword);
WebComponentUtil.encryptProtectedString(password, true, getMidpointApplication());
final ItemPath valuePath = new ItemPath(SchemaConstantsGenerated.C_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE);
SchemaRegistry registry = getPrismContext().getSchemaRegistry();
Collection<ObjectDelta<? extends ObjectType>> deltas = new ArrayList<ObjectDelta<? extends ObjectType>>();
PrismObjectDefinition objDef = registry.findObjectDefinitionByCompileTimeClass(UserType.class);
PropertyDelta delta = PropertyDelta.createModificationReplaceProperty(valuePath, objDef, password);
Class<? extends ObjectType> type = UserType.class;
deltas.add(ObjectDelta.createModifyDelta(user.getOid(), delta, type, getPrismContext()));
try {
modelService.executeChanges(deltas, null, task, result);
OperationResult parentResult = new OperationResult(OPERATION_LOAD_RESET_PASSWORD_POLICY);
try {
if (getModelInteractionService().getCredentialsPolicy(null, null, parentResult).getSecurityQuestions().getResetMethod().getResetType().equals(CredentialsResetTypeType.SECURITY_QUESTIONS)) {
getSession().setAttribute("pwdReset", newPassword);
setResponsePage(PageShowPassword.class);
} else if (getModelInteractionService().getCredentialsPolicy(null, null, parentResult).getSecurityQuestions().getResetMethod().getResetType().equals(CredentialsResetTypeType.SECURITY_QUESTIONS_EMAIL)) {
if (systemConfig.asObjectable().getNotificationConfiguration() != null && systemConfig.asObjectable().getNotificationConfiguration().getMail() != null) {
MailConfigurationType mailConfig = systemConfig.asObjectable().getNotificationConfiguration().getMail();
if (mailConfig.getServer() != null) {
List serverList = mailConfig.getServer();
if (serverList.size() > 0) {
MailServerConfigurationType mailServerType = mailConfig.getServer().get(0);
sendMailToUser(mailServerType.getUsername(), getMidpointApplication().getProtector().decryptString(mailServerType.getPassword()), newPassword, mailServerType.getHost(), mailServerType.getPort().toString(), mailConfig.getDefaultFrom(), user.getEmailAddress());
} else {
getSession().error(getString("pageLogin.message.ForgetPasswordSettingsWrong"));
throw new RestartResponseException(PageLogin.class);
}
} else {
getSession().error(getString("pageLogin.message.ForgetPasswordSettingsWrong"));
throw new RestartResponseException(PageLogin.class);
}
} else {
// System.out.println("ifff4");
getSession().error(getString("pageLogin.message.ForgetPasswordSettingsWrong"));
throw new RestartResponseException(PageLogin.class);
}
}
} catch (ObjectNotFoundException | SchemaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO ASAP a message should be shown as the result of the process
// MailMessage mailMessage=new MailMessage(, port);
// mailTransport.send(mailMessage, transportName, task,
// parentResult);
} catch (ObjectAlreadyExistsException | ObjectNotFoundException | SchemaException | ExpressionEvaluationException | CommunicationException | ConfigurationException | PolicyViolationException | SecurityViolationException | EncryptionException e) {
LoggingUtils.logUnexpectedException(LOGGER, "reset password exception", e);
}
}
use of com.evolveum.midpoint.xml.ns._public.common.common_3.MailConfigurationType in project midpoint by Evolveum.
the class NotificationConfigurationDto method getNewObject.
public NotificationConfigurationType getNewObject(SystemConfigurationType systemConfig) {
NotificationConfigurationType notificationConfig = (systemConfig.getNotificationConfiguration() != null) ? systemConfig.getNotificationConfiguration() : new NotificationConfigurationType();
MailConfigurationType mailConfig = (notificationConfig.getMail() != null) ? notificationConfig.getMail() : new MailConfigurationType();
mailConfig.setDebug(isDebug());
mailConfig.setDefaultFrom(getDefaultFrom());
mailConfig.setRedirectToFile(getRedirectToFile());
mailConfig.getServer().clear();
for (MailServerConfigurationTypeDto serverDto : getServers()) {
MailServerConfigurationType newConfig = new MailServerConfigurationType();
newConfig.setHost(serverDto.getHost());
newConfig.setPort(serverDto.getPort());
newConfig.setUsername(serverDto.getUsername());
newConfig.setTransportSecurity(serverDto.getMailTransportSecurityType());
if (serverDto.getPassword() != null && StringUtils.isNotEmpty(serverDto.getPassword())) {
ProtectedStringType pass = new ProtectedStringType();
pass.setClearValue(serverDto.getPassword());
newConfig.setPassword(pass);
} else {
newConfig.setPassword(serverDto.getOldConfig().getPassword());
}
mailConfig.getServer().add(newConfig);
}
notificationConfig.setMail(mailConfig);
return notificationConfig;
}
use of com.evolveum.midpoint.xml.ns._public.common.common_3.MailConfigurationType in project midpoint by Evolveum.
the class MailTransport method send.
@Override
public void send(Message mailMessage, String transportName, Event event, Task task, OperationResult parentResult) {
OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
result.addCollectionOfSerializablesAsParam("mailMessage recipient(s)", mailMessage.getTo());
result.addParam("mailMessage subject", mailMessage.getSubject());
SystemConfigurationType systemConfiguration = NotificationFunctionsImpl.getSystemConfiguration(cacheRepositoryService, new OperationResult("dummy"));
if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null || systemConfiguration.getNotificationConfiguration().getMail() == null) {
String msg = "No notifications are configured. Mail notification to " + mailMessage.getTo() + " will not be sent.";
LOGGER.warn(msg);
result.recordWarning(msg);
return;
}
// if (mailConfigurationType == null) {
MailConfigurationType mailConfigurationType = systemConfiguration.getNotificationConfiguration().getMail();
// }
String redirectToFile = mailConfigurationType.getRedirectToFile();
if (redirectToFile != null) {
try {
TransportUtil.appendToFile(redirectToFile, formatToFile(mailMessage));
result.recordSuccess();
} catch (IOException e) {
LoggingUtils.logException(LOGGER, "Couldn't write to mail redirect file {}", e, redirectToFile);
result.recordPartialError("Couldn't write to mail redirect file " + redirectToFile, e);
}
return;
}
if (mailConfigurationType.getServer().isEmpty()) {
String msg = "Mail server(s) are not defined, mail notification to " + mailMessage.getTo() + " will not be sent.";
LOGGER.warn(msg);
result.recordWarning(msg);
return;
}
long start = System.currentTimeMillis();
String defaultFrom = mailConfigurationType.getDefaultFrom() != null ? mailConfigurationType.getDefaultFrom() : "nobody@nowhere.org";
for (MailServerConfigurationType mailServerConfigurationType : mailConfigurationType.getServer()) {
OperationResult resultForServer = result.createSubresult(DOT_CLASS + "send.forServer");
final String host = mailServerConfigurationType.getHost();
resultForServer.addContext("server", host);
resultForServer.addContext("port", mailServerConfigurationType.getPort());
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
if (mailServerConfigurationType.getPort() != null) {
properties.setProperty("mail.smtp.port", String.valueOf(mailServerConfigurationType.getPort()));
}
MailTransportSecurityType mailTransportSecurityType = mailServerConfigurationType.getTransportSecurity();
boolean sslEnabled = false, starttlsEnable = false, starttlsRequired = false;
if (mailTransportSecurityType != null) {
switch(mailTransportSecurityType) {
case STARTTLS_ENABLED:
starttlsEnable = true;
break;
case STARTTLS_REQUIRED:
starttlsEnable = true;
starttlsRequired = true;
break;
case SSL:
sslEnabled = true;
break;
}
}
properties.put("mail.smtp.ssl.enable", "" + sslEnabled);
properties.put("mail.smtp.starttls.enable", "" + starttlsEnable);
properties.put("mail.smtp.starttls.required", "" + starttlsRequired);
if (Boolean.TRUE.equals(mailConfigurationType.isDebug())) {
properties.put("mail.debug", "true");
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Using mail properties: ");
for (Object key : properties.keySet()) {
if (key instanceof String && ((String) key).startsWith("mail.")) {
LOGGER.debug(" - " + key + " = " + properties.get(key));
}
}
}
task.recordState("Sending notification mail via " + host);
Session session = Session.getInstance(properties);
try {
MimeMessage mimeMessage = new MimeMessage(session);
String from = mailMessage.getFrom() != null ? mailMessage.getFrom() : defaultFrom;
mimeMessage.setFrom(new InternetAddress(from));
for (String recipient : mailMessage.getTo()) {
mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient));
}
for (String recipientCc : mailMessage.getCc()) {
mimeMessage.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(recipientCc));
}
for (String recipientBcc : mailMessage.getBcc()) {
mimeMessage.addRecipient(javax.mail.Message.RecipientType.BCC, new InternetAddress(recipientBcc));
}
mimeMessage.setSubject(mailMessage.getSubject(), "utf-8");
String contentType = mailMessage.getContentType();
if (StringUtils.isEmpty(contentType)) {
contentType = "text/plain; charset=UTF-8";
}
mimeMessage.setContent(mailMessage.getBody(), contentType);
javax.mail.Transport t = session.getTransport("smtp");
if (StringUtils.isNotEmpty(mailServerConfigurationType.getUsername())) {
ProtectedStringType passwordProtected = mailServerConfigurationType.getPassword();
String password = null;
if (passwordProtected != null) {
try {
password = protector.decryptString(passwordProtected);
} catch (EncryptionException e) {
String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", because the plaintext password value couldn't be obtained. Trying another mail server, if there is any.";
LoggingUtils.logException(LOGGER, msg, e);
resultForServer.recordFatalError(msg, e);
continue;
}
}
t.connect(mailServerConfigurationType.getUsername(), password);
} else {
t.connect();
}
t.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
LOGGER.info("Message sent successfully to " + mailMessage.getTo() + " via server " + host + ".");
resultForServer.recordSuccess();
result.recordSuccess();
long duration = System.currentTimeMillis() - start;
task.recordState("Notification mail sent successfully via " + host + ", in " + duration + " ms overall.");
task.recordNotificationOperation(NAME, true, duration);
return;
} catch (MessagingException e) {
String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", trying another mail server, if there is any";
LoggingUtils.logException(LOGGER, msg, e);
resultForServer.recordFatalError(msg, e);
task.recordState("Error sending notification mail via " + host);
}
}
LOGGER.warn("No more mail servers to try, mail notification to " + mailMessage.getTo() + " will not be sent.");
result.recordWarning("Mail notification to " + mailMessage.getTo() + " could not be sent.");
task.recordNotificationOperation(NAME, false, System.currentTimeMillis() - start);
}
Aggregations