-
Notifications
You must be signed in to change notification settings - Fork 188
/
PageSelfRegistration.java
575 lines (465 loc) · 24.3 KB
/
PageSelfRegistration.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
/*
* Copyright (c) 2010-2018 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.web.page.login;
import com.evolveum.midpoint.gui.api.util.WebComponentUtil;
import com.evolveum.midpoint.prism.delta.DeltaFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.feedback.ContainerFeedbackMessageFilter;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.basic.MultiLineLabel;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.util.string.StringValue;
import com.evolveum.midpoint.gui.api.component.password.PasswordPanel;
import com.evolveum.midpoint.gui.api.model.LoadableModel;
import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils;
import com.evolveum.midpoint.model.api.ModelExecuteOptions;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.PrismObjectDefinition;
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.schema.result.OperationResultStatus;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.Producer;
import com.evolveum.midpoint.util.exception.CommunicationException;
import com.evolveum.midpoint.util.exception.ConfigurationException;
import com.evolveum.midpoint.util.exception.ExpressionEvaluationException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
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.web.application.PageDescriptor;
import com.evolveum.midpoint.web.application.Url;
import com.evolveum.midpoint.web.component.form.Form;
import com.evolveum.midpoint.web.component.input.TextPanel;
import com.evolveum.midpoint.web.component.prism.DynamicFormPanel;
import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour;
import com.evolveum.midpoint.web.page.admin.configuration.component.EmptyOnBlurAjaxFormUpdatingBehaviour;
import com.evolveum.midpoint.web.util.InfoTooltipBehavior;
import com.evolveum.midpoint.xml.ns._public.common.common_3.CredentialsType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.NonceCredentialsPolicyType;
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.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType;
import com.evolveum.prism.xml.ns._public.types_3.PolyStringType;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;
@PageDescriptor(urls = {@Url(mountUrl = "/registration")}, permitAll = true)
public class PageSelfRegistration extends PageAbstractFlow {
private static final long serialVersionUID = 1L;
private static final Trace LOGGER = TraceManager.getTrace(PageSelfRegistration.class);
private static final String DOT_CLASS = PageSelfRegistration.class.getName() + ".";
private static final String OPERATION_LOAD_USER = DOT_CLASS + "loadUser";
// private static final String OPERATION_SAVE_USER = DOT_CLASS + "saveUser";
private static final String ID_WELCOME = "welcome";
private static final String ID_ADDITIONAL_TEXT = "additionalText";
private static final String ID_MAIN_FORM = "mainForm";
private static final String ID_FIRST_NAME = "firstName";
private static final String ID_LAST_NAME = "lastName";
private static final String ID_EMAIL = "email";
private static final String ID_PASSWORD = "password";
private static final String ID_TOOLTIP = "tooltip";
private static final String ID_FEEDBACK = "feedback";
private static final String ID_REGISTRATION_SUBMITED = "registrationInfo";
private static final String ID_STATIC_FORM = "staticForm";
private static final String PARAM_USER_OID = "user";
private IModel<UserType> userModel;
public PageSelfRegistration(PageParameters pageParameters) {
super(pageParameters);
}
private String getOidFromParams(PageParameters pageParameters) {
if (pageParameters == null) {
return null;
}
StringValue oidValue = pageParameters.get(PARAM_USER_OID);
if (oidValue != null) {
return oidValue.toString();
}
return null;
}
@Override
public void initalizeModel() {
final String userOid = getOidFromParams(pageParameters);
userModel = new LoadableModel<UserType>(false) {
private static final long serialVersionUID = 1L;
@Override
protected UserType load() {
return createUserModel(userOid);
}
};
}
private UserType createUserModel(String userOid) {
if (userOid == null) {
LOGGER.trace("Registration process for new user started");
return instantiateUser();
}
PrismObject<UserType> result = runPrivileged(new Producer<PrismObject<UserType>>() {
private static final long serialVersionUID = 1L;
@Override
public PrismObject<UserType> run() {
LOGGER.trace("Loading preregistered user with oid {}.", userOid);
Task task = createAnonymousTask(OPERATION_LOAD_USER);
OperationResult result = new OperationResult(OPERATION_LOAD_USER);
PrismObject<UserType> user = WebModelServiceUtils.loadObject(UserType.class, userOid,
PageSelfRegistration.this, task, result);
result.computeStatus();
return user;
}
});
if (result == null) {
LOGGER.error("Failed to load preregistered user");
getSession().error(
createStringResource("PageSelfRegistration.invalid.registration.link").getString());
throw new RestartResponseException(PageLogin.class);
}
return result.asObjectable();
}
private UserType instantiateUser() {
PrismObjectDefinition<UserType> userDef = getUserDefinition();
PrismObject<UserType> user;
try {
user = userDef.instantiate();
} catch (SchemaException e) {
UserType userType = new UserType();
user = userType.asPrismObject();
}
return user.asObjectable();
}
private PrismObjectDefinition<UserType> getUserDefinition() {
return getPrismContext().getSchemaRegistry().findObjectDefinitionByCompileTimeClass(UserType.class);
}
@Override
protected WebMarkupContainer initStaticLayout() {
// feedback
// final Form<?> mainForm = new Form<>(ID_MAIN_FORM);
WebMarkupContainer staticRegistrationForm = createMarkupContainer(ID_STATIC_FORM, null);
addMultilineLable(ID_WELCOME, createStringResource("PageSelfRegistration.welcome.message"), staticRegistrationForm);
addMultilineLable(ID_ADDITIONAL_TEXT, createStringResource("PageSelfRegistration.additional.message",
WebComponentUtil.getMidpointCustomSystemName(PageSelfRegistration.this, "MidPoint")), staticRegistrationForm);
FeedbackPanel feedback = new FeedbackPanel(ID_FEEDBACK,
new ContainerFeedbackMessageFilter(PageSelfRegistration.this));
feedback.setOutputMarkupId(true);
add(feedback);
TextPanel<String> firstName = new TextPanel<>(ID_FIRST_NAME,
new PropertyModel<String>(getUserModel(), UserType.F_GIVEN_NAME.getLocalPart() + ".orig") {
private static final long serialVersionUID = 1L;
@Override
public void setObject(String object) {
getUserModel().getObject().setGivenName(new PolyStringType(object));
}
});
initInputProperties(feedback, firstName);
staticRegistrationForm.add(firstName);
TextPanel<String> lastName = new TextPanel<>(ID_LAST_NAME,
new PropertyModel<String>(getUserModel(), UserType.F_FAMILY_NAME.getLocalPart() + ".orig") {
private static final long serialVersionUID = 1L;
@Override
public void setObject(String object) {
getUserModel().getObject().setFamilyName(new PolyStringType(object));
}
});
initInputProperties(feedback, lastName);
staticRegistrationForm.add(lastName);
TextPanel<String> email = new TextPanel<>(ID_EMAIL,
new PropertyModel<>(getUserModel(), UserType.F_EMAIL_ADDRESS.getLocalPart()));
initInputProperties(feedback, email);
staticRegistrationForm.add(email);
createPasswordPanel(staticRegistrationForm);
return staticRegistrationForm;
}
private void addMultilineLable(String id, StringResourceModel messageModel, WebMarkupContainer mainForm) {
MultiLineLabel welcome = new MultiLineLabel(id, messageModel);
welcome.setOutputMarkupId(true);
// welcome.add(new VisibleEnableBehaviour() {
// private static final long serialVersionUID = 1L;
//
// @Override
// public boolean isVisible() {
// return !submited;
// }
// });
mainForm.add(welcome);
}
private void initInputProperties(FeedbackPanel feedback, TextPanel<String> input) {
input.getBaseFormComponent().add(new EmptyOnBlurAjaxFormUpdatingBehaviour());
input.getBaseFormComponent().setRequired(true);
feedback.setFilter(new ContainerFeedbackMessageFilter(input.getBaseFormComponent()));
input.add(new VisibleEnableBehaviour() {
private static final long serialVersionUID = 1L;
@Override
public boolean isEnabled() {
return getOidFromParams(getPageParameters()) == null;
}
});
}
private void createPasswordPanel(WebMarkupContainer staticRegistrationForm) {
// ProtectedStringType initialPassword = null;
PasswordPanel password = new PasswordPanel(ID_PASSWORD,
new PropertyModel<>(getUserModel(), "credentials.password.value"), false, true);
password.getBaseFormComponent().add(new EmptyOnBlurAjaxFormUpdatingBehaviour());
password.getBaseFormComponent().setRequired(true);
staticRegistrationForm.add(password);
Label help = new Label(ID_TOOLTIP);
final StringResourceModel tooltipText = createStringResource("PageSelfRegistration.password.policy");
help.add(AttributeModifier.replace("title", tooltipText));
help.add(new InfoTooltipBehavior());
help.add(new VisibleEnableBehaviour() {
private static final long serialVersionUID = 1L;
@Override
public boolean isVisible() {
return StringUtils.isNotEmpty(tooltipText.getObject());
}
});
staticRegistrationForm.add(help);
}
@Override
protected WebMarkupContainer initDynamicLayout() {
DynamicFormPanel<UserType> dynamicForm = runPrivileged(
() -> {
Task task = createAnonymousTask(OPERATION_LOAD_DYNAMIC_FORM);
return createDynamicPanel(getMainForm(), task);
});
return dynamicForm;
}
private WebMarkupContainer createMarkupContainer(String id, Form<?> mainForm) {
WebMarkupContainer formContainer = new WebMarkupContainer(id);
formContainer.setOutputMarkupId(true);
add(formContainer);
return formContainer;
}
@Override
public IModel<UserType> getUserModel() {
return userModel;
}
@Override
public boolean isCustomFormDefined() {
return getSelfRegistrationConfiguration().getFormRef() != null;
}
@Override
protected void submitRegistration(AjaxRequestTarget target) {
OperationResult result = runPrivileged(new Producer<OperationResult>() {
private static final long serialVersionUID = 1L;
@Override
public OperationResult run() {
Task task = createAnonymousTask(OPERATION_SAVE_USER);
task.setChannel(SchemaConstants.CHANNEL_GUI_SELF_REGISTRATION_URI);
OperationResult result = new OperationResult(OPERATION_SAVE_USER);
saveUser(task, result);
result.computeStatus();
return result;
}
});
if (result.getStatus() == OperationResultStatus.SUCCESS) {
getSession()
.success(createStringResource("PageSelfRegistration.registration.success").getString());
switch (getSelfRegistrationConfiguration().getAuthenticationMethod()) {
case MAIL:
target.add(PageSelfRegistration.this);
break;
case SMS:
throw new UnsupportedOperationException();
case NONE:
setResponsePage(PageLogin.class);
}
LOGGER.trace("Registration for user {} was successfull.", getUserModel().getObject());
} else {
String message;
if (result.getUserFriendlyMessage() != null) {
message = WebModelServiceUtils.translateMessage(result, this);
} else {
message = result.getMessage();
}
getSession().error(
createStringResource("PageSelfRegistration.registration.error", message)
.getString());
// removePassword(target);
updateCaptcha(target);
target.add(getFeedbackPanel());
LOGGER.error("Failed to register user {}. Reason {}", getUserModel().getObject(), result.getMessage());
return;
}
target.add(getFeedbackPanel());
MultiLineLabel label = new MultiLineLabel(ID_REGISTRATION_SUBMITED,
createStringResource("PageSelfRegistration.registration.confirm.message"));
Fragment messageContent = new Fragment("contentArea", "messageContent", this);
messageContent.add(label);
getMainForm().replace(messageContent);
target.add(this);
}
private void saveUser(Task task, OperationResult result) {
ObjectDelta<UserType> userDelta;
try {
userDelta = prepareUserDelta(task, result);
} catch (SchemaException | ExpressionEvaluationException | ObjectNotFoundException | CommunicationException | ConfigurationException | SecurityViolationException e) {
result.recordFatalError(getString("PageSelfRegistration.message.saveUser.fatalError", e.getMessage()), e);
return;
}
userDelta.setPrismContext(getPrismContext());
WebModelServiceUtils.save(userDelta, ModelExecuteOptions.createOverwrite(), result, task,
PageSelfRegistration.this);
result.computeStatus();
}
private ObjectDelta<UserType> prepareUserDelta(Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException {
if (getOidFromParams(getPageParameters()) == null) {
LOGGER.trace("Preparing user ADD delta (new user registration)");
UserType userType = prepareUserToSave(task, result);
ObjectDelta<UserType> userDelta = DeltaFactory.Object.createAddDelta(userType.asPrismObject());
LOGGER.trace("Going to register user {}", userDelta);
return userDelta;
} else {
LOGGER.trace("Preparing user MODIFY delta (preregistered user registration)");
ObjectDelta<UserType> delta = null;
if (!isCustomFormDefined()) {
delta = getPrismContext().deltaFactory().object().createEmptyModifyDelta(UserType.class,
getOidFromParams(getPageParameters()));
if (getSelfRegistrationConfiguration().getInitialLifecycleState() != null) {
delta.addModificationReplaceProperty(UserType.F_LIFECYCLE_STATE,
getSelfRegistrationConfiguration().getInitialLifecycleState());
}
delta.addModificationReplaceProperty(SchemaConstants.PATH_PASSWORD_VALUE, createPassword().getValue());
} else {
delta = getDynamicFormPanel().getObjectDelta();
}
delta.addModificationReplaceContainer(SchemaConstants.PATH_NONCE,
createNonce(getSelfRegistrationConfiguration().getNoncePolicy(), task, result)
.asPrismContainerValue());
LOGGER.trace("Going to register user with modifications {}", delta);
return delta;
}
}
private UserType prepareUserToSave(Task task, OperationResult result) throws ExpressionEvaluationException, SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException {
SelfRegistrationDto selfRegistrationConfiguration = getSelfRegistrationConfiguration();
UserType userType = getUserModel().getObject();
UserType userToSave = userType.clone();
if (!isCustomFormDefined()) {
applyPassword(userToSave);
if (selfRegistrationConfiguration.getRequiredLifecycleState() != null) {
String userLifecycle = userToSave.getLifecycleState();
if (!selfRegistrationConfiguration.getRequiredLifecycleState().equals(userLifecycle)) {
LOGGER.error(
"Registration not allowed for a user {} -> Unsatisfied Configuration for required lifecycle, expected {} but was {}",
new Object[] {
userToSave.getEmailAddress() != null ? userToSave.getEmailAddress()
: userToSave,
selfRegistrationConfiguration.getRequiredLifecycleState(),
userLifecycle });
getSession().error(createStringResource(
"PageSelfRegistration.registration.failed.unsatisfied.registration.configuration")
.getString());
throw new RestartResponseException(this);
}
}
} else {
try {
userToSave = getDynamicFormPanel().getObject().asObjectable().clone();
} catch (SchemaException e) {
LoggingUtils.logException(LOGGER, "Failed to construct delta " + e.getMessage(), e);
new RestartResponseException(this);
}
}
// CredentialsType credentials =
applyNonce(userToSave, selfRegistrationConfiguration.getNoncePolicy(), task, result);
// userToSave.setCredentials(credentials);
if (selfRegistrationConfiguration.getInitialLifecycleState() != null) {
LOGGER.trace("Setting initial lifecycle state of registered user to {}",
selfRegistrationConfiguration.getInitialLifecycleState());
userToSave.setLifecycleState(selfRegistrationConfiguration.getInitialLifecycleState());
}
try {
getPrismContext().adopt(userToSave);
} catch (SchemaException e) {
// nothing to do, try without it
}
return userToSave;
}
// private void createCredentials(UserType user, NonceCredentialsPolicyType noncePolicy, Task task,
// OperationResult result) throws ExpressionEvaluationException, SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException {
// NonceType nonceType = createNonce(noncePolicy, task, result);
//
//// PasswordType password = createPassword();
//
// CredentialsType credentials = user.getCredentials();
// if (user.getCredentials() == null) {
// credentials = new CredentialsType();
// user.setCredentials(credentials);
// }
//
// credentials.setNonce(nonceType);
//// credentials.setPassword(password);
// // return credentials;
//
// }
private NonceType createNonce(NonceCredentialsPolicyType noncePolicy, Task task, OperationResult result) throws ExpressionEvaluationException, SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException {
ProtectedStringType nonceCredentials = new ProtectedStringType();
nonceCredentials.setClearValue(generateNonce(noncePolicy, null, task, result));
NonceType nonceType = new NonceType();
nonceType.setValue(nonceCredentials);
return nonceType;
}
private void applyPassword(UserType user) {
getCredentials(user).setPassword(createPassword());
}
private void applyNonce(UserType user, NonceCredentialsPolicyType noncePolicy, Task task, OperationResult result) throws ExpressionEvaluationException, SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException {
getCredentials(user).setNonce(createNonce(noncePolicy, task, result));
}
private CredentialsType getCredentials(UserType user) {
CredentialsType credentials = user.getCredentials();
if (user.getCredentials() == null) {
credentials = new CredentialsType();
user.setCredentials(credentials);
}
return credentials;
}
private PasswordType createPassword() {
PasswordType password = new PasswordType();
ProtectedStringType protectedString = new ProtectedStringType();
protectedString.setClearValue(getPassword());
password.setValue(protectedString);
return password;
}
private <O extends ObjectType> String generateNonce(NonceCredentialsPolicyType noncePolicy,
PrismObject<O> user, Task task, OperationResult result) throws ExpressionEvaluationException, SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException {
ValuePolicyType policy = null;
if (noncePolicy != null && noncePolicy.getValuePolicyRef() != null) {
PrismObject<ValuePolicyType> valuePolicy = WebModelServiceUtils.loadObject(ValuePolicyType.class,
noncePolicy.getValuePolicyRef().getOid(), PageSelfRegistration.this, task, result);
if (valuePolicy == null) {
LOGGER.error("Nonce cannot be generated, as value policy {} cannot be fetched", noncePolicy.getValuePolicyRef().getOid());
throw new ObjectNotFoundException("Nonce cannot be generated"); // no more information (security); TODO implement more correctly
}
policy = valuePolicy.asObjectable();
}
return getModelInteractionService().generateValue(policy,
24, false, user, "nonce generation (registration)", task, result);
}
private String getPassword() {
PasswordPanel password = (PasswordPanel)
get(createComponentPath(ID_MAIN_FORM, ID_CONTENT_AREA, ID_STATIC_FORM, ID_PASSWORD));
return (String) password.getBaseFormComponent().getModel().getObject();
}
@Override
protected boolean isBackButtonVisible() {
return true;
}
@Override
protected ObjectReferenceType getCustomFormRef() {
return getSelfRegistrationConfiguration().getFormRef();
}
}