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;
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.jjobs.beans.BaseJobsBean;
35 import org.mxchange.jjobs.beans.contact.JobsAdminContactWebRequestController;
36 import org.mxchange.jjobs.beans.contact.JobsContactWebRequestController;
37 import org.mxchange.jjobs.beans.features.JobsFeaturesWebApplicationController;
38 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
39 import org.mxchange.jusercore.events.user.add.ObservableAdminAddedUserEvent;
40 import org.mxchange.jusercore.events.user.created.ObservableCreatedUserEvent;
41 import org.mxchange.jusercore.events.user.delete.AdminDeletedUserEvent;
42 import org.mxchange.jusercore.events.user.delete.ObservableAdminDeletedUserEvent;
43 import org.mxchange.jusercore.events.user.linked.AdminLinkedUserEvent;
44 import org.mxchange.jusercore.events.user.linked.ObservableAdminLinkedUserEvent;
45 import org.mxchange.jusercore.events.user.locked.AdminLockedUserEvent;
46 import org.mxchange.jusercore.events.user.locked.ObservableAdminLockedUserEvent;
47 import org.mxchange.jusercore.events.user.unlocked.AdminUnlockedUserEvent;
48 import org.mxchange.jusercore.events.user.unlocked.ObservableAdminUnlockedUserEvent;
49 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
50 import org.mxchange.jusercore.events.user.update.ObservableAdminUpdatedUserDataEvent;
51 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
52 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
53 import org.mxchange.jusercore.exceptions.UserNotFoundException;
54 import org.mxchange.jusercore.exceptions.UserStatusConfirmedException;
55 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
56 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
57 import org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote;
58 import org.mxchange.jusercore.model.user.LoginUser;
59 import org.mxchange.jusercore.model.user.User;
60 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
61 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
62 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
63 import org.mxchange.juserlogincore.container.login.UserLoginContainer;
64 import org.mxchange.juserlogincore.events.registration.ObservableUserRegisteredEvent;
65 import org.mxchange.juserlogincore.exceptions.UserPasswordRepeatMismatchException;
66 import org.mxchange.juserlogincore.login.UserLoginUtils;
69 * A user controller (bean)
71 * @author Roland Häder<roland@mxchange.org>
73 @Named ("adminUserController")
75 public class JobsAdminUserWebRequestBean extends BaseJobsBean implements JobsAdminUserWebRequestController {
80 private static final long serialVersionUID = 542_145_347_916L;
83 * An event fired when the administrator has added a new user
87 private Event<ObservableAdminAddedUserEvent> addedUserEvent;
90 * Regular contact controller
93 private JobsAdminContactWebRequestController adminContactController;
96 * Administrative user EJB
98 @EJB (lookup = "java:global/jjobs-ejb/adminUser!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote")
99 private AdminUserSessionBeanRemote adminUserBean;
104 private Contact contact;
107 * Regular contact controller
110 private JobsContactWebRequestController contactController;
113 * Event being fired when admin has deleted user
117 private Event<ObservableAdminDeletedUserEvent> deleteUserEvent;
120 * Features controller
123 private JobsFeaturesWebApplicationController featureController;
126 * An event fired when the administrator has updated a new user
130 private Event<ObservableAdminUpdatedUserDataEvent> updatedUserDataEvent;
140 @EJB (lookup = "java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote")
141 private UserSessionBeanRemote userBean;
144 * Regular user controller
147 private JobsUserWebRequestController userController;
152 private String userDeleteReason;
155 * An event fired when the administrator has linked a user with existing
160 private Event<ObservableAdminLinkedUserEvent> userLinkedEvent;
165 private String userLockReason;
168 * Event being fired when an administrator has locked a user
172 private Event<ObservableAdminLockedUserEvent> userLockedEvent;
175 * Flag whether user must change password after login
177 private Boolean userMustChangePassword;
182 private String userName;
185 * User password (clear-text from web form)
187 private String userPassword;
190 * User password repeated (clear-text from web form)
192 private String userPasswordRepeat;
195 * Whether the user wants a public profile
197 private ProfileMode userProfileMode;
200 * Event being fired when administrator unlocks an account
204 private Event<ObservableAdminUnlockedUserEvent> userUnlockedEvent;
207 * Default constructor
209 public JobsAdminUserWebRequestBean () {
210 // Call super constructor
215 * Adds user instance to database by preparing a complete user instance and
216 * sending it to the EJB. The data set in the controller is being verified,
217 * e.g. if the user name or email address is not used yet.
220 public void addUser () {
221 // As the form cannot validate the data (required="true"), check it here
222 if (this.getUserName() == null) {
224 throw new NullPointerException("userName is null"); //NOI18N
225 } else if (this.getUserName().isEmpty()) {
227 throw new IllegalArgumentException("userName is null"); //NOI18N
228 } else if (this.getContact() == null) {
229 // No contact instance set, so test required fields: gender, first name and family name
230 this.adminContactController.validateContactData();
233 // Create new user instance
234 final User newUser = this.createUserInstance();
236 // Is the user name or email address used already?
237 // @TODO Add password length check
238 if ((this.featureController.isFeatureEnabled("user_login_require_user_name")) && (this.userController.isUserNameRegistered(newUser))) {
239 // User name is already used
240 throw new FaceletException(new UserNameAlreadyRegisteredException(newUser));
241 } else if ((this.getContact() == null) && (this.contactController.isEmailAddressRegistered(newUser.getUserContact()))) {
242 // Email address is already used
243 this.showFacesMessage("admin_add_user:emailAddress", "ERROR_EMAIL_ADDRESS_ALREADY_USED"); //NOI18N
245 // Always clear password
246 this.setUserPassword(null);
247 this.setUserPasswordRepeat(null);
254 // Now, that all is set, call EJB
255 if (this.getContact() instanceof Contact) {
256 // Link contact with this user
257 final User updatedUser = this.adminUserBean.linkUser(newUser);
260 this.userLinkedEvent.fire(new AdminLinkedUserEvent(updatedUser));
263 final User updatedUser = this.adminUserBean.addUser(newUser);
266 this.addedUserEvent.fire(new AdminAddedUserEvent(updatedUser));
268 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
270 throw new FaceletException(ex);
274 this.setContact(null);
281 * Event observer for when a bean helper has successfully created a user
282 * instance, means the user exists. If the user does not exist, this event
283 * should not fire but instead a proper exception must be thrown.
285 * @param event User created event
287 public void afterCreatedUserEvent (@Observes final ObservableCreatedUserEvent event) {
288 // Is the instance valid?
291 throw new NullPointerException("event is null"); //NOI18N
292 } else if (event.getCreatedUser() == null) {
294 throw new NullPointerException("event.createdUser is null"); //NOI18N
295 } else if (event.getCreatedUser().getUserId() == null) {
297 throw new NullPointerException("event.createdUser.userId is null"); //NOI18N
298 } else if (event.getCreatedUser().getUserId() < 1) {
300 throw new NullPointerException(MessageFormat.format("event.createdUser.userId={0} is not valid", event.getCreatedUser().getUserId())); //NOI18N
304 this.setUser(event.getCreatedUser());
308 * Event observer for new user registrations
310 * @param event User registration event
312 public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
313 // event should not be null
316 throw new NullPointerException("event is null"); //NOI18N
317 } else if (event.getRegisteredUser() == null) {
319 throw new NullPointerException("event.user is null"); //NOI18N
320 } else if (event.getRegisteredUser().getUserId() == null) {
322 throw new NullPointerException("event.user.userId is null"); //NOI18N
323 } else if (event.getRegisteredUser().getUserId() < 1) {
325 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
329 final User registeredUser = event.getRegisteredUser();
331 // @TODO Nothing to do with the user here?
337 * Deletes given user account
339 public void deleteUserData () {
340 // Is the user instance valid and CONFIRMED?
341 if (this.getUser() == null) {
343 throw new NullPointerException("user is null"); //NOI18N
344 } else if (this.getUser().getUserId() == null) {
346 throw new NullPointerException("user.userId is null"); //NOI18N
347 } else if (this.getUser().getUserId() < 1) {
349 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
353 // All fine, delete it
354 this.adminUserBean.deleteUser(this.getUser(), this.getUserDeleteReason());
355 } catch (final UserNotFoundException ex) {
356 // Should not happen, so throw again
357 throw new FaceletException(ex);
361 this.deleteUserEvent.fire(new AdminDeletedUserEvent(this.getUser(), this.getUserDeleteReason()));
365 * Edits currently loaded user's data in database.
367 public void editUserData () {
368 // Null password means not setting it
369 String encryptedPassword = null;
371 // Check if user instance is in helper and valid
372 if (this.getUser() == null) {
374 throw new NullPointerException("beanHelper.user is null"); //NOI18N
375 } else if (this.getUser().getUserId() == null) {
377 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
378 } else if (this.getUser().getUserId() < 1) {
380 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", this.getUser().getUserId())); //NOI18N
381 } else if (this.getUserName() == null) {
382 // Not all required fields are set
383 throw new NullPointerException("this.userName is null"); //NOI18N
384 } else if (this.getUserName().isEmpty()) {
385 // Not all required fields are set
386 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
387 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
388 // Clear password fields
389 this.setUserPassword(null);
390 this.setUserPasswordRepeat(null);
392 // Not same password entered
393 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT"); //NOI18N
395 } else if ((!Objects.equals(this.getUser().getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
399 // User name already exists
400 this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS"); //NOI18N
402 } else if (this.isSamePasswordEntered()) {
403 // Same password entered, create container
404 if ((Objects.equals(this.getUser().getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserLoginUtils.ifPasswordMatches(new UserLoginContainer(this.getUser(), this.getUserPassword())))) {
405 // Clear password fields
406 this.setUserPassword(null);
407 this.setUserPasswordRepeat(null);
409 // Same password entered
410 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD"); //NOI18N
415 encryptedPassword = UserLoginUtils.encryptPassword(this.getUserPassword());
418 // Set user name and flag
419 this.getUser().setUserName(this.getUserName());
420 this.getUser().setUserMustChangePassword(this.getUserMustChangePassword());
422 // Is a password set?
423 if (encryptedPassword != null) {
425 this.getUser().setUserEncryptedPassword(encryptedPassword);
428 // Call EJB for updating user data
429 final User updatedUser = this.userBean.updateUserData(this.getUser());
432 this.updatedUserDataEvent.fire(new AdminUpdatedUserDataEvent(updatedUser));
436 * Getter for contact instance
438 * @return Contact instance
440 public Contact getContact () {
445 * Setter for contact instance
447 * @param contact Contact instance
449 public void setContact (final Contact contact) {
450 this.contact = contact;
454 * Getter for user instance
456 * @return User instance
458 public User getUser () {
463 * Setter for user instance
465 * @param user User instance
467 public void setUser (final User user) {
472 * Getter for user delete reason
474 * @return User delete reason
476 public String getUserDeleteReason () {
477 return this.userDeleteReason;
481 * Setter for user delete reason
483 * @param userDeleteReason User delete reason
485 public void setUserDeleteReason (final String userDeleteReason) {
486 this.userDeleteReason = userDeleteReason;
490 * Getter for user lock reason
492 * @return User lock reason
494 public String getUserLockReason () {
495 return this.userLockReason;
499 * Setter for user lock reason
501 * @param userLockReason User lock reason
503 public void setUserLockReason (final String userLockReason) {
504 this.userLockReason = userLockReason;
508 * Getter for flag if user needs to change password
510 * @return Flag if user needs to change password
512 public Boolean getUserMustChangePassword () {
513 return this.userMustChangePassword;
517 * Setter for flag if user needs to change password
519 * @param userMustChangePassword Flag if user needs to change password
521 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
522 this.userMustChangePassword = userMustChangePassword;
526 * Getter for user name
530 public String getUserName () {
531 return this.userName;
535 * Setter for user name
537 * @param userName User name
539 public void setUserName (final String userName) {
540 this.userName = userName;
544 * Getter for clear-text user password
546 * @return Clear-text user password
548 public String getUserPassword () {
549 return this.userPassword;
553 * Setter for clear-text user password
555 * @param userPassword Clear-text user password
557 public void setUserPassword (final String userPassword) {
558 this.userPassword = userPassword;
562 * Getter for clear-text user password repeated
564 * @return Clear-text user password repeated
566 public String getUserPasswordRepeat () {
567 return this.userPasswordRepeat;
571 * Setter for clear-text user password repeated
573 * @param userPasswordRepeat Clear-text user password repeated
575 public void setUserPasswordRepeat (final String userPasswordRepeat) {
576 this.userPasswordRepeat = userPasswordRepeat;
580 * Getter for user profile mode
582 * @return User profile mode
584 public ProfileMode getUserProfileMode () {
585 return this.userProfileMode;
589 * Setter for user profile mode
591 * @param userProfileMode User profile mode
593 public void setUserProfileMode (final ProfileMode userProfileMode) {
594 this.userProfileMode = userProfileMode;
598 * Locks selected user's account. This method makes sure that a lock reason
599 * is provided that th user later can read on login attempts.
601 * @return Redirect outcome
603 public String lockUserAccount () {
604 // Is the user instance valid and CONFIRMED?
605 if (this.getUser() == null) {
607 throw new NullPointerException("this.user is null"); //NOI18N
608 } else if (this.getUser().getUserId() == null) {
610 throw new NullPointerException("this.user.userId is null"); //NOI18N
611 } else if (this.getUser().getUserId() < 1) {
613 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
614 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.LOCKED) {
615 // User account is locked
616 throw new FacesException(new UserStatusLockedException(this.getUser()));
617 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
618 // User account is locked
619 throw new FaceletException(new UserStatusUnconfirmedException(this.getUser()));
620 } else if (this.getUserLockReason() == null) {
622 throw new NullPointerException("this.userLockReason is null"); //NOI18N
623 } else if (this.getUserLockReason().isEmpty()) {
625 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
628 // Init updated user instance
629 final User updatedUser;
633 final String baseUrl = FacesUtils.generateBaseUrl();
635 // Call EJB to lock account
636 updatedUser = this.adminUserBean.lockUserAccount(this.getUser(), this.getUserLockReason(), baseUrl);
637 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
639 throw new FaceletException(ex);
643 this.userLockedEvent.fire(new AdminLockedUserEvent(updatedUser));
648 // Should go fine at this point, redirect to user profile
649 return "admin_show_user"; //NOI18N
653 * Unlocks selected user's account. This method makes sure that the account
656 * @return Redirect outcome
658 public String unlockUserAccount () {
659 // Is the user instance valid and CONFIRMED?
660 if (this.getUser() == null) {
662 throw new NullPointerException("this.user is null"); //NOI18N
663 } else if (this.getUser().getUserId() == null) {
665 throw new NullPointerException("this.user.userId is null"); //NOI18N
666 } else if (this.getUser().getUserId() < 1) {
668 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
669 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
670 // User account is locked
671 throw new FacesException(new UserStatusConfirmedException(this.getUser()));
672 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
673 // User account is locked
674 throw new FaceletException(new UserStatusUnconfirmedException(this.getUser()));
677 // Init updated user instance
678 final User updatedUser;
682 final String baseUrl = FacesUtils.generateBaseUrl();
684 // Call EJB to unlock account
685 updatedUser = this.adminUserBean.unlockUserAccount(this.getUser(), baseUrl);
686 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
688 throw new FaceletException(ex);
692 this.userUnlockedEvent.fire(new AdminUnlockedUserEvent(updatedUser));
697 // Should go fine at this point, redirect to user profile
698 return "admin_show_user"; //NOI18N
704 private void clear () {
706 this.setContact(null);
707 this.setUserDeleteReason(null);
709 this.setUserLockReason(null);
710 this.setUserMustChangePassword(null);
711 this.setUserName(null);
712 this.setUserPassword(null);
713 this.setUserPasswordRepeat(null);
714 this.setUserProfileMode(null);
719 * Creates a new user instance from all currently saved data from this bean
721 * @return New user instance
723 private User createUserInstance () {
724 // Init variable for password
725 String password = null;
728 final Contact userContact;
730 // Is a contact instance in helper set?
731 if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
732 // Empty password entered, then generate one
733 password = UserLoginUtils.createRandomPassword(JobsUserWebRequestController.MINIMUM_PASSWORD_LENGTH);
734 } else if (!this.isSamePasswordEntered()) {
735 // Both passwords don't match
736 throw new FaceletException(new UserPasswordRepeatMismatchException());
738 // Both match, so get it from this bean
739 password = this.getUserPassword();
742 // The password should not be null and at least 5 characters long
743 assert (password != null) : "password is null"; //NOI18N
744 assert (password.length() >= JobsUserWebRequestController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
746 // Is contact instance given? Else create one
747 if (this.getContact() instanceof Contact) {
748 // Then use it for contact linking
749 userContact = this.getContact();
751 // Create contact instance
752 userContact = this.contactController.createContactInstance();
755 // Create new instance
756 final User newUser = new LoginUser(this.getUserName(), this.getUserProfileMode(), this.getUserMustChangePassword(), UserLoginUtils.encryptPassword(password), UserAccountStatus.CONFIRMED, userContact);
758 // Get locale from view-root
759 final Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
762 newUser.setUserLocale(locale);
769 * Checks if same password is entered and that they are not empty.
771 * @return Whether the same password was entered
773 private boolean isSamePasswordEntered () {
774 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));