2 * Copyright (C) 2016 - 2020 Free Software Foundation
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as
6 * published by the Free Software Foundation, either version 3 of the
7 * License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
14 * You should have received a copy of the GNU Affero General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org.mxchange.jjobs.beans.user.register;
19 import java.util.Objects;
21 import javax.enterprise.context.RequestScoped;
22 import javax.enterprise.event.Event;
23 import javax.enterprise.event.Observes;
24 import javax.enterprise.inject.Any;
25 import javax.faces.FacesException;
26 import javax.faces.application.FacesMessage;
27 import javax.inject.Inject;
28 import javax.inject.Named;
29 import org.mxchange.jcontacts.model.contact.Contact;
30 import org.mxchange.jcontacts.model.contact.UserContact;
31 import org.mxchange.jcoreee.utils.FacesUtils;
32 import org.mxchange.jjobs.beans.BaseJobsBean;
33 import org.mxchange.jjobs.beans.contact.JobsContactWebRequestController;
34 import org.mxchange.jjobs.beans.features.JobsFeaturesWebApplicationController;
35 import org.mxchange.jjobs.beans.localization.JobsLocalizationSessionController;
36 import org.mxchange.jjobs.beans.user.JobsUserWebRequestController;
37 import org.mxchange.jjobs.beans.user.list.JobsUserListWebViewController;
38 import org.mxchange.jusercore.exceptions.DataRepeatMismatchException;
39 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
40 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
41 import org.mxchange.jusercore.model.user.LoginUser;
42 import org.mxchange.jusercore.model.user.User;
43 import org.mxchange.jusercore.model.user.Users;
44 import org.mxchange.jusercore.model.user.password_history.PasswordHistory;
45 import org.mxchange.jusercore.model.user.password_history.UserPasswordHistory;
46 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
47 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
48 import org.mxchange.juserlogincore.events.registration.ObservableUserRegisteredEvent;
49 import org.mxchange.juserlogincore.events.registration.UserRegisteredEvent;
50 import org.mxchange.juserlogincore.events.user.password_change.ObservableUpdatedUserPasswordEvent;
51 import org.mxchange.juserlogincore.events.user.password_change.UpdatedUserPasswordEvent;
52 import org.mxchange.juserlogincore.login.UserLoginUtils;
53 import org.mxchange.juserlogincore.model.user.register.UserRegistrationSessionBeanRemote;
56 * A web bean for user registration
58 * @author Roland Häder<roland@mxchange.org>
60 @Named ("userRegistrationController")
62 public class JobsUserRegisterWebRequestBean extends BaseJobsBean implements JobsUserRegisterWebRequestController {
67 private static final long serialVersionUID = 47_828_986_719_691_592L;
73 private JobsContactWebRequestController contactController;
79 private JobsFeaturesWebApplicationController featureController;
82 * Localization controller
85 private JobsLocalizationSessionController localizationController;
88 * Remote register session-scoped bean
90 @EJB (lookup = "java:global/jjobs-ejb/userRegistration!org.mxchange.juserlogincore.model.user.register.UserRegistrationSessionBeanRemote")
91 private UserRegistrationSessionBeanRemote registerBean;
94 * User list controller
97 private JobsUserListWebViewController userListController;
102 private String userName;
105 * User password (clear-text from web form)
107 private String userPassword;
110 * An event being fired when a user password was changed
114 private Event<ObservableUpdatedUserPasswordEvent> userPasswordChangedEvent;
117 * User password repeated (clear-text from web form)
119 private String userPasswordRepeat;
122 * Whether the user wants a public profile
124 private ProfileMode userProfileMode;
127 * An event being fired when a new user has registered
131 private Event<ObservableUserRegisteredEvent> userRegisteredEvent;
134 * Default constructor
136 public JobsUserRegisterWebRequestBean () {
137 // Call super constructor
142 * Event observer for user password changes
144 * @param event Event being fired
146 public void afterUserPasswordChangedEvent (@Observes final ObservableUpdatedUserPasswordEvent event) {
150 throw new NullPointerException("event is null"); //NOI18N
151 } else if (event.getUserPassword() == null) {
153 throw new NullPointerException("event.userPassword is null"); //NOI18N
154 } else if (event.getUserPassword().isEmpty()) {
156 throw new IllegalArgumentException("event.userPassword is empty"); //NOI18N
160 this.setUserPassword(event.getUserPassword());
161 this.setUserPasswordRepeat(event.getUserPassword());
165 * Registers the user, if not found. Otherwise this method should throw an
168 * @return Redirection target
170 public String doFinishRegistration () {
171 // Is registration enabled?
172 if (!this.featureController.isFeatureEnabled("user_registration")) { //NOI18N
174 throw new FacesException("Registration is disabled."); //NOI18N
178 final User user = this.createUserInstance(true);
180 // Null random password means registration requires user-entered password
181 String randomPassword = null;
183 // Is the user already used?
186 throw new NullPointerException("user is null after createUserInstance() was called"); //NOI18N
187 } else if (!this.isRequiredPersonalDataSet()) {
188 // Not all required fields are set
189 throw new FacesException("Not all required fields are set."); //NOI18N
190 } else if ((this.featureController.isFeatureEnabled("user_login_require_user_name")) && (this.userListController.isUserNameRegistered(user))) { //NOI18N
191 // Is multi-page enabled?
192 if (this.featureController.isFeatureEnabled("user_register_multiple_page")) { //NOI18N
193 // User name is already used, should not happen here
194 throw new FacesException(new UserNameAlreadyRegisteredException(user));
196 // May happen here, clear user name
197 this.clearUserName();
200 this.showFacesMessage("form_register_single:userName", "ERROR_USER_NAME_ALREADY_USED", FacesMessage.SEVERITY_WARN); //NOI18N
203 } else if (this.contactController.isEmailAddressRegistered(user.getUserContact())) {
204 // Is multi-page enabled?
205 if (this.featureController.isFeatureEnabled("user_register_multiple_page")) { //NOI18N
206 // Email address has already been taken, should not happen here
207 throw new FacesException(new EmailAddressAlreadyRegisteredException(user));
209 // May happen here, reset fields
210 this.contactController.clearEmailAddresses();
211 this.showFacesMessage("form_register_single:emailAddressRepeat", "ERROR_EMAIL_ADDRESS_ALREADY_USED", FacesMessage.SEVERITY_WARN); //NOI18N
214 } else if (!this.contactController.isSameEmailAddressEntered()) {
215 // Is multi-page enabled?
216 if (this.featureController.isFeatureEnabled("user_register_multiple_page")) { //NOI18N
217 // Not same email address entered, should not happen here
218 throw new FacesException(new DataRepeatMismatchException("Email addresses not matching.")); //NOI18N
220 // May happen here, reset fields
221 this.contactController.clearEmailAddresses();
222 this.showFacesMessage("form_register_single:emailAddressRepeat", "ERROR_EMAIL_ADDRESSES_MISMATCHING", FacesMessage.SEVERITY_INFO); //NOI18N
225 } else if (!this.isSamePasswordEntered()) {
226 // Is multi-page enabled?
227 if (this.featureController.isFeatureEnabled("user_register_multiple_page")) { //NOI18N
228 // Not same password entered, should no longer happen here
229 throw new FacesException(new DataRepeatMismatchException("Passwords not matching.")); //NOI18N
230 } else if (this.ifBothPasswordsEmptyAllowed()) {
231 // Both passwords are left empty and is allowed, then generate a random password
232 randomPassword = UserLoginUtils.createRandomPassword(JobsUserWebRequestController.MINIMUM_PASSWORD_LENGTH);
234 // Generate (ignored) password-history
235 final PasswordHistory passwordHistory = new UserPasswordHistory(randomPassword, user);
238 this.userPasswordChangedEvent.fire(new UpdatedUserPasswordEvent(passwordHistory, randomPassword));
243 final String encryptedPassword = UserLoginUtils.encryptPassword(this.getUserPassword());
246 user.setUserEncryptedPassword(encryptedPassword);
248 // Is developer mode?
249 if (this.isDebugModeEnabled("register")) { //NOI18N
250 // For debugging/programming only:
251 user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
253 // No debugging of this part
254 user.setUserAccountStatus(UserAccountStatus.UNCONFIRMED);
256 // Ask EJB for generating a not-existing confirmation key
257 final String confirmKey = this.registerBean.generateConfirmationKey(user);
260 user.setUserConfirmKey(confirmKey);
264 final User registeredUser;
268 final String baseUrl = FacesUtils.generateBaseUrl();
271 registeredUser = this.registerBean.registerUser(user, baseUrl, randomPassword);
273 // The id number should be set
274 assert (registeredUser.getUserId() instanceof Long) : "registeredUser.userId is null after registerUser() was called."; //NOI18N
275 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
277 throw new FacesException(ex);
281 this.userRegisteredEvent.fire(new UserRegisteredEvent(registeredUser));
283 // All fine, redirect to proper page
284 return "user_register_done"; //NOI18N
288 * Handles registration request send from first page. The (maybe) entered
289 * user name and email address is not used and that privacy and T&C are
294 public String doRegisterMultiPage1 () {
295 // Is registration enabled?
296 if (!this.featureController.isFeatureEnabled("user_registration")) { //NOI18N
298 throw new FacesException("Registration is disabled."); //NOI18N
302 final User user = this.createUserInstance(false);
304 // First check if user is not null and user name is not used + if same email address is entered
307 throw new NullPointerException("user is null after createUserInstance() was called"); //NOI18N
308 } else if ((this.featureController.isFeatureEnabled("user_login_require_user_name")) && (this.userListController.isUserNameRegistered(user))) { //NOI18N
309 // User name is already used, so clear it
310 this.clearUserName();
313 this.showFacesMessage("form_register_page1:userName", "ERROR_USER_NAME_ALREADY_USED", FacesMessage.SEVERITY_WARN); //NOI18N
315 } else if (!this.contactController.isSameEmailAddressEntered()) {
316 // Not same email address entered, clear both
317 this.contactController.clearEmailAddresses();
318 this.showFacesMessage("form_register_page1:emailAddressRepeat", "ERROR_EMAIL_ADDRESSES_MISMATCHING", FacesMessage.SEVERITY_WARN); //NOI18N
320 } else if (!this.isSamePasswordEntered()) {
321 // Is multi-page enabled?
322 if (this.featureController.isFeatureEnabled("user_register_multiple_page")) { //NOI18N
324 this.clearUserPasswords();
326 // Output faces message
327 this.showFacesMessage("form_register_page1:userPassword", "ERROR_USER_PASSWORD_EMPTY", FacesMessage.SEVERITY_WARN); //NOI18N
328 this.showFacesMessage("form_register_page1:userPasswordRepeat", "ERROR_USER_PASSWORD_REPEAT_EMPTY", FacesMessage.SEVERITY_WARN); //NOI18N
330 } else if (this.ifBothPasswordsEmptyAllowed()) {
331 // Both passwords are left empty and is allowed, then generate a random password
332 final String randomPassword = UserLoginUtils.createRandomPassword(JobsUserWebRequestController.MINIMUM_PASSWORD_LENGTH);
334 // Generate (ignored) password-history
335 final PasswordHistory passwordHistory = new UserPasswordHistory(randomPassword, user);
338 this.userPasswordChangedEvent.fire(new UpdatedUserPasswordEvent(passwordHistory, randomPassword));
342 // Create half contact instance with email address
343 final Contact contact = new UserContact();
344 contact.setContactEmailAddress(this.contactController.getEmailAddress());
346 // Set contact in user
347 user.setUserContact(contact);
349 // Check if email address is registered
350 if (this.contactController.isEmailAddressRegistered(user.getUserContact())) {
351 // Email address has already been taken, clear both
352 this.contactController.clearEmailAddresses();
353 this.showFacesMessage("form_register_page1:emailAddress", "ERROR_EMAIL_ADDRESS_ALREADY_USED", FacesMessage.SEVERITY_WARN); //NOI18N
357 // Now only redirect to next page as the JSF does it
358 return "user_register_page2"; //NOI18N
362 * Getter for user name
366 public String getUserName () {
367 return this.userName;
371 * Setter for user name
373 * @param userName User name
375 public void setUserName (final String userName) {
376 this.userName = userName;
380 * Getter for clear-text user password
382 * @return Clear-text user password
384 public String getUserPassword () {
385 return this.userPassword;
389 * Setter for clear-text user password
391 * @param userPassword Clear-text user password
393 public void setUserPassword (final String userPassword) {
394 this.userPassword = userPassword;
398 * Getter for clear-text user password repeated
400 * @return Clear-text user password repeated
402 public String getUserPasswordRepeat () {
403 return this.userPasswordRepeat;
407 * Setter for clear-text user password repeated
409 * @param userPasswordRepeat Clear-text user password repeated
411 public void setUserPasswordRepeat (final String userPasswordRepeat) {
412 this.userPasswordRepeat = userPasswordRepeat;
416 * Getter for user profile mode
418 * @return User profile mode
420 public ProfileMode getUserProfileMode () {
421 return this.userProfileMode;
425 * Setter for user profile mode
427 * @param userProfileMode User profile mode
429 public void setUserProfileMode (final ProfileMode userProfileMode) {
430 this.userProfileMode = userProfileMode;
434 public boolean isRequiredChangePersonalDataSet () {
435 return ((this.getUserProfileMode() != null) &&
436 (this.getUserName() != null) &&
437 (!this.getUserName().isEmpty()) &&
438 (this.contactController.isRequiredChangePersonalDataSet()));
444 private void clearUserName () {
446 this.setUserName(null);
450 * Clears both user passwords
452 private void clearUserPasswords () {
454 this.setUserPassword(null);
455 this.setUserPasswordRepeat(null);
459 * Creates an instance from all properties
461 * @param createContactData Whether contact data should be created
463 * @return A user instance
465 private User createUserInstance (final boolean createContactData) {
466 // Required personal data must be set
467 assert (this.isRequiredPersonalDataSet()) : "All required personal data must be set before invoking this method."; //NOI18N
469 // Is user name required?
470 if (!this.featureController.isFeatureEnabled("user_login_require_username")) {
472 String randomName = null;
473 boolean isUsernameFree = false;
476 for (final User user : this.userListController.getAllUsers()) {
477 // Loop until a user name is found
478 while ((randomName == null) || (randomName.equals(user.getUserName()))) {
479 // Generate random name
480 randomName = Users.generateRandomUserName();
481 isUsernameFree = true;
484 // Is non-existing username found
485 if (isUsernameFree) {
486 // Also stop looping here
491 // Set it and inivisible profile
492 this.setUserName(randomName);
493 this.setUserProfileMode(ProfileMode.INVISIBLE);
495 // Generate random password
496 final String randomPassword = UserLoginUtils.createRandomPassword(JobsUserWebRequestController.MINIMUM_PASSWORD_LENGTH);
498 // Set random password
499 this.setUserPassword(randomPassword);
500 this.setUserPasswordRepeat(randomPassword);
503 // Create new user instance
504 final User user = new LoginUser();
506 // Set user name profile mode and locale
507 user.setUserName(this.getUserName());
508 user.setUserProfileMode(this.getUserProfileMode());
509 user.setUserLocale(this.localizationController.getLocale());
511 // Is multiple registration page
512 if ((createContactData) || (!this.featureController.isFeatureEnabled("user_register_multiple_page"))) { //NOI18N
513 // Create contact instance
514 final Contact contact = this.contactController.createContactInstance();
516 // Set contact in user
517 user.setUserContact(contact);
525 * Checks if both user passwords are left empty and if this is enabled
526 * (allowed) in context parameter. If true, the calling bean should create a
527 * random password (preferable with UserUtils.createRandomPassword() and set
528 * it in both user password fields.
530 * @return Whether empty passwords are allowed
532 private boolean ifBothPasswordsEmptyAllowed () {
533 // Check feature first
534 return ((this.featureController.isFeatureEnabled("allow_user_registration_empty_password")) && //NOI18N
535 ((this.getUserPassword() == null) || (this.getUserPassword().isEmpty())) &&
536 ((this.getUserPasswordRepeat() == null) || (this.getUserPasswordRepeat().isEmpty())));
540 * Checks whether all required personal data is set
542 * @return Whether the required personal data is set
544 private boolean isRequiredPersonalDataSet () {
545 // Check conditions based on of multi-page registration is enabled
546 if (this.featureController.isFeatureEnabled("user_register_multiple_page")) { //NOI18N
547 // Multiple registration page
548 return this.contactController.isRequiredPersonalDataSet();
550 // Single registration page
551 return (((this.getUserName() != null) || (!this.featureController.isFeatureEnabled("user_login_require_username"))) && //NOI18N
552 (this.getUserProfileMode() != null) &&
553 (this.contactController.isRequiredPersonalDataSet()) &&
554 (this.getUserPassword() != null) &&
555 (this.getUserPasswordRepeat() != null));
560 * Checks whether same passwords has been entered
562 * @return Whether same passwords has been entered
564 private boolean isSamePasswordEntered () {
565 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));