Skip to content

Commit

Permalink
adding defaultHostname attribut. small improvements for email notific…
Browse files Browse the repository at this point in the history
…ations (registration)
  • Loading branch information
katkav committed Oct 27, 2016
1 parent a4d07c0 commit b3bd7ab
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 93 deletions.
Expand Up @@ -4,24 +4,20 @@
import java.util.List;

import org.apache.commons.lang.Validate;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.string.StringValue;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;

import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils;
import com.evolveum.midpoint.model.api.AuthenticationEvaluator;
import com.evolveum.midpoint.prism.delta.ContainerDelta;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.delta.PropertyDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.schema.constants.ObjectTypes;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
Expand All @@ -30,22 +26,17 @@
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.security.api.ConnectionEnvironment;
import com.evolveum.midpoint.security.api.MidPointPrincipal;
import com.evolveum.midpoint.security.api.SecurityUtil;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.Producer;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.web.application.PageDescriptor;
import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour;
import com.evolveum.midpoint.web.util.MidPointPageParametersEncoder;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.CredentialsType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.NonceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;

import net.sf.jasperreports.components.map.ItemData;

//CONFIRMATION_LINK = "http://localhost:8080/midpoint/confirm/registration/";
@PageDescriptor(url = "/confirm", encoder = MidPointPageParametersEncoder.class)
public class PageRegistrationConfirmation extends PageRegistrationBase {
Expand Down Expand Up @@ -83,26 +74,40 @@ private void init(final PageParameters pageParameters) {
Validate.notEmpty(userNameValue.toString());
StringValue tokenValue = params.get(SchemaConstants.REGISTRATION_TOKEN);
Validate.notEmpty(tokenValue.toString());
ConnectionEnvironment connEnv = new ConnectionEnvironment();
connEnv.setChannel(SchemaConstants.CHANNEL_GUI_SELF_REGISTRATION_URI);


OperationResult result = new OperationResult(OPERATION_FINISH_REGISTRATION);
UsernamePasswordAuthenticationToken token = null;
UsernamePasswordAuthenticationToken token = authenticateUser(userNameValue.toString(), tokenValue.toString(), result);
if (token == null) {
initLayout(result);
return;
}

final MidPointPrincipal principal = (MidPointPrincipal) token.getPrincipal();
final NonceType nonceClone = principal.getUser().getCredentials().getNonce().clone();

result = removeNonce(principal.getOid(), nonceClone);
assignAdditionalRoleIfPresent(principal.getOid(), token, nonceClone, result);

initLayout(result);
}

private UsernamePasswordAuthenticationToken authenticateUser(String username, String nonce, OperationResult result){
ConnectionEnvironment connEnv = new ConnectionEnvironment();
connEnv.setChannel(SchemaConstants.CHANNEL_GUI_SELF_REGISTRATION_URI);
try {
token = getAuthenticationEvaluator().authenticateUserNonce(connEnv, userNameValue.toString(),
tokenValue.toString(), getSelfRegistrationConfiguration().getNoncePolicy());
return getAuthenticationEvaluator().authenticateUserNonce(connEnv, username,
nonce, getSelfRegistrationConfiguration().getNoncePolicy());
} catch (AuthenticationException ex) {
getSession()
.error(createStringResource("PageRegistrationConfirmation.bad.credentials").getString());
result.recordFatalError("Failed to validate user");
initLayout(result);
return;
return null;
}

final MidPointPrincipal principal = (MidPointPrincipal) token.getPrincipal();
final NonceType nonceClone = principal.getUser().getCredentials().getNonce().clone();

result = runPrivileged(new Producer<OperationResult>() {
}

private OperationResult removeNonce(final String userOid, final NonceType nonce){
return runPrivileged(new Producer<OperationResult>() {

@Override
public OperationResult run() {
Expand All @@ -111,7 +116,7 @@ public OperationResult run() {

ObjectDelta<UserType> userAssignmentsDelta;
try {
userAssignmentsDelta = ObjectDelta.createModificationDeleteContainer(UserType.class, principal.getOid(), new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_NONCE), getPrismContext(), nonceClone);
userAssignmentsDelta = ObjectDelta.createModificationDeleteContainer(UserType.class, userOid, new ItemPath(UserType.F_CREDENTIALS, CredentialsType.F_NONCE), getPrismContext(), nonce);
} catch (SchemaException e) {
result.recordFatalError("Could not create delta");
return result;
Expand All @@ -121,48 +126,12 @@ public OperationResult run() {
return result;
}
});

// if (result.getS)

// final String oid = principal.getOid();
// result = runPrivileged(new Producer<OperationResult>() {
//
// @Override
// public OperationResult run() {
// OperationResult result = new OperationResult("assignDefaultRoles");
// Task task = createAnonymousTask("assignDefaultRoles");
// List<ContainerDelta<AssignmentType>> assignmentDelta = new ArrayList<ContainerDelta<AssignmentType>>();
// for (ObjectReferenceType defaultRole : getSelfRegistrationConfiguration().getDefaultRoles()) {
// AssignmentType assignment = new AssignmentType();
// assignment.setTargetRef(defaultRole);
// try {
// assignmentDelta.add(ContainerDelta.createModificationAdd(UserType.F_ASSIGNMENT, UserType.class, getPrismContext(), assignment));
// getPrismContext().adopt(assignment);
// } catch (SchemaException e) {
// //nothing to do
// }
//
// }
// ObjectDelta<UserType> userAssignmentsDelta = ObjectDelta.createModifyDelta(oid, assignmentDelta, UserType.class, getPrismContext());
// WebModelServiceUtils.save(userAssignmentsDelta, result, task, PageRegistrationConfirmation.this);
// result.computeStatusIfUnknown();
// return result;
// }
// });

// token = getAuthenticationEvaluator().authenticateUserNonce(connEnv, userNameValue.toString(),
// tokenValue.toString(), getSelfRegistrationConfiguration().getNoncePolicy());
// principal = (MidPointPrincipal) token.getPrincipal();
//
List<ItemDelta> userDeltas = new ArrayList<>();
// userDeltas.add(PropertyDelta.createModificationReplaceProperty(
// SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS,
// principal.getUser().asPrismObject().getDefinition(), (ActivationStatusType) null));
}

private void assignAdditionalRoleIfPresent(String userOid, UsernamePasswordAuthenticationToken token, NonceType nonceType, OperationResult result){
SecurityContextHolder.getContext().setAuthentication(token);

if (nonceClone.getResetType() != null) {
List<ItemDelta> userDeltas = new ArrayList<>();
if (nonceType.getResetType() != null) {

Task task = createSimpleTask(OPERATION_FINISH_REGISTRATION);

Expand All @@ -171,17 +140,16 @@ public OperationResult run() {
try {
AssignmentType assignment = new AssignmentType();
assignment.setTargetRef(
ObjectTypeUtil.createObjectRef(nonceClone.getResetType(), ObjectTypes.ABSTRACT_ROLE));
ObjectTypeUtil.createObjectRef(nonceType.getResetType(), ObjectTypes.ABSTRACT_ROLE));
getPrismContext().adopt(assignment);
userDeltas.add((ItemDelta) ContainerDelta.createModificationAdd(UserType.F_ASSIGNMENT,
UserType.class, getPrismContext(), assignment));

assignRoleDelta = ObjectDelta.createModifyDelta(principal.getOid(), userDeltas,
assignRoleDelta = ObjectDelta.createModifyDelta(userOid, userDeltas,
UserType.class, getPrismContext());
assignRoleDelta.setPrismContext(getPrismContext());
} catch (SchemaException e) {
result.recordFatalError("Could not create delta");
initLayout(result);
return;

}
Expand All @@ -191,13 +159,8 @@ public OperationResult run() {

}
SecurityContextHolder.getContext().setAuthentication(null);




initLayout(result);

}

private void initLayout(final OperationResult result) {

WebMarkupContainer successPanel = new WebMarkupContainer(ID_SUCCESS_PANEL);
Expand Down
Expand Up @@ -109,6 +109,16 @@ public static SystemConfigurationType getSystemConfiguration(RepositoryService r
}
}

public SystemConfigurationType getSystemConfiguration(OperationResult result) {
try {
return cacheRepositoryService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(),
null, result).asObjectable();
} catch (ObjectNotFoundException|SchemaException e) {
LoggingUtils.logException(LOGGER, "Notification(s) couldn't be processed, because the system configuration couldn't be retrieved", e);
return null;
}
}

public static SecurityPolicyType getSecurityPolicyConfiguration(ObjectReferenceType securityPolicyRef, RepositoryService repositoryService, OperationResult result) {
try {
if (securityPolicyRef == null) {
Expand Down
Expand Up @@ -16,39 +16,28 @@

package com.evolveum.midpoint.notifications.impl.notifiers;

import com.evolveum.midpoint.common.crypto.CryptoUtil;
import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.evolveum.midpoint.model.api.expr.MidpointFunctions;
import com.evolveum.midpoint.model.common.expression.ExpressionVariables;
import com.evolveum.midpoint.notifications.api.events.Event;
import com.evolveum.midpoint.notifications.api.events.ModelEvent;
import com.evolveum.midpoint.notifications.impl.NotificationFuctionsImpl;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.crypto.EncryptionException;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.GeneralNotifierType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.RegistrationConfirmationMethodType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserPasswordNotifierType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserRegistrationNotifierType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;

import org.apache.commons.codec.digest.Crypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.w3c.tools.codec.Base64Decoder;
import org.w3c.tools.codec.Base64Encoder;

import javax.annotation.PostConstruct;

import java.util.List;

/**
* @author mederly
Expand All @@ -65,7 +54,7 @@ public class UserRegistrationNotifier extends GeneralNotifier {
private NotificationFuctionsImpl notificationsUtil;


private static String CONFIRMATION_LINK = "http://localhost:8080/midpoint/confirm/";
private static String CONFIRMATION_LINK = "/confirm/";

@PostConstruct
public void init() {
Expand Down Expand Up @@ -130,7 +119,7 @@ protected String getBody(Event event, GeneralNotifierType generalNotifierType, S
messageBuilder.append(userType.getGivenName()).append(",\n")
.append("your account was successfully created. To activate your account click on the following confiramtion link. ")
.append("\n")
.append(createConfirmationLink(userType, generalNotifierType))
.append(createConfirmationLink(userType, generalNotifierType, result))
.append("\n\n")
.append("After your account is activated, use following credentials to log in: \n")
.append("username: ")
Expand All @@ -141,7 +130,7 @@ protected String getBody(Event event, GeneralNotifierType generalNotifierType, S
return messageBuilder.toString();
}

private String createConfirmationLink(UserType userType, GeneralNotifierType generalNotifierType){
private String createConfirmationLink(UserType userType, GeneralNotifierType generalNotifierType, OperationResult result){


UserRegistrationNotifierType userRegistrationNotifier = (UserRegistrationNotifierType) generalNotifierType;
Expand All @@ -154,7 +143,13 @@ private String createConfirmationLink(UserType userType, GeneralNotifierType gen

switch (confirmationMethod) {
case LINK:
StringBuilder confirmLinkBuilder = new StringBuilder(CONFIRMATION_LINK);
SystemConfigurationType systemConfiguration = notificationsUtil.getSystemConfiguration(result);
if (systemConfiguration == null) {
LOGGER.trace("No system configuration defined. Skipping link generation.");
return null;
}
String defaultHostname = systemConfiguration.getDefaultHostname();
StringBuilder confirmLinkBuilder = new StringBuilder(defaultHostname + CONFIRMATION_LINK);
confirmLinkBuilder.append(SchemaConstants.REGISTRATION_ID+"/").append(userType.getName().getOrig())
.append("/"+SchemaConstants.REGISTRATION_TOKEN+"/").append(getNonce(userType));
return confirmLinkBuilder.toString();
Expand Down Expand Up @@ -202,7 +197,7 @@ protected String getBodyFromExpression(Event event, GeneralNotifierType generalN

String body = super.getBodyFromExpression(event, generalNotifierType, variables, task, result);
if (body != null ) {
return body + "\n" + createConfirmationLink(userType, generalNotifierType);
return body + "\n" + createConfirmationLink(userType, generalNotifierType, result);
}

return body;
Expand Down

0 comments on commit b3bd7ab

Please sign in to comment.