]> git.mxchange.org Git - jjobs-war.git/blob - src/java/org/mxchange/jjobs/beans/user/register/JobsUserRegisterWebRequestBean.java
114e0ec729f5e212b08486e365ca95366d68fcdc
[jjobs-war.git] / src / java / org / mxchange / jjobs / beans / user / register / JobsUserRegisterWebRequestBean.java
1 /*
2  * Copyright (C) 2016 - 2020 Free Software Foundation
3  *
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.
8  *
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.
13  *
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/>.
16  */
17 package org.mxchange.jjobs.beans.user.register;
18
19 import java.util.Objects;
20 import javax.ejb.EJB;
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;
54
55 /**
56  * A web bean for user registration
57  * <p>
58  * @author Roland Häder<roland@mxchange.org>
59  */
60 @Named ("userRegistrationController")
61 @RequestScoped
62 public class JobsUserRegisterWebRequestBean extends BaseJobsBean implements JobsUserRegisterWebRequestController {
63
64         /**
65          * Serial number
66          */
67         private static final long serialVersionUID = 47_828_986_719_691_592L;
68
69         /**
70          * Contact controller
71          */
72         @Inject
73         private JobsContactWebRequestController contactController;
74
75         /**
76          * Features controller
77          */
78         @Inject
79         private JobsFeaturesWebApplicationController featureController;
80
81         /**
82          * Localization controller
83          */
84         @Inject
85         private JobsLocalizationSessionController localizationController;
86
87         /**
88          * Remote register session-scoped bean
89          */
90         @EJB (lookup = "java:global/jjobs-ejb/userRegistration!org.mxchange.juserlogincore.model.user.register.UserRegistrationSessionBeanRemote")
91         private UserRegistrationSessionBeanRemote registerBean;
92
93         /**
94          * User list controller
95          */
96         @Inject
97         private JobsUserListWebViewController userListController;
98
99         /**
100          * User name
101          */
102         private String userName;
103
104         /**
105          * User password (clear-text from web form)
106          */
107         private String userPassword;
108
109         /**
110          * An event being fired when a user password was changed
111          */
112         @Inject
113         @Any
114         private Event<ObservableUpdatedUserPasswordEvent> userPasswordChangedEvent;
115
116         /**
117          * User password repeated (clear-text from web form)
118          */
119         private String userPasswordRepeat;
120
121         /**
122          * Whether the user wants a public profile
123          */
124         private ProfileMode userProfileMode;
125
126         /**
127          * An event being fired when a new user has registered
128          */
129         @Inject
130         @Any
131         private Event<ObservableUserRegisteredEvent> userRegisteredEvent;
132
133         /**
134          * Default constructor
135          */
136         public JobsUserRegisterWebRequestBean () {
137                 // Call super constructor
138                 super();
139         }
140
141         /**
142          * Event observer for user password changes
143          * <p>
144          * @param event Event being fired
145          */
146         public void afterUserPasswordChangedEvent (@Observes final ObservableUpdatedUserPasswordEvent event) {
147                 // Is it valid?
148                 if (null == event) {
149                         // Throw NPE
150                         throw new NullPointerException("event is null"); //NOI18N
151                 } else if (event.getUserPassword() == null) {
152                         // Throw NPE
153                         throw new NullPointerException("event.userPassword is null"); //NOI18N
154                 } else if (event.getUserPassword().isEmpty()) {
155                         // Throw NPE
156                         throw new IllegalArgumentException("event.userPassword is empty"); //NOI18N
157                 }
158
159                 // Set it here
160                 this.setUserPassword(event.getUserPassword());
161                 this.setUserPasswordRepeat(event.getUserPassword());
162         }
163
164         /**
165          * Registers the user, if not found. Otherwise this method should throw an
166          * exception.
167          * <p>
168          * @return Redirection target
169          */
170         public String doFinishRegistration () {
171                 // Is registration enabled?
172                 if (!this.featureController.isFeatureEnabled("user_registration")) { //NOI18N
173                         // Is not enabled
174                         throw new FacesException("Registration is disabled."); //NOI18N
175                 }
176
177                 // Get user instance
178                 final User user = this.createUserInstance(true);
179
180                 // Null random password means registration requires user-entered password
181                 String randomPassword = null;
182
183                 // Is the user already used?
184                 if (null == user) {
185                         // user must be set
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));
195                         } else {
196                                 // May happen here, clear user name
197                                 this.clearUserName();
198
199                                 // Output message
200                                 this.showFacesMessage("form_register_single:userName", "ERROR_USER_NAME_ALREADY_USED", FacesMessage.SEVERITY_WARN); //NOI18N
201                                 return ""; //NOI18N
202                         }
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));
208                         } else {
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
212                                 return ""; //NOI18N
213                         }
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
219                         } else {
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
223                                 return ""; //NOI18N
224                         }
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);
233
234                                 // Generate (ignored) password-history
235                                 final PasswordHistory passwordHistory = new UserPasswordHistory(randomPassword, user);
236
237                                 // Fire event
238                                 this.userPasswordChangedEvent.fire(new UpdatedUserPasswordEvent(passwordHistory, randomPassword));
239                         }
240                 }
241
242                 // Encrypt password
243                 final String encryptedPassword = UserLoginUtils.encryptPassword(this.getUserPassword());
244
245                 // Set it here
246                 user.setUserEncryptedPassword(encryptedPassword);
247
248                 // Is developer mode?
249                 if (this.isDebugModeEnabled("register")) { //NOI18N
250                         // For debugging/programming only:
251                         user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
252                 } else {
253                         // No debugging of this part
254                         user.setUserAccountStatus(UserAccountStatus.UNCONFIRMED);
255
256                         // Ask EJB for generating a not-existing confirmation key
257                         final String confirmKey = this.registerBean.generateConfirmationKey(user);
258
259                         // Set it in user
260                         user.setUserConfirmKey(confirmKey);
261                 }
262
263                 try {
264                         // Get base URL
265                         final String baseUrl = FacesUtils.generateBaseUrl();
266
267                         // Call bean
268                         final User registeredUser = this.registerBean.registerUser(user, baseUrl, randomPassword);
269
270                         // The id number should be set
271                         assert (registeredUser.getUserId() instanceof Long) : "registeredUser.userId is null after registerUser() was called."; //NOI18N
272
273                         // Fire event
274                         this.userRegisteredEvent.fire(new UserRegisteredEvent(registeredUser));
275
276                         // All fine, redirect to proper page
277                         return "user_register_done"; //NOI18N
278                 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
279                         // Continue to throw
280                         throw new FacesException(ex);
281                 }
282         }
283
284         /**
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
287          * accepted.
288          * <p>
289          * @return Redirect
290          */
291         public String doRegisterMultiPage1 () {
292                 // Is registration enabled?
293                 if (!this.featureController.isFeatureEnabled("user_registration")) { //NOI18N
294                         // Is not enabled
295                         throw new FacesException("Registration is disabled."); //NOI18N
296                 }
297
298                 // Get user instance
299                 final User user = this.createUserInstance(false);
300
301                 // First check if user is not null and user name is not used + if same email address is entered
302                 if (null == user) {
303                         // user must be set
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();
308
309                         // Output message
310                         this.showFacesMessage("form_register_page1:userName", "ERROR_USER_NAME_ALREADY_USED", FacesMessage.SEVERITY_WARN); //NOI18N
311                         return ""; //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
316                         return ""; //NOI18N
317                 } else if (!this.isSamePasswordEntered()) {
318                         // Is multi-page enabled?
319                         if (this.featureController.isFeatureEnabled("user_register_multiple_page")) { //NOI18N
320                                 // Clear passwords
321                                 this.clearUserPasswords();
322
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
326                                 return ""; //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);
330
331                                 // Generate (ignored) password-history
332                                 final PasswordHistory passwordHistory = new UserPasswordHistory(randomPassword, user);
333
334                                 // Fire event
335                                 this.userPasswordChangedEvent.fire(new UpdatedUserPasswordEvent(passwordHistory, randomPassword));
336                         }
337                 }
338
339                 // Create half contact instance with email address
340                 final Contact contact = new UserContact();
341                 contact.setContactEmailAddress(this.contactController.getEmailAddress());
342
343                 // Set contact in user
344                 user.setUserContact(contact);
345
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
351                         return ""; //NOI18N
352                 }
353
354                 // Now only redirect to next page as the JSF does it
355                 return "user_register_page2"; //NOI18N
356         }
357
358         /**
359          * Getter for user name
360          * <p>
361          * @return User name
362          */
363         public String getUserName () {
364                 return this.userName;
365         }
366
367         /**
368          * Setter for user name
369          * <p>
370          * @param userName User name
371          */
372         public void setUserName (final String userName) {
373                 this.userName = userName;
374         }
375
376         /**
377          * Getter for clear-text user password
378          * <p>
379          * @return Clear-text user password
380          */
381         public String getUserPassword () {
382                 return this.userPassword;
383         }
384
385         /**
386          * Setter for clear-text user password
387          * <p>
388          * @param userPassword Clear-text user password
389          */
390         public void setUserPassword (final String userPassword) {
391                 this.userPassword = userPassword;
392         }
393
394         /**
395          * Getter for clear-text user password repeated
396          * <p>
397          * @return Clear-text user password repeated
398          */
399         public String getUserPasswordRepeat () {
400                 return this.userPasswordRepeat;
401         }
402
403         /**
404          * Setter for clear-text user password repeated
405          * <p>
406          * @param userPasswordRepeat Clear-text user password repeated
407          */
408         public void setUserPasswordRepeat (final String userPasswordRepeat) {
409                 this.userPasswordRepeat = userPasswordRepeat;
410         }
411
412         /**
413          * Getter for user profile mode
414          * <p>
415          * @return User profile mode
416          */
417         public ProfileMode getUserProfileMode () {
418                 return this.userProfileMode;
419         }
420
421         /**
422          * Setter for user profile mode
423          * <p>
424          * @param userProfileMode User profile mode
425          */
426         public void setUserProfileMode (final ProfileMode userProfileMode) {
427                 this.userProfileMode = userProfileMode;
428         }
429
430         @Override
431         public boolean isRequiredChangePersonalDataSet () {
432                 return ((this.getUserProfileMode() != null) &&
433                                 (this.getUserName() != null) &&
434                                 (!this.getUserName().isEmpty()) &&
435                                 (this.contactController.isRequiredChangePersonalDataSet()));
436         }
437
438         /**
439          * Clears user name
440          */
441         private void clearUserName () {
442                 // Clear it
443                 this.setUserName(null);
444         }
445
446         /**
447          * Clears both user passwords
448          */
449         private void clearUserPasswords () {
450                 // Clear both
451                 this.setUserPassword(null);
452                 this.setUserPasswordRepeat(null);
453         }
454
455         /**
456          * Creates an instance from all properties
457          * <p>
458          * @param createContactData Whether contact data should be created
459          * <p>
460          * @return A user instance
461          */
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
465
466                 // Is user name required?
467                 if (!this.featureController.isFeatureEnabled("user_login_require_username")) {
468                         // Init variables
469                         String randomName = null;
470                         boolean isUsernameFree = false;
471
472                         // Get full list
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;
479                                 }
480
481                                 // Is non-existing username found
482                                 if (isUsernameFree) {
483                                         // Also stop looping here
484                                         break;
485                                 }
486                         }
487
488                         // Set it and inivisible profile
489                         this.setUserName(randomName);
490                         this.setUserProfileMode(ProfileMode.INVISIBLE);
491
492                         // Generate random password
493                         final String randomPassword = UserLoginUtils.createRandomPassword(JobsUserWebRequestController.MINIMUM_PASSWORD_LENGTH);
494
495                         // Set random password
496                         this.setUserPassword(randomPassword);
497                         this.setUserPasswordRepeat(randomPassword);
498                 }
499
500                 // Create new user instance
501                 final User user = new LoginUser();
502
503                 // Set user name profile mode and locale
504                 user.setUserName(this.getUserName());
505                 user.setUserProfileMode(this.getUserProfileMode());
506                 user.setUserLocale(this.localizationController.getLocale());
507
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();
512
513                         // Set contact in user
514                         user.setUserContact(contact);
515                 }
516
517                 // Return it
518                 return user;
519         }
520
521         /**
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.
526          * <p>
527          * @return Whether empty passwords are allowed
528          */
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())));
534         }
535
536         /**
537          * Checks whether all required personal data is set
538          * <p>
539          * @return Whether the required personal data is set
540          */
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();
546                 } else {
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));
553                 }
554         }
555
556         /**
557          * Checks whether same passwords has been entered
558          * <p>
559          * @return Whether same passwords has been entered
560          */
561         private boolean isSamePasswordEntered () {
562                 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
563         }
564
565 }