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);
265 final String baseUrl = FacesUtils.generateBaseUrl();
268 final User registeredUser = this.registerBean.registerUser(user, baseUrl, randomPassword);
270 // The id number should be set
271 assert (registeredUser.getUserId() instanceof Long) : "registeredUser.userId is null after registerUser() was called."; //NOI18N
274 this.userRegisteredEvent.fire(new UserRegisteredEvent(registeredUser));
276 // All fine, redirect to proper page
277 return "user_register_done"; //NOI18N
278 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
280 throw new FacesException(ex);
285 * Handles registration request send from first page. The (maybe) entered
286 * user name and email address is not used and that privacy and T&C are
291 public String doRegisterMultiPage1 () {
292 // Is registration enabled?
293 if (!this.featureController.isFeatureEnabled("user_registration")) { //NOI18N
295 throw new FacesException("Registration is disabled."); //NOI18N
299 final User user = this.createUserInstance(false);
301 // First check if user is not null and user name is not used + if same email address is entered
304 throw new NullPointerException("user is null after createUserInstance() was called"); //NOI18N
305 } else if ((this.featureController.isFeatureEnabled("user_login_require_user_name")) && (this.userListController.isUserNameRegistered(user))) { //NOI18N
306 // User name is already used, so clear it
307 this.clearUserName();
310 this.showFacesMessage("form_register_page1:userName", "ERROR_USER_NAME_ALREADY_USED", FacesMessage.SEVERITY_WARN); //NOI18N
312 } else if (!this.contactController.isSameEmailAddressEntered()) {
313 // Not same email address entered, clear both
314 this.contactController.clearEmailAddresses();
315 this.showFacesMessage("form_register_page1:emailAddressRepeat", "ERROR_EMAIL_ADDRESSES_MISMATCHING", FacesMessage.SEVERITY_WARN); //NOI18N
317 } else if (!this.isSamePasswordEntered()) {
318 // Is multi-page enabled?
319 if (this.featureController.isFeatureEnabled("user_register_multiple_page")) { //NOI18N
321 this.clearUserPasswords();
323 // Output faces message
324 this.showFacesMessage("form_register_page1:userPassword", "ERROR_USER_PASSWORD_EMPTY", FacesMessage.SEVERITY_WARN); //NOI18N
325 this.showFacesMessage("form_register_page1:userPasswordRepeat", "ERROR_USER_PASSWORD_REPEAT_EMPTY", FacesMessage.SEVERITY_WARN); //NOI18N
327 } else if (this.ifBothPasswordsEmptyAllowed()) {
328 // Both passwords are left empty and is allowed, then generate a random password
329 final String randomPassword = UserLoginUtils.createRandomPassword(JobsUserWebRequestController.MINIMUM_PASSWORD_LENGTH);
331 // Generate (ignored) password-history
332 final PasswordHistory passwordHistory = new UserPasswordHistory(randomPassword, user);
335 this.userPasswordChangedEvent.fire(new UpdatedUserPasswordEvent(passwordHistory, randomPassword));
339 // Create half contact instance with email address
340 final Contact contact = new UserContact();
341 contact.setContactEmailAddress(this.contactController.getEmailAddress());
343 // Set contact in user
344 user.setUserContact(contact);
346 // Check if email address is registered
347 if (this.contactController.isEmailAddressRegistered(user.getUserContact())) {
348 // Email address has already been taken, clear both
349 this.contactController.clearEmailAddresses();
350 this.showFacesMessage("form_register_page1:emailAddress", "ERROR_EMAIL_ADDRESS_ALREADY_USED", FacesMessage.SEVERITY_WARN); //NOI18N
354 // Now only redirect to next page as the JSF does it
355 return "user_register_page2"; //NOI18N
359 * Getter for user name
363 public String getUserName () {
364 return this.userName;
368 * Setter for user name
370 * @param userName User name
372 public void setUserName (final String userName) {
373 this.userName = userName;
377 * Getter for clear-text user password
379 * @return Clear-text user password
381 public String getUserPassword () {
382 return this.userPassword;
386 * Setter for clear-text user password
388 * @param userPassword Clear-text user password
390 public void setUserPassword (final String userPassword) {
391 this.userPassword = userPassword;
395 * Getter for clear-text user password repeated
397 * @return Clear-text user password repeated
399 public String getUserPasswordRepeat () {
400 return this.userPasswordRepeat;
404 * Setter for clear-text user password repeated
406 * @param userPasswordRepeat Clear-text user password repeated
408 public void setUserPasswordRepeat (final String userPasswordRepeat) {
409 this.userPasswordRepeat = userPasswordRepeat;
413 * Getter for user profile mode
415 * @return User profile mode
417 public ProfileMode getUserProfileMode () {
418 return this.userProfileMode;
422 * Setter for user profile mode
424 * @param userProfileMode User profile mode
426 public void setUserProfileMode (final ProfileMode userProfileMode) {
427 this.userProfileMode = userProfileMode;
431 public boolean isRequiredChangePersonalDataSet () {
432 return ((this.getUserProfileMode() != null) &&
433 (this.getUserName() != null) &&
434 (!this.getUserName().isEmpty()) &&
435 (this.contactController.isRequiredChangePersonalDataSet()));
441 private void clearUserName () {
443 this.setUserName(null);
447 * Clears both user passwords
449 private void clearUserPasswords () {
451 this.setUserPassword(null);
452 this.setUserPasswordRepeat(null);
456 * Creates an instance from all properties
458 * @param createContactData Whether contact data should be created
460 * @return A user instance
462 private User createUserInstance (final boolean createContactData) {
463 // Required personal data must be set
464 assert (this.isRequiredPersonalDataSet()) : "All required personal data must be set before invoking this method."; //NOI18N
466 // Is user name required?
467 if (!this.featureController.isFeatureEnabled("user_login_require_username")) {
469 String randomName = null;
470 boolean isUsernameFree = false;
473 for (final User user : this.userListController.getAllUsers()) {
474 // Loop until a user name is found
475 while ((randomName == null) || (randomName.equals(user.getUserName()))) {
476 // Generate random name
477 randomName = Users.generateRandomUserName();
478 isUsernameFree = true;
481 // Is non-existing username found
482 if (isUsernameFree) {
483 // Also stop looping here
488 // Set it and inivisible profile
489 this.setUserName(randomName);
490 this.setUserProfileMode(ProfileMode.INVISIBLE);
492 // Generate random password
493 final String randomPassword = UserLoginUtils.createRandomPassword(JobsUserWebRequestController.MINIMUM_PASSWORD_LENGTH);
495 // Set random password
496 this.setUserPassword(randomPassword);
497 this.setUserPasswordRepeat(randomPassword);
500 // Create new user instance
501 final User user = new LoginUser();
503 // Set user name profile mode and locale
504 user.setUserName(this.getUserName());
505 user.setUserProfileMode(this.getUserProfileMode());
506 user.setUserLocale(this.localizationController.getLocale());
508 // Is multiple registration page
509 if ((createContactData) || (!this.featureController.isFeatureEnabled("user_register_multiple_page"))) { //NOI18N
510 // Create contact instance
511 final Contact contact = this.contactController.createContactInstance();
513 // Set contact in user
514 user.setUserContact(contact);
522 * Checks if both user passwords are left empty and if this is enabled
523 * (allowed) in context parameter. If true, the calling bean should create a
524 * random password (preferable with UserUtils.createRandomPassword() and set
525 * it in both user password fields.
527 * @return Whether empty passwords are allowed
529 private boolean ifBothPasswordsEmptyAllowed () {
530 // Check feature first
531 return ((this.featureController.isFeatureEnabled("allow_user_registration_empty_password")) && //NOI18N
532 ((this.getUserPassword() == null) || (this.getUserPassword().isEmpty())) &&
533 ((this.getUserPasswordRepeat() == null) || (this.getUserPasswordRepeat().isEmpty())));
537 * Checks whether all required personal data is set
539 * @return Whether the required personal data is set
541 private boolean isRequiredPersonalDataSet () {
542 // Check conditions based on of multi-page registration is enabled
543 if (this.featureController.isFeatureEnabled("user_register_multiple_page")) { //NOI18N
544 // Multiple registration page
545 return this.contactController.isRequiredPersonalDataSet();
547 // Single registration page
548 return (((this.getUserName() != null) || (!this.featureController.isFeatureEnabled("user_login_require_username"))) && //NOI18N
549 (this.getUserProfileMode() != null) &&
550 (this.contactController.isRequiredPersonalDataSet()) &&
551 (this.getUserPassword() != null) &&
552 (this.getUserPasswordRepeat() != null));
557 * Checks whether same passwords has been entered
559 * @return Whether same passwords has been entered
561 private boolean isSamePasswordEntered () {
562 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));