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.application.FacesMessage;
29 import javax.faces.context.FacesContext;
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.jjobs.beans.user.list.JobsUserListWebViewController;
39 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
40 import org.mxchange.jusercore.events.user.add.ObservableAdminAddedUserEvent;
41 import org.mxchange.jusercore.events.user.created.ObservableCreatedUserEvent;
42 import org.mxchange.jusercore.events.user.delete.AdminDeletedUserEvent;
43 import org.mxchange.jusercore.events.user.delete.ObservableAdminDeletedUserEvent;
44 import org.mxchange.jusercore.events.user.linked.AdminLinkedUserEvent;
45 import org.mxchange.jusercore.events.user.linked.ObservableAdminLinkedUserEvent;
46 import org.mxchange.jusercore.events.user.locked.AdminLockedUserEvent;
47 import org.mxchange.jusercore.events.user.locked.ObservableAdminLockedUserEvent;
48 import org.mxchange.jusercore.events.user.unlocked.AdminUnlockedUserEvent;
49 import org.mxchange.jusercore.events.user.unlocked.ObservableAdminUnlockedUserEvent;
50 import org.mxchange.jusercore.events.user.update.post.AdminPostUserDataUpdatedEvent;
51 import org.mxchange.jusercore.events.user.update.post.ObservableAdminPostUserDataUpdatedEvent;
52 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
53 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
54 import org.mxchange.jusercore.exceptions.UserNotFoundException;
55 import org.mxchange.jusercore.exceptions.UserStatusConfirmedException;
56 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
57 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
58 import org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote;
59 import org.mxchange.jusercore.model.user.LoginUser;
60 import org.mxchange.jusercore.model.user.User;
61 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
62 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
63 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
64 import org.mxchange.juserlogincore.container.login.UserLoginContainer;
65 import org.mxchange.juserlogincore.events.registration.ObservableUserRegisteredEvent;
66 import org.mxchange.juserlogincore.exceptions.UserPasswordRepeatMismatchException;
67 import org.mxchange.juserlogincore.login.UserLoginUtils;
70 * A user controller (bean)
72 * @author Roland Häder<roland@mxchange.org>
74 @Named ("adminUserController")
76 public class JobsAdminUserWebRequestBean extends BaseJobsBean implements JobsAdminUserWebRequestController {
81 private static final long serialVersionUID = 542_145_347_916L;
84 * An event fired when the administrator has added a new user
88 private Event<ObservableAdminAddedUserEvent> addedUserEvent;
91 * Regular contact controller
94 private JobsAdminContactWebRequestController adminContactController;
97 * Administrative user EJB
99 @EJB (lookup = "java:global/jjobs-ejb/adminUser!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote")
100 private AdminUserSessionBeanRemote adminUserBean;
105 private Contact contact;
108 * Regular contact controller
111 private JobsContactWebRequestController contactController;
114 * Event being fired when admin has deleted user
118 private Event<ObservableAdminDeletedUserEvent> deleteUserEvent;
121 * Features controller
124 private JobsFeaturesWebApplicationController featureController;
127 * An event fired when the administrator has updated a new user
131 private Event<ObservableAdminPostUserDataUpdatedEvent> updatedUserDataEvent;
141 @EJB (lookup = "java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote")
142 private UserSessionBeanRemote userBean;
145 * Regular user controller
148 private JobsUserWebRequestController userController;
153 private String userDeleteReason;
156 * An event fired when the administrator has linked a user with existing
161 private Event<ObservableAdminLinkedUserEvent> userLinkedEvent;
164 * Regular user controller
167 private JobsUserListWebViewController userListController;
172 private String userLockReason;
175 * Event being fired when an administrator has locked a user
179 private Event<ObservableAdminLockedUserEvent> userLockedEvent;
182 * Flag whether user must change password after login
184 private Boolean userMustChangePassword;
189 private String userName;
192 * User password (clear-text from web form)
194 private String userPassword;
197 * User password repeated (clear-text from web form)
199 private String userPasswordRepeat;
202 * Whether the user wants a public profile
204 private ProfileMode userProfileMode;
207 * Event being fired when administrator unlocks an account
211 private Event<ObservableAdminUnlockedUserEvent> userUnlockedEvent;
214 * Default constructor
216 public JobsAdminUserWebRequestBean () {
217 // Call super constructor
222 * Adds user instance to database by preparing a complete user instance and
223 * sending it to the EJB. The data set in the controller is being verified,
224 * e.g. if the user name or email address is not used yet.
227 public void addUser () {
228 // As the form cannot validate the data (required="true"), check it here
229 if (this.getUserName() == null) {
231 throw new NullPointerException("userName is null"); //NOI18N
232 } else if (this.getUserName().isEmpty()) {
234 throw new IllegalArgumentException("userName is null"); //NOI18N
235 } else if (this.getContact() == null) {
236 // No contact instance set, so test required fields: gender, first name and family name
237 this.adminContactController.validateContactData();
240 // Create new user instance
241 final User newUser = this.createUserInstance();
243 // Is the user name or email address used already?
244 // @TODO Add password length check
245 if ((this.featureController.isFeatureEnabled("user_login_require_user_name")) && (this.userListController.isUserNameRegistered(newUser))) {
246 // User name is already used
247 throw new FacesException(new UserNameAlreadyRegisteredException(newUser));
248 } else if ((this.getContact() == null) && (this.contactController.isEmailAddressRegistered(newUser.getUserContact()))) {
249 // Email address is already used
250 this.showFacesMessage("admin_add_user:emailAddress", "ERROR_EMAIL_ADDRESS_ALREADY_USED", FacesMessage.SEVERITY_WARN); //NOI18N
252 // Always clear password
253 this.setUserPassword(null);
254 this.setUserPasswordRepeat(null);
261 final User updatedUser;
264 // Now, that all is set, call EJB
265 if (this.getContact() instanceof Contact) {
266 // Link contact with this user
267 updatedUser = this.adminUserBean.linkUser(newUser);
270 updatedUser = this.adminUserBean.addUser(newUser);
272 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
274 throw new FacesException(ex);
277 // Now, that all is set, call EJB
278 if (this.getContact() instanceof Contact) {
280 this.userLinkedEvent.fire(new AdminLinkedUserEvent(updatedUser));
283 this.addedUserEvent.fire(new AdminAddedUserEvent(updatedUser));
286 this.setContact(null);
293 * Event observer for when a bean helper has successfully created a user
294 * instance, means the user exists. If the user does not exist, this event
295 * should not fire but instead a proper exception must be thrown.
297 * @param event User created event
299 public void afterCreatedUserEvent (@Observes final ObservableCreatedUserEvent event) {
300 // Is the instance valid?
303 throw new NullPointerException("event is null"); //NOI18N
304 } else if (event.getCreatedUser() == null) {
306 throw new NullPointerException("event.createdUser is null"); //NOI18N
307 } else if (event.getCreatedUser().getUserId() == null) {
309 throw new NullPointerException("event.createdUser.userId is null"); //NOI18N
310 } else if (event.getCreatedUser().getUserId() < 1) {
312 throw new NullPointerException(MessageFormat.format("event.createdUser.userId={0} is not valid", event.getCreatedUser().getUserId())); //NOI18N
316 this.setUser(event.getCreatedUser());
320 * Event observer for new user registrations
322 * @param event User registration event
324 public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
325 // Event and contained entity instance should not be null
328 throw new NullPointerException("event is null"); //NOI18N
329 } else if (event.getRegisteredUser() == null) {
331 throw new NullPointerException("event.user is null"); //NOI18N
332 } else if (event.getRegisteredUser().getUserId() == null) {
334 throw new NullPointerException("event.user.userId is null"); //NOI18N
335 } else if (event.getRegisteredUser().getUserId() < 1) {
337 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
341 final User registeredUser = event.getRegisteredUser();
343 // @TODO Nothing to do with the user here?
349 * Deletes given user account
351 public void deleteUserData () {
352 // Is the user instance valid and CONFIRMED?
353 if (this.getUser() == null) {
355 throw new NullPointerException("user is null"); //NOI18N
356 } else if (this.getUser().getUserId() == null) {
358 throw new NullPointerException("user.userId is null"); //NOI18N
359 } else if (this.getUser().getUserId() < 1) {
361 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
365 // All fine, delete it
366 this.adminUserBean.deleteUser(this.getUser(), this.getUserDeleteReason());
367 } catch (final UserNotFoundException ex) {
368 // Should not happen, so throw again
369 throw new FacesException(ex);
373 this.deleteUserEvent.fire(new AdminDeletedUserEvent(this.getUser(), this.getUserDeleteReason()));
377 * Edits currently loaded user's data in database.
379 public void editUserData () {
380 // Null password means not setting it
381 String encryptedPassword = null;
383 // Check if user instance is in helper and valid
384 if (this.getUser() == null) {
386 throw new NullPointerException("beanHelper.user is null"); //NOI18N
387 } else if (this.getUser().getUserId() == null) {
389 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
390 } else if (this.getUser().getUserId() < 1) {
392 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", this.getUser().getUserId())); //NOI18N
393 } else if (this.getUserName() == null) {
394 // Not all required fields are set
395 throw new NullPointerException("this.userName is null"); //NOI18N
396 } else if (this.getUserName().isEmpty()) {
397 // Not all required fields are set
398 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
399 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
400 // Clear password fields
401 this.setUserPassword(null);
402 this.setUserPasswordRepeat(null);
404 // Not same password entered
405 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT", FacesMessage.SEVERITY_INFO); //NOI18N
407 } else if ((!Objects.equals(this.getUser().getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
411 // User name already exists
412 this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS", FacesMessage.SEVERITY_WARN); //NOI18N
414 } else if (this.isSamePasswordEntered()) {
415 // Same password entered, create container
416 if ((Objects.equals(this.getUser().getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserLoginUtils.ifPasswordMatches(new UserLoginContainer(this.getUser(), this.getUserPassword())))) {
417 // Clear password fields
418 this.setUserPassword(null);
419 this.setUserPasswordRepeat(null);
421 // Same password entered
422 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD", FacesMessage.SEVERITY_WARN); //NOI18N
427 encryptedPassword = UserLoginUtils.encryptPassword(this.getUserPassword());
430 // Set user name and flag
431 this.getUser().setUserName(this.getUserName());
432 this.getUser().setUserMustChangePassword(this.getUserMustChangePassword());
434 // Is a password set?
435 if (encryptedPassword != null) {
437 this.getUser().setUserEncryptedPassword(encryptedPassword);
440 // Call EJB for updating user data
441 final User updatedUser = this.userBean.updateUserData(this.getUser());
444 this.updatedUserDataEvent.fire(new AdminPostUserDataUpdatedEvent(updatedUser));
448 * Getter for contact instance
450 * @return Contact instance
452 public Contact getContact () {
457 * Setter for contact instance
459 * @param contact Contact instance
461 public void setContact (final Contact contact) {
462 this.contact = contact;
466 * Getter for user instance
468 * @return User instance
470 public User getUser () {
475 * Setter for user instance
477 * @param user User instance
479 public void setUser (final User user) {
484 * Getter for user delete reason
486 * @return User delete reason
488 public String getUserDeleteReason () {
489 return this.userDeleteReason;
493 * Setter for user delete reason
495 * @param userDeleteReason User delete reason
497 public void setUserDeleteReason (final String userDeleteReason) {
498 this.userDeleteReason = userDeleteReason;
502 * Getter for user lock reason
504 * @return User lock reason
506 public String getUserLockReason () {
507 return this.userLockReason;
511 * Setter for user lock reason
513 * @param userLockReason User lock reason
515 public void setUserLockReason (final String userLockReason) {
516 this.userLockReason = userLockReason;
520 * Getter for flag if user needs to change password
522 * @return Flag if user needs to change password
524 public Boolean getUserMustChangePassword () {
525 return this.userMustChangePassword;
529 * Setter for flag if user needs to change password
531 * @param userMustChangePassword Flag if user needs to change password
533 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
534 this.userMustChangePassword = userMustChangePassword;
538 * Getter for user name
542 public String getUserName () {
543 return this.userName;
547 * Setter for user name
549 * @param userName User name
551 public void setUserName (final String userName) {
552 this.userName = userName;
556 * Getter for clear-text user password
558 * @return Clear-text user password
560 public String getUserPassword () {
561 return this.userPassword;
565 * Setter for clear-text user password
567 * @param userPassword Clear-text user password
569 public void setUserPassword (final String userPassword) {
570 this.userPassword = userPassword;
574 * Getter for clear-text user password repeated
576 * @return Clear-text user password repeated
578 public String getUserPasswordRepeat () {
579 return this.userPasswordRepeat;
583 * Setter for clear-text user password repeated
585 * @param userPasswordRepeat Clear-text user password repeated
587 public void setUserPasswordRepeat (final String userPasswordRepeat) {
588 this.userPasswordRepeat = userPasswordRepeat;
592 * Getter for user profile mode
594 * @return User profile mode
596 public ProfileMode getUserProfileMode () {
597 return this.userProfileMode;
601 * Setter for user profile mode
603 * @param userProfileMode User profile mode
605 public void setUserProfileMode (final ProfileMode userProfileMode) {
606 this.userProfileMode = userProfileMode;
610 * Locks selected user's account. This method makes sure that a lock reason
611 * is provided that th user later can read on login attempts.
613 * @return Redirect outcome
615 public String lockUserAccount () {
616 // Is the user instance valid and CONFIRMED?
617 if (this.getUser() == null) {
619 throw new NullPointerException("this.user is null"); //NOI18N
620 } else if (this.getUser().getUserId() == null) {
622 throw new NullPointerException("this.user.userId is null"); //NOI18N
623 } else if (this.getUser().getUserId() < 1) {
625 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
626 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.LOCKED) {
627 // User account is locked
628 throw new FacesException(new UserStatusLockedException(this.getUser()));
629 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
630 // User account is locked
631 throw new FacesException(new UserStatusUnconfirmedException(this.getUser()));
632 } else if (this.getUserLockReason() == null) {
634 throw new NullPointerException("this.userLockReason is null"); //NOI18N
635 } else if (this.getUserLockReason().isEmpty()) {
637 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
640 // Init updated user instance
641 final User updatedUser;
645 final String baseUrl = FacesUtils.generateBaseUrl();
647 // Call EJB to lock account
648 updatedUser = this.adminUserBean.lockUserAccount(this.getUser(), this.getUserLockReason(), baseUrl);
649 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
651 throw new FacesException(ex);
655 this.userLockedEvent.fire(new AdminLockedUserEvent(updatedUser));
660 // Should go fine at this point, redirect to user profile
661 return "admin_show_user"; //NOI18N
665 * Unlocks selected user's account. This method makes sure that the account
668 * @return Redirect outcome
670 public String unlockUserAccount () {
671 // Is the user instance valid and CONFIRMED?
672 if (this.getUser() == null) {
674 throw new NullPointerException("this.user is null"); //NOI18N
675 } else if (this.getUser().getUserId() == null) {
677 throw new NullPointerException("this.user.userId is null"); //NOI18N
678 } else if (this.getUser().getUserId() < 1) {
680 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
681 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
682 // User account is locked
683 throw new FacesException(new UserStatusConfirmedException(this.getUser()));
684 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
685 // User account is locked
686 throw new FacesException(new UserStatusUnconfirmedException(this.getUser()));
689 // Init updated user instance
690 final User updatedUser;
694 final String baseUrl = FacesUtils.generateBaseUrl();
696 // Call EJB to unlock account
697 updatedUser = this.adminUserBean.unlockUserAccount(this.getUser(), baseUrl);
698 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
700 throw new FacesException(ex);
704 this.userUnlockedEvent.fire(new AdminUnlockedUserEvent(updatedUser));
709 // Should go fine at this point, redirect to user profile
710 return "admin_show_user"; //NOI18N
716 private void clear () {
718 this.setContact(null);
719 this.setUserDeleteReason(null);
721 this.setUserLockReason(null);
722 this.setUserMustChangePassword(null);
723 this.setUserName(null);
724 this.setUserPassword(null);
725 this.setUserPasswordRepeat(null);
726 this.setUserProfileMode(null);
731 * Creates a new user instance from all currently saved data from this bean
733 * @return New user instance
735 private User createUserInstance () {
736 // Init variable for password
737 String password = null;
740 final Contact userContact;
742 // Is a contact instance in helper set?
743 if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
744 // Empty password entered, then generate one
745 password = UserLoginUtils.createRandomPassword(JobsUserWebRequestController.MINIMUM_PASSWORD_LENGTH);
746 } else if (!this.isSamePasswordEntered()) {
747 // Both passwords don't match
748 throw new FacesException(new UserPasswordRepeatMismatchException());
750 // Both match, so get it from this bean
751 password = this.getUserPassword();
754 // The password should not be null and at least 5 characters long
755 assert (password != null) : "password is null"; //NOI18N
756 assert (password.length() >= JobsUserWebRequestController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
758 // Is contact instance given? Else create one
759 if (this.getContact() instanceof Contact) {
760 // Then use it for contact linking
761 userContact = this.getContact();
763 // Create contact instance
764 userContact = this.contactController.createContactInstance();
767 // Create new instance
768 final User newUser = new LoginUser(
770 this.getUserProfileMode(),
771 this.getUserMustChangePassword(),
772 UserLoginUtils.encryptPassword(password),
773 UserAccountStatus.CONFIRMED,
777 // Get locale from view-root
778 final Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
781 newUser.setUserLocale(locale);
788 * Checks if same password is entered and that they are not empty.
790 * @return Whether the same password was entered
792 private boolean isSamePasswordEntered () {
793 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));