2 * Copyright (C) 2016, 2017 Roland Häder
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;
22 import javax.annotation.PostConstruct;
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 javax.naming.Context;
33 import javax.naming.InitialContext;
34 import javax.naming.NamingException;
35 import org.mxchange.jcontacts.contact.Contact;
36 import org.mxchange.jcoreee.utils.FacesUtils;
37 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
38 import org.mxchange.jusercore.events.user.add.ObservableAdminAddedUserEvent;
39 import org.mxchange.jusercore.events.user.created.ObservableCreatedUserEvent;
40 import org.mxchange.jusercore.events.user.delete.AdminDeletedUserEvent;
41 import org.mxchange.jusercore.events.user.delete.ObservableAdminDeletedUserEvent;
42 import org.mxchange.jusercore.events.user.linked.AdminLinkedUserEvent;
43 import org.mxchange.jusercore.events.user.linked.ObservableAdminLinkedUserEvent;
44 import org.mxchange.jusercore.events.user.locked.AdminLockedUserEvent;
45 import org.mxchange.jusercore.events.user.locked.ObservableAdminLockedUserEvent;
46 import org.mxchange.jusercore.events.user.unlocked.AdminUnlockedUserEvent;
47 import org.mxchange.jusercore.events.user.unlocked.ObservableAdminUnlockedUserEvent;
48 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
49 import org.mxchange.jusercore.events.user.update.ObservableAdminUpdatedUserDataEvent;
50 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
51 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
52 import org.mxchange.jusercore.exceptions.UserNotFoundException;
53 import org.mxchange.jusercore.exceptions.UserStatusConfirmedException;
54 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
55 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
56 import org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote;
57 import org.mxchange.jusercore.model.user.LoginUser;
58 import org.mxchange.jusercore.model.user.User;
59 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
60 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
61 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
62 import org.mxchange.juserlogincore.container.login.UserLoginContainer;
63 import org.mxchange.juserlogincore.events.registration.ObservableUserRegisteredEvent;
64 import org.mxchange.juserlogincore.exceptions.UserPasswordRepeatMismatchException;
65 import org.mxchange.juserlogincore.login.UserLoginUtils;
66 import org.mxchange.pizzaapplication.beans.BasePizzaController;
67 import org.mxchange.pizzaapplication.beans.contact.PizzaAdminContactWebRequestController;
68 import org.mxchange.pizzaapplication.beans.contact.PizzaContactWebSessionController;
69 import org.mxchange.pizzaapplication.beans.helper.PizzaWebRequestHelperController;
70 import org.mxchange.pizzaapplication.beans.localization.PizzaLocalizationSessionController;
73 * Administrative user bean (controller)
75 * @author Roland Häder<roland@mxchange.org>
77 @Named ("adminUserController")
79 public class PizzaAdminUserWebRequestBean extends BasePizzaController implements PizzaAdminUserWebRequestController {
84 private static final long serialVersionUID = 542_145_347_916L;
87 * An event fired when the administrator has added a new user
91 private Event<ObservableAdminAddedUserEvent> addedUserEvent;
94 * Regular contact controller
97 private PizzaAdminContactWebRequestController adminContactController;
100 * Administrative user EJB
102 private AdminUserSessionBeanRemote adminUserBean;
108 private PizzaWebRequestHelperController beanHelper;
113 private Contact contact;
116 * Regular contact controller
119 private PizzaContactWebSessionController contactController;
122 * Event being fired when administrator has deleted user
126 private Event<ObservableAdminDeletedUserEvent> deleteUserEvent;
129 * Localization controller
132 private PizzaLocalizationSessionController localizationController;
135 * An event fired when the administrator has updated a new user
139 private Event<ObservableAdminUpdatedUserDataEvent> updatedUserDataEvent;
149 private UserSessionBeanRemote userBean;
152 * Regular user controller
155 private PizzaUserWebSessionController userController;
160 private String userDeleteReason;
163 * An event fired when the administrator has linked a user with existing
168 private Event<ObservableAdminLinkedUserEvent> userLinkedEvent;
173 private String userLockReason;
176 * Event being fired when an administrator has locked a user
180 private Event<ObservableAdminLockedUserEvent> userLockedEvent;
183 * Flag whether user must change password after login
185 private Boolean userMustChangePassword;
190 private String userName;
193 * User password (clear-text from web form)
195 private String userPassword;
198 * User password repeated (clear-text from web form)
200 private String userPasswordRepeat;
203 * Event being fired when administrator unlocks an account
207 private Event<ObservableAdminUnlockedUserEvent> userUnlockedEvent;
210 * Default constructor
212 public PizzaAdminUserWebRequestBean () {
213 // Call super constructor
218 * Adds user instance to database by preparing a complete user instance and
219 * sending it to the EJB. The data set in the controller is being verified,
220 * e.g. if the user name or email address is not used yet.
222 * @return Redirect outcome
224 public String addUser () {
225 // As the form cannot validate the data (required="true"), check it here
226 if (this.getUserName() == null) {
228 throw new NullPointerException("userName is null"); //NOI18N
229 } else if (this.getUserName().isEmpty()) {
231 throw new IllegalArgumentException("userName is null"); //NOI18N
232 } else if (this.getContact() == null) {
233 // No contact instance set, so test required fields: gender, first name and family name
234 this.adminContactController.validateContactData();
237 // Create new user instance
238 User newUser = new LoginUser();
240 // Set user name, CONFIRMED and INVISIBLE
241 newUser.setUserName(this.getUserName());
242 newUser.setUserMustChangePassword(this.getUserMustChangePassword());
243 newUser.setUserAccountStatus(UserAccountStatus.CONFIRMED);
244 newUser.setUserProfileMode(ProfileMode.INVISIBLE);
246 // Get locale from view-root
247 Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
250 newUser.setUserLocale(locale);
255 // Is a contact instance in helper set?
256 if (this.getContact() instanceof Contact) {
257 // Then use it for contact linking
258 userContact = this.getContact();
260 // Create contact instance
261 userContact = this.contactController.createContactInstance();
264 // Set contact in user
265 newUser.setUserContact(userContact);
267 // Init variable for password
268 String password = null;
270 // Is the user name or email address used already?
271 // @TODO Add password length check
272 if (this.userController.isUserNameRegistered(newUser)) {
273 // User name is already used
274 throw new FaceletException(new UserNameAlreadyRegisteredException(newUser));
275 } else if ((this.getContact() == null) && (this.contactController.isEmailAddressRegistered(newUser.getUserContact()))) {
276 // Email address is already used
277 this.showFacesMessage("admin_add_user:emailAddress", "ERROR_EMAIL_ADDRESS_ALREADY_USED"); //NOI18N
279 // Always clear password
280 this.setUserPassword(null);
281 this.setUserPasswordRepeat(null);
285 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
286 // Empty password entered, then generate one
287 password = UserLoginUtils.createRandomPassword(PizzaUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
288 } else if (!this.isSamePasswordEntered()) {
289 // Both passwords don't match
290 throw new FaceletException(new UserPasswordRepeatMismatchException(newUser));
292 // Both match, so get it from this bean
293 password = this.getUserPassword();
296 // The password should not be null and at least 5 characters long
297 assert (password != null) : "password is null"; //NOI18N
298 assert (password.length() >= PizzaUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
300 // Encrypt password and set it
301 newUser.setUserEncryptedPassword(UserLoginUtils.encryptPassword(password));
304 // Now, that all is set, call EJB
305 if (this.getContact() instanceof Contact) {
306 // Link contact with this user
307 User updatedUser = this.adminUserBean.linkUser(newUser);
310 this.userLinkedEvent.fire(new AdminLinkedUserEvent(updatedUser));
313 User updatedUser = this.adminUserBean.addUser(newUser);
316 this.addedUserEvent.fire(new AdminAddedUserEvent(updatedUser));
318 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
320 throw new FaceletException(ex);
324 this.setContact(null);
329 // Return to user list (for now)
330 return "admin_list_user"; //NOI18N
334 * Event observer for when a bean helper has successfully created a user
335 * instance, means the user exists. If the user does not exist, this event
336 * should not fire but instead a proper exception must be thrown.
338 * @param event User created event
340 public void afterCreatedUserEvent (@Observes final ObservableCreatedUserEvent event) {
341 // Is the instance valid?
344 throw new NullPointerException("event is null"); //NOI18N
345 } else if (event.getCreatedUser() == null) {
347 throw new NullPointerException("event.createdUser is null"); //NOI18N
348 } else if (event.getCreatedUser().getUserId() == null) {
350 throw new NullPointerException("event.createdUser.userId is null"); //NOI18N
351 } else if (event.getCreatedUser().getUserId() < 1) {
353 throw new NullPointerException(MessageFormat.format("event.createdUser.userId={0} is not valid", event.getCreatedUser().getUserId())); //NOI18N
357 this.setUser(event.getCreatedUser());
361 * Event observer for new user registrations
363 * @param event User registration event
365 public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
366 // event should not be null
369 throw new NullPointerException("event is null"); //NOI18N
370 } else if (event.getRegisteredUser() == null) {
372 throw new NullPointerException("event.user is null"); //NOI18N
373 } else if (event.getRegisteredUser().getUserId() == null) {
375 throw new NullPointerException("event.user.userId is null"); //NOI18N
376 } else if (event.getRegisteredUser().getUserId() < 1) {
378 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
382 User registeredUser = event.getRegisteredUser();
384 // @TODO Nothing to do with the user here?
390 * Deletes given user account
392 * @return Redirect outcome
394 public String deleteUserData () {
395 // Is the user instance valid and CONFIRMED?
396 if (this.getUser() == null) {
398 throw new NullPointerException("user is null"); //NOI18N
399 } else if (this.getUser().getUserId() == null) {
401 throw new NullPointerException("user.userId is null"); //NOI18N
402 } else if (this.getUser().getUserId() < 1) {
404 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
408 // All fine, delete it
409 this.adminUserBean.deleteUser(this.getUser(), this.getUserDeleteReason());
410 } catch (final UserNotFoundException ex) {
411 // Should not happen, so throw again
412 throw new FaceletException(ex);
416 this.deleteUserEvent.fire(new AdminDeletedUserEvent(this.getUser(), this.getUserDeleteReason()));
419 return "admin_list_user"; //NOI18N
423 * Edits currently loaded user's data in database.
425 * @return Redirect outcome
427 public String editUserData () {
428 // Null password means not setting it
429 String encryptedPassword = null;
431 // Check if user instance is in helper and valid
432 if (this.getUser() == null) {
434 throw new NullPointerException("beanHelper.user is null"); //NOI18N
435 } else if (this.getUser().getUserId() == null) {
437 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
438 } else if (this.getUser().getUserId() < 1) {
440 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", this.getUser().getUserId())); //NOI18N
441 } else if (this.getUserName() == null) {
442 // Not all required fields are set
443 throw new NullPointerException("this.userName is null"); //NOI18N
444 } else if (this.getUserName().isEmpty()) {
445 // Not all required fields are set
446 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
447 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
448 // Clear password fields
449 this.setUserPassword(null);
450 this.setUserPasswordRepeat(null);
452 // Not same password entered
453 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT"); //NOI18N
455 } else if ((!Objects.equals(this.getUser().getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
459 // User name already exists
460 this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS"); //NOI18N
462 } else if (this.isSamePasswordEntered()) {
463 // Same password entered, create container
464 if ((Objects.equals(this.getUser().getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserLoginUtils.ifPasswordMatches(new UserLoginContainer(this.getUser(), this.getUserPassword())))) {
465 // Clear password fields
466 this.setUserPassword(null);
467 this.setUserPasswordRepeat(null);
469 // Same password entered
470 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD"); //NOI18N
475 encryptedPassword = UserLoginUtils.encryptPassword(this.getUserPassword());
478 // Set user name and flag
479 this.getUser().setUserName(this.getUserName());
480 this.getUser().setUserMustChangePassword(this.getUserMustChangePassword());
482 // Is a password set?
483 if (encryptedPassword != null) {
485 this.getUser().setUserEncryptedPassword(encryptedPassword);
488 // Call EJB for updating user data
489 User updatedUser = this.userBean.updateUserData(this.getUser());
492 this.updatedUserDataEvent.fire(new AdminUpdatedUserDataEvent(updatedUser));
494 // Return to user list (for now)
495 return "admin_list_user"; //NOI18N
499 * Getter for contact instance
501 * @return Contact instance
503 public Contact getContact () {
508 * Setter for contact instance
510 * @param contact Contact instance
512 public void setContact (final Contact contact) {
513 this.contact = contact;
517 * Getter for user instance
519 * @return User instance
521 public User getUser () {
526 * Setter for user instance
528 * @param user User instance
530 public void setUser (final User user) {
535 * Getter for user delete reason
537 * @return User delete reason
539 public String getUserDeleteReason () {
540 return this.userDeleteReason;
544 * Setter for user delete reason
546 * @param userDeleteReason User delete reason
548 public void setUserDeleteReason (final String userDeleteReason) {
549 this.userDeleteReason = userDeleteReason;
553 * Getter for user lock reason
555 * @return User lock reason
557 public String getUserLockReason () {
558 return this.userLockReason;
562 * Setter for user lock reason
564 * @param userLockReason User lock reason
566 public void setUserLockReason (final String userLockReason) {
567 this.userLockReason = userLockReason;
571 * Getter for flag if user needs to change password
573 * @return Flag if user needs to change password
575 public Boolean getUserMustChangePassword () {
576 return this.userMustChangePassword;
580 * Setter for flag if user needs to change password
582 * @param userMustChangePassword Flag if user needs to change password
584 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
585 this.userMustChangePassword = userMustChangePassword;
589 * Getter for user name
593 public String getUserName () {
594 return this.userName;
598 * Setter for user name
600 * @param userName User name
602 public void setUserName (final String userName) {
603 this.userName = userName;
607 * Getter for clear-text user password
609 * @return Clear-text user password
611 public String getUserPassword () {
612 return this.userPassword;
616 * Setter for clear-text user password
618 * @param userPassword Clear-text user password
620 public void setUserPassword (final String userPassword) {
621 this.userPassword = userPassword;
625 * Getter for clear-text user password repeated
627 * @return Clear-text user password repeated
629 public String getUserPasswordRepeat () {
630 return this.userPasswordRepeat;
634 * Setter for clear-text user password repeated
636 * @param userPasswordRepeat Clear-text user password repeated
638 public void setUserPasswordRepeat (final String userPasswordRepeat) {
639 this.userPasswordRepeat = userPasswordRepeat;
643 * Post-construction method
646 public void init () {
649 // Get initial context
650 Context context = new InitialContext();
653 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/pizzaservice-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
654 this.adminUserBean = (AdminUserSessionBeanRemote) context.lookup("java:global/pizzaservice-ejb/adminUser!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote"); //NOI18N
655 } catch (final NamingException e) {
657 throw new FaceletException(e);
662 * Locks selected user's account. This method makes sure that a lock reason
663 * is provided that th user later can read on login attempts.
665 * @return Redirect outcome
667 public String lockUserAccount () {
668 // Is the user instance valid and CONFIRMED?
669 if (this.getUser() == null) {
671 throw new NullPointerException("this.user is null"); //NOI18N
672 } else if (this.getUser().getUserId() == null) {
674 throw new NullPointerException("this.user.userId is null"); //NOI18N
675 } else if (this.getUser().getUserId() < 1) {
677 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
678 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.LOCKED) {
679 // User account is locked
680 throw new FacesException(new UserStatusLockedException(this.getUser()));
681 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
682 // User account is locked
683 throw new FaceletException(new UserStatusUnconfirmedException(this.getUser()));
684 } else if (this.getUserLockReason() == null) {
686 throw new NullPointerException("this.userLockReason is null"); //NOI18N
687 } else if (this.getUserLockReason().isEmpty()) {
689 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
692 // Init updated user instance
697 String baseUrl = FacesUtils.generateBaseUrl();
699 // Call EJB to lock account
700 updatedUser = this.adminUserBean.lockUserAccount(this.getUser(), this.getUserLockReason(), baseUrl);
701 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
703 throw new FaceletException(ex);
707 this.userLockedEvent.fire(new AdminLockedUserEvent(updatedUser));
712 // Should go fine at this point, redirect to user profile
713 return "admin_show_user"; //NOI18N
717 * Unlocks selected user's account. This method makes sure that the account
720 * @return Redirect outcome
722 public String unlockUserAccount () {
723 // Is the user instance valid and CONFIRMED?
724 if (this.getUser() == null) {
726 throw new NullPointerException("this.user is null"); //NOI18N
727 } else if (this.getUser().getUserId() == null) {
729 throw new NullPointerException("this.user.userId is null"); //NOI18N
730 } else if (this.getUser().getUserId() < 1) {
732 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
733 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
734 // User account is locked
735 throw new FacesException(new UserStatusConfirmedException(this.getUser()));
736 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
737 // User account is locked
738 throw new FaceletException(new UserStatusUnconfirmedException(this.getUser()));
741 // Init updated user instance
746 String baseUrl = FacesUtils.generateBaseUrl();
748 // Call EJB to unlock account
749 updatedUser = this.adminUserBean.unlockUserAccount(this.getUser(), baseUrl);
750 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
752 throw new FaceletException(ex);
756 this.userUnlockedEvent.fire(new AdminUnlockedUserEvent(updatedUser));
761 // Should go fine at this point, redirect to user profile
762 return "admin_show_user"; //NOI18N
768 private void clear () {
770 this.setContact(null);
771 this.setUserLockReason(null);
772 this.setUserMustChangePassword(null);
773 this.setUserName(null);
777 * Checks if same password is entered and that they are not empty.
779 * @return Whether the same password was entered
781 private boolean isSamePasswordEntered () {
782 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));