2 * Copyright (C) 2016 - 2024 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.pizzaapplication.beans.user;
19 import java.text.MessageFormat;
20 import java.util.Locale;
21 import java.util.Objects;
23 import javax.enterprise.context.RequestScoped;
24 import javax.enterprise.event.Event;
25 import javax.enterprise.event.Observes;
26 import javax.enterprise.inject.Any;
27 import javax.faces.FacesException;
28 import javax.faces.context.FacesContext;
29 import javax.faces.view.facelets.FaceletException;
30 import javax.inject.Inject;
31 import javax.inject.Named;
32 import org.mxchange.jcontacts.model.contact.Contact;
33 import org.mxchange.jcoreee.utils.FacesUtils;
34 import org.mxchange.pizzaapplication.beans.helper.PizzaWebViewHelperController;
35 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
36 import org.mxchange.jusercore.events.user.add.ObservableAdminAddedUserEvent;
37 import org.mxchange.jusercore.events.user.delete.AdminDeletedUserEvent;
38 import org.mxchange.jusercore.events.user.delete.ObservableAdminDeletedUserEvent;
39 import org.mxchange.jusercore.events.user.linked.AdminLinkedUserEvent;
40 import org.mxchange.jusercore.events.user.linked.ObservableAdminLinkedUserEvent;
41 import org.mxchange.jusercore.events.user.locked.AdminLockedUserEvent;
42 import org.mxchange.jusercore.events.user.locked.ObservableAdminLockedUserEvent;
43 import org.mxchange.jusercore.events.user.unlocked.AdminUnlockedUserEvent;
44 import org.mxchange.jusercore.events.user.unlocked.ObservableAdminUnlockedUserEvent;
45 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
46 import org.mxchange.jusercore.events.user.update.ObservableAdminUpdatedUserDataEvent;
47 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
48 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
49 import org.mxchange.jusercore.exceptions.UserNotFoundException;
50 import org.mxchange.jusercore.exceptions.UserStatusConfirmedException;
51 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
52 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
53 import org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote;
54 import org.mxchange.jusercore.model.user.LoginUser;
55 import org.mxchange.jusercore.model.user.User;
56 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
57 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
58 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
59 import org.mxchange.juserlogincore.container.login.UserLoginContainer;
60 import org.mxchange.juserlogincore.events.registration.ObservableUserRegisteredEvent;
61 import org.mxchange.juserlogincore.exceptions.UserPasswordRepeatMismatchException;
62 import org.mxchange.juserlogincore.utils.UserLoginUtils;
63 import org.mxchange.pizzaapplication.beans.BasePizzaBean;
64 import org.mxchange.pizzaapplication.beans.contact.PizzaAdminContactWebRequestController;
65 import org.mxchange.pizzaapplication.beans.contact.PizzaContactWebRequestController;
66 import org.mxchange.pizzaapplication.beans.localization.PizzaLocalizationSessionController;
69 * Administrative user bean (controller)
71 * @author Roland Häder<roland@mxchange.org>
73 @Named ("adminUserController")
75 public class PizzaAdminUserWebRequestBean extends BasePizzaBean implements PizzaAdminUserWebRequestController {
80 private static final long serialVersionUID = 542_145_356_001L;
83 * An event fired when the administrator has added a new user
87 private Event<ObservableAdminAddedUserEvent> addedUserEvent;
90 * Regular contact controller
93 private PizzaAdminContactWebRequestController adminContactController;
96 * Administrative user EJB
98 @EJB (lookup = "java:global/pizzaservice-ejb/adminUser!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote")
99 private AdminUserSessionBeanRemote adminUserBean;
105 private PizzaWebViewHelperController beanHelper;
110 private Contact contact;
113 * Regular contact controller
116 private PizzaContactWebRequestController contactController;
119 * Event being fired when administrator has deleted user
123 private Event<ObservableAdminDeletedUserEvent> deleteUserEvent;
126 * Localization controller
129 private PizzaLocalizationSessionController localizationController;
132 * An event fired when the administrator has updated a new user
136 private Event<ObservableAdminUpdatedUserDataEvent> updatedUserDataEvent;
141 @EJB (lookup = "java:global/pizzaservice-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote")
142 private UserSessionBeanRemote userBean;
145 * Regular user controller
148 private PizzaUserWebRequestController userController;
153 private String userDeleteReason;
156 * An event fired when the administrator has linked a user with existing
161 private Event<ObservableAdminLinkedUserEvent> userLinkedEvent;
166 private String userLockReason;
169 * Event being fired when an administrator has locked a user
173 private Event<ObservableAdminLockedUserEvent> userLockedEvent;
176 * Flag whether user must change password after login
178 private Boolean userMustChangePassword;
183 private String userName;
186 * User password (clear-text from web form)
188 private String userPassword;
191 * User password repeated (clear-text from web form)
193 private String userPasswordRepeat;
196 * Event being fired when administrator unlocks an account
200 private Event<ObservableAdminUnlockedUserEvent> userUnlockedEvent;
203 * Default constructor
205 public PizzaAdminUserWebRequestBean () {
206 // Call super constructor
211 * Adds user instance to database by preparing a complete user instance and
212 * sending it to the EJB. The data set in the controller is being verified,
213 * e.g. if the user name or email address is not used yet.
215 * @return Redirect outcome
217 public String addUser () {
218 // As the form cannot validate the data (required="true"), check it here
219 if (this.getUserName() == null) {
221 throw new NullPointerException("userName is null"); //NOI18N
222 } else if (this.getUserName().isEmpty()) {
224 throw new IllegalArgumentException("userName is null"); //NOI18N
225 } else if (this.getContact() == null) {
226 // No contact instance set, so test required fields: personal title, first name and family name
227 this.adminContactController.validateContactData();
230 // Create new user instance
231 final User newUser = new LoginUser();
233 // Set user name, CONFIRMED and INVISIBLE
234 newUser.setUserName(this.getUserName());
235 newUser.setUserMustChangePassword(this.getUserMustChangePassword());
236 newUser.setUserAccountStatus(UserAccountStatus.CONFIRMED);
237 newUser.setUserProfileMode(ProfileMode.INVISIBLE);
239 // Get locale from view-root
240 final Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
243 newUser.setUserLocale(locale);
248 // Is a contact instance in helper set?
249 if (this.getContact() instanceof Contact) {
250 // Then use it for contact linking
251 userContact = this.getContact();
253 // Create contact instance
254 userContact = this.contactController.createContactInstance();
257 // Set contact in user
258 newUser.setUserContact(userContact);
260 // Init variable for password
261 String password = null;
263 // Is the user name or email address used already?
264 // @TODO Add password length check
265 if ((this.featureController.isFeatureEnabled("user_login_require_user_name")) && (this.userListController.isUserNameRegistered(newUser))) {
266 // User name is already used
267 throw new FaceletException(new UserNameAlreadyRegisteredException(newUser));
268 } else if ((this.getContact() == null) && (this.contactController.isEmailAddressRegistered(newUser.getUserContact()))) {
269 // Email address is already used
270 this.showFacesMessage("admin_add_user:emailAddress", "ERROR_EMAIL_ADDRESS_ALREADY_USED"); //NOI18N
272 // Always clear password
273 this.setUserPassword(null);
274 this.setUserPasswordRepeat(null);
278 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
279 // Empty password entered, then generate one
280 password = UserLoginUtils.createRandomPassword(PizzaUserWebRequestController.MINIMUM_PASSWORD_LENGTH);
281 } else if (!this.isSamePasswordEntered()) {
282 // Both passwords don't match
283 throw new FaceletException(new UserPasswordRepeatMismatchException(newUser));
285 // Both match, so get it from this bean
286 password = this.getUserPassword();
289 // The password should not be null and at least 5 characters long
290 assert (password != null) : "password is null"; //NOI18N
291 assert (password.length() >= PizzaUserWebRequestController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
293 // Encrypt password and set it
294 newUser.setUserEncryptedPassword(UserLoginUtils.encryptPassword(password));
297 // Now, that all is set, call EJB
298 if (this.getContact() instanceof Contact) {
299 // Link contact with this user
300 final User updatedUser = this.adminUserBean.linkUser(newUser);
303 this.userLinkedEvent.fire(new AdminLinkedUserEvent(updatedUser));
306 final User updatedUser = this.adminUserBean.addUser(newUser);
309 this.addedUserEvent.fire(new AdminAddedUserEvent(updatedUser));
311 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
313 throw new FaceletException(ex);
316 // Now, that all is set, call EJB
317 if (this.getContact() instanceof Contact) {
319 this.userLinkedEvent.fire(new AdminLinkedUserEvent(updatedUser));
322 this.addedUserEvent.fire(new AdminAddedUserEvent(updatedUser));
326 this.setContact(null);
331 // Return to user list (for now)
332 return "admin_list_user"; //NOI18N
336 * Event observer for new user registrations
338 * @param event User registration event
340 public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
341 // event should not be null
344 throw new NullPointerException("event is null"); //NOI18N
345 } else if (event.getRegisteredUser() == null) {
347 throw new NullPointerException("event.user is null"); //NOI18N
348 } else if (event.getRegisteredUser().getUserId() == null) {
350 throw new NullPointerException("event.user.userId is null"); //NOI18N
351 } else if (event.getRegisteredUser().getUserId() < 1) {
353 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
357 final User registeredUser = event.getRegisteredUser();
359 // @TODO Nothing to do with the user here?
365 * Deletes given user account
367 * @return Redirect outcome
369 public String deleteUserData () {
371 final User user = this.beanHelper.getUser();
373 // Is the user instance valid and CONFIRMED?
376 throw new NullPointerException("user is null"); //NOI18N
377 } else if (user.getUserId() == null) {
379 throw new NullPointerException("user.userId is null"); //NOI18N
380 } else if (user.getUserId() < 1) {
382 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
386 // All fine, delete it
387 this.adminUserBean.deleteUser(user, this.getUserDeleteReason());
388 } catch (final UserNotFoundException ex) {
389 // Should not happen, so throw again
390 throw new FaceletException(ex);
394 this.deleteUserEvent.fire(new AdminDeletedUserEvent(this.getUser(), this.getUserDeleteReason()));
397 return "admin_list_user"; //NOI18N
401 * Edits currently loaded user's data in database.
403 * @return Redirect outcome
405 public String editUserData () {
407 final User user = this.beanHelper.getUser();
409 // Null password means not setting it
410 String encryptedPassword = null;
412 // Check if user instance is in helper and valid
415 throw new NullPointerException("beanHelper.user is null"); //NOI18N
416 } else if (user.getUserId() == null) {
418 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
419 } else if (user.getUserId() < 1) {
421 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N
422 } else if (this.getUserName() == null) {
423 // Not all required fields are set
424 throw new NullPointerException("userName is null"); //NOI18N
425 } else if (this.getUserName().isEmpty()) {
426 // Not all required fields are set
427 throw new IllegalArgumentException("userName is empty"); //NOI18N
428 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
429 // Clear password fields
430 this.setUserPassword(null);
431 this.setUserPasswordRepeat(null);
433 // Not same password entered
434 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT", FacesMessage.SEVERITY_INFO); //NOI18N
436 } else if ((!Objects.equals(user.getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
440 // User name already exists
441 this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS"); //NOI18N
443 } else if (this.isSamePasswordEntered()) {
444 // Same password entered, create container
445 if ((Objects.equals(user.getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserLoginUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword())))) {
446 // Clear password fields
447 this.setUserPassword(null);
448 this.setUserPasswordRepeat(null);
450 // Same password entered
451 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD"); //NOI18N
456 encryptedPassword = UserLoginUtils.encryptPassword(this.getUserPassword());
459 // Set user name and flag
460 user.setUserName(this.getUserName());
461 user.setUserMustChangePassword(this.getUserMustChangePassword());
463 // Is a password set?
464 if (encryptedPassword != null) {
466 user.setUserEncryptedPassword(encryptedPassword);
469 // Init updated User instance
470 final User updatedUser;
473 // Call EJB for updating user data
474 updatedUser = this.userBean.updateUserData(user);
475 } catch (final UserNotFoundException ex) {
477 throw new FacesException(ex);
481 this.updatedUserDataEvent.fire(new AdminUpdatedUserDataEvent(updatedUser));
483 // Return to user list (for now)
484 return "admin_list_user"; //NOI18N
488 * Getter for contact instance
490 * @return Contact instance
492 public Contact getContact () {
497 * Setter for contact instance
499 * @param contact Contact instance
501 public void setContact (final Contact contact) {
502 this.contact = contact;
506 * Getter for user delete reason
508 * @return User delete reason
510 public String getUserDeleteReason () {
511 return this.userDeleteReason;
515 * Setter for user delete reason
517 * @param userDeleteReason User delete reason
519 public void setUserDeleteReason (final String userDeleteReason) {
520 this.userDeleteReason = userDeleteReason;
524 * Getter for user lock reason
526 * @return User lock reason
528 public String getUserLockReason () {
529 return this.userLockReason;
533 * Setter for user lock reason
535 * @param userLockReason User lock reason
537 public void setUserLockReason (final String userLockReason) {
538 this.userLockReason = userLockReason;
542 * Getter for flag if user needs to change password
544 * @return Flag if user needs to change password
546 public Boolean getUserMustChangePassword () {
547 return this.userMustChangePassword;
551 * Setter for flag if user needs to change password
553 * @param userMustChangePassword Flag if user needs to change password
555 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
556 this.userMustChangePassword = userMustChangePassword;
560 * Getter for user name
564 public String getUserName () {
565 return this.userName;
569 * Setter for user name
571 * @param userName User name
573 public void setUserName (final String userName) {
574 this.userName = userName;
578 * Getter for clear-text user password
580 * @return Clear-text user password
582 public String getUserPassword () {
583 return this.userPassword;
587 * Setter for clear-text user password
589 * @param userPassword Clear-text user password
591 public void setUserPassword (final String userPassword) {
592 this.userPassword = userPassword;
596 * Getter for clear-text user password repeated
598 * @return Clear-text user password repeated
600 public String getUserPasswordRepeat () {
601 return this.userPasswordRepeat;
605 * Setter for clear-text user password repeated
607 * @param userPasswordRepeat Clear-text user password repeated
609 public void setUserPasswordRepeat (final String userPasswordRepeat) {
610 this.userPasswordRepeat = userPasswordRepeat;
614 * Locks selected user's account. This method makes sure that a lock reason
615 * is provided that th user later can read on login attempts.
617 * @return Redirect outcome
619 public String lockUserAccount () {
621 final User user = this.beanHelper.getUser();
623 // Is the user instance valid and CONFIRMED?
626 throw new NullPointerException("user is null"); //NOI18N
627 } else if (user.getUserId() == null) {
629 throw new NullPointerException("user.userId is null"); //NOI18N
630 } else if (user.getUserId() < 1) {
632 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
633 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
634 // User account is locked
635 throw new FacesException(new UserStatusLockedException(user));
636 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
637 // User account is locked
638 throw new FacesException(new UserStatusUnconfirmedException(user));
639 } else if (this.getUserLockReason() == null) {
641 throw new NullPointerException("userLockReason is null"); //NOI18N
642 } else if (this.getUserLockReason().isEmpty()) {
644 throw new IllegalArgumentException("userLockReason is empty"); //NOI18N
647 // Init updated user instance
648 final User updatedUser;
652 final String baseUrl = FacesUtils.generateBaseUrl();
654 // Call EJB to lock account
655 updatedUser = this.adminUserBean.lockUserAccount(user, this.getUserLockReason(), baseUrl);
656 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
658 throw new FaceletException(ex);
662 this.userLockedEvent.fire(new AdminLockedUserEvent(updatedUser));
667 // Should go fine at this point, redirect to user profile
668 return "admin_show_user"; //NOI18N
672 * Unlocks selected user's account. This method makes sure that the account
675 * @return Redirect outcome
677 public String unlockUserAccount () {
679 final User user = this.beanHelper.getUser();
681 // Is the user instance valid and CONFIRMED?
684 throw new NullPointerException("user is null"); //NOI18N
685 } else if (user.getUserId() == null) {
687 throw new NullPointerException("user.userId is null"); //NOI18N
688 } else if (user.getUserId() < 1) {
690 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
691 } else if (user.getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
692 // User account is locked
693 throw new FacesException(new UserStatusConfirmedException(user));
694 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
695 // User account is locked
696 throw new FacesException(new UserStatusUnconfirmedException(user));
699 // Init updated user instance
700 final User updatedUser;
704 final String baseUrl = FacesUtils.generateBaseUrl();
706 // Call EJB to unlock account
707 updatedUser = this.adminUserBean.unlockUserAccount(user, baseUrl);
708 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
710 throw new FaceletException(ex);
714 this.userUnlockedEvent.fire(new AdminUnlockedUserEvent(updatedUser));
719 // Should go fine at this point, redirect to user profile
720 return "admin_show_user"; //NOI18N
726 private void clear () {
728 this.setContact(null);
729 this.setUserDeleteReason(null);
730 this.setUserLockReason(null);
731 this.setUserMustChangePassword(null);
732 this.setUserName(null);
733 this.setUserPassword(null);
734 this.setUserPasswordRepeat(null);
735 this.setUserProfileMode(null);
740 * Creates a new user instance from all currently saved data from this bean
742 * @return New user instance
744 private User createUserInstance () {
745 // Init variable for password and contact
746 final String password;
747 final Contact userContact;
749 // Is a contact instance in helper set?
750 if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
751 // Empty password entered, then generate one
752 password = UserLoginUtils.createRandomPassword(PizzaUserWebRequestController.MINIMUM_PASSWORD_LENGTH);
753 } else if (!this.isSamePasswordEntered()) {
754 // Both passwords don't match
755 throw new FacesException(new UserPasswordRepeatMismatchException());
757 // Both match, so get it from this bean
758 password = this.getUserPassword();
761 // Is contact instance given? Else create one
762 if (this.getContact() instanceof Contact) {
763 // Then use it for contact linking
764 userContact = this.getContact();
766 // Create contact instance
767 userContact = this.contactController.createContactInstance();
770 // Create new instance
771 final User newUser = new LoginUser(
773 this.getUserProfileMode(),
774 this.getUserMustChangePassword(),
775 UserLoginUtils.encryptPassword(password),
776 UserAccountStatus.CONFIRMED,
780 // Get locale from view-root
781 final Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
784 newUser.setUserLocale(locale);
791 * Checks if same password is entered and that they are not empty.
793 * @return Whether the same password was entered
795 private boolean isSamePasswordEntered () {
796 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));