2 * Copyright (C) 2016 - 2022 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.helper.JobsWebViewHelperController;
39 import org.mxchange.jjobs.beans.user.list.JobsUserListWebViewController;
40 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
41 import org.mxchange.jusercore.events.user.add.ObservableAdminAddedUserEvent;
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.utils.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_356_001L;
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;
106 private JobsWebViewHelperController beanHelper;
111 private Contact contact;
114 * Regular contact controller
117 private JobsContactWebRequestController contactController;
120 * Event being fired when admin has deleted user
124 private Event<ObservableAdminDeletedUserEvent> deleteUserEvent;
127 * Features controller
130 private JobsFeaturesWebApplicationController featureController;
133 * An event fired when the administrator has updated a new user
137 private Event<ObservableAdminPostUserDataUpdatedEvent> updatedUserDataEvent;
142 @EJB (lookup = "java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote")
143 private UserSessionBeanRemote userBean;
146 * Regular user controller
149 private JobsUserWebRequestController userController;
154 private String userDeleteReason;
157 * An event fired when the administrator has linked a user with existing
162 private Event<ObservableAdminLinkedUserEvent> userLinkedEvent;
165 * Regular user controller
168 private JobsUserListWebViewController userListController;
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 * Whether the user wants a public profile
205 private ProfileMode userProfileMode;
208 * Event being fired when administrator unlocks an account
212 private Event<ObservableAdminUnlockedUserEvent> userUnlockedEvent;
215 * Default constructor
217 public JobsAdminUserWebRequestBean () {
218 // Call super constructor
223 * Adds user instance to database by preparing a complete user instance and
224 * sending it to the EJB. The data set in the controller is being verified,
225 * e.g. if the user name or email address is not used yet.
228 public void addUser () {
229 // As the form cannot validate the data (required="true"), check it here
230 if (this.getUserName() == null) {
232 throw new NullPointerException("userName is null"); //NOI18N
233 } else if (this.getUserName().isEmpty()) {
235 throw new IllegalArgumentException("userName is null"); //NOI18N
236 } else if (this.getContact() == null) {
237 // No contact instance set, so test required fields: personal title, first name and family name
238 this.adminContactController.validateContactData();
241 // Create new user instance
242 final User newUser = this.createUserInstance();
244 // Is the user name or email address used already?
245 // @TODO Add password length check
246 if ((this.featureController.isFeatureEnabled("user_login_require_user_name")) && (this.userListController.isUserNameRegistered(newUser))) {
247 // User name is already used
248 throw new FacesException(new UserNameAlreadyRegisteredException(newUser));
249 } else if ((this.getContact() == null) && (this.contactController.isEmailAddressRegistered(newUser.getUserContact()))) {
250 // Email address is already used
251 this.showFacesMessage("admin_add_user:emailAddress", "ERROR_EMAIL_ADDRESS_ALREADY_USED", FacesMessage.SEVERITY_WARN); //NOI18N
253 // Always clear password
254 this.setUserPassword(null);
255 this.setUserPasswordRepeat(null);
262 final User updatedUser;
265 // Now, that all is set, call EJB
266 if (this.getContact() instanceof Contact) {
267 // Link contact with this user
268 updatedUser = this.adminUserBean.linkUser(newUser);
271 updatedUser = this.adminUserBean.addUser(newUser);
273 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
275 throw new FacesException(ex);
278 // Now, that all is set, call EJB
279 if (this.getContact() instanceof Contact) {
281 this.userLinkedEvent.fire(new AdminLinkedUserEvent(updatedUser));
284 this.addedUserEvent.fire(new AdminAddedUserEvent(updatedUser));
287 this.setContact(null);
294 * Event observer for new user registrations
296 * @param event User registration event
298 public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
299 // Event and contained entity instance should not be null
302 throw new NullPointerException("event is null"); //NOI18N
303 } else if (event.getRegisteredUser() == null) {
305 throw new NullPointerException("event.user is null"); //NOI18N
306 } else if (event.getRegisteredUser().getUserId() == null) {
308 throw new NullPointerException("event.user.userId is null"); //NOI18N
309 } else if (event.getRegisteredUser().getUserId() < 1) {
311 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
315 final User registeredUser = event.getRegisteredUser();
317 // @TODO Nothing to do with the user here?
323 * Deletes given user account
325 public void deleteUserData () {
327 final User user = this.beanHelper.getUser();
329 // Is the user instance valid and CONFIRMED?
332 throw new NullPointerException("user is null"); //NOI18N
333 } else if (user.getUserId() == null) {
335 throw new NullPointerException("user.userId is null"); //NOI18N
336 } else if (user.getUserId() < 1) {
338 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
342 // All fine, delete it
343 this.adminUserBean.deleteUser(user, this.getUserDeleteReason());
344 } catch (final UserNotFoundException ex) {
345 // Should not happen, so throw again
346 throw new FacesException(ex);
350 this.deleteUserEvent.fire(new AdminDeletedUserEvent(user, this.getUserDeleteReason()));
354 * Edits currently loaded user's data in database.
356 public void editUserData () {
358 final User user = this.beanHelper.getUser();
360 // Null password means not setting it
361 String encryptedPassword = null;
363 // Check if user instance is in helper and valid
366 throw new NullPointerException("beanHelper.user is null"); //NOI18N
367 } else if (user.getUserId() == null) {
369 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
370 } else if (user.getUserId() < 1) {
372 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N
373 } else if (this.getUserName() == null) {
374 // Not all required fields are set
375 throw new NullPointerException("userName is null"); //NOI18N
376 } else if (this.getUserName().isEmpty()) {
377 // Not all required fields are set
378 throw new IllegalArgumentException("userName is empty"); //NOI18N
379 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
380 // Clear password fields
381 this.setUserPassword(null);
382 this.setUserPasswordRepeat(null);
384 // Not same password entered
385 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT", FacesMessage.SEVERITY_INFO); //NOI18N
387 } else if ((!Objects.equals(user.getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
391 // User name already exists
392 this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS", FacesMessage.SEVERITY_WARN); //NOI18N
394 } else if (this.isSamePasswordEntered()) {
395 // Same password entered, create container
396 if ((Objects.equals(user.getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserLoginUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword())))) {
397 // Clear password fields
398 this.setUserPassword(null);
399 this.setUserPasswordRepeat(null);
401 // Same password entered
402 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD", FacesMessage.SEVERITY_WARN); //NOI18N
407 encryptedPassword = UserLoginUtils.encryptPassword(this.getUserPassword());
410 // Set user name and flag
411 user.setUserName(this.getUserName());
412 user.setUserMustChangePassword(this.getUserMustChangePassword());
414 // Is a password set?
415 if (encryptedPassword != null) {
417 user.setUserEncryptedPassword(encryptedPassword);
420 // Init updated User instance
421 final User updatedUser;
424 // Call EJB for updating user data
425 updatedUser = this.userBean.updateUserData(user);
426 } catch (final UserNotFoundException ex) {
428 throw new FacesException(ex);
432 this.updatedUserDataEvent.fire(new AdminPostUserDataUpdatedEvent(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 delete reason
456 * @return User delete reason
458 public String getUserDeleteReason () {
459 return this.userDeleteReason;
463 * Setter for user delete reason
465 * @param userDeleteReason User delete reason
467 public void setUserDeleteReason (final String userDeleteReason) {
468 this.userDeleteReason = userDeleteReason;
472 * Getter for user lock reason
474 * @return User lock reason
476 public String getUserLockReason () {
477 return this.userLockReason;
481 * Setter for user lock reason
483 * @param userLockReason User lock reason
485 public void setUserLockReason (final String userLockReason) {
486 this.userLockReason = userLockReason;
490 * Getter for flag if user needs to change password
492 * @return Flag if user needs to change password
494 public Boolean getUserMustChangePassword () {
495 return this.userMustChangePassword;
499 * Setter for flag if user needs to change password
501 * @param userMustChangePassword Flag if user needs to change password
503 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
504 this.userMustChangePassword = userMustChangePassword;
508 * Getter for user name
512 public String getUserName () {
513 return this.userName;
517 * Setter for user name
519 * @param userName User name
521 public void setUserName (final String userName) {
522 this.userName = userName;
526 * Getter for clear-text user password
528 * @return Clear-text user password
530 public String getUserPassword () {
531 return this.userPassword;
535 * Setter for clear-text user password
537 * @param userPassword Clear-text user password
539 public void setUserPassword (final String userPassword) {
540 this.userPassword = userPassword;
544 * Getter for clear-text user password repeated
546 * @return Clear-text user password repeated
548 public String getUserPasswordRepeat () {
549 return this.userPasswordRepeat;
553 * Setter for clear-text user password repeated
555 * @param userPasswordRepeat Clear-text user password repeated
557 public void setUserPasswordRepeat (final String userPasswordRepeat) {
558 this.userPasswordRepeat = userPasswordRepeat;
562 * Getter for user profile mode
564 * @return User profile mode
566 public ProfileMode getUserProfileMode () {
567 return this.userProfileMode;
571 * Setter for user profile mode
573 * @param userProfileMode User profile mode
575 public void setUserProfileMode (final ProfileMode userProfileMode) {
576 this.userProfileMode = userProfileMode;
580 * Locks selected user's account. This method makes sure that a lock reason
581 * is provided that th user later can read on login attempts.
583 * @return Redirect outcome
585 public String lockUserAccount () {
587 final User user = this.beanHelper.getUser();
589 // Is the user instance valid and CONFIRMED?
592 throw new NullPointerException("user is null"); //NOI18N
593 } else if (user.getUserId() == null) {
595 throw new NullPointerException("user.userId is null"); //NOI18N
596 } else if (user.getUserId() < 1) {
598 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
599 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
600 // User account is locked
601 throw new FacesException(new UserStatusLockedException(user));
602 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
603 // User account is locked
604 throw new FacesException(new UserStatusUnconfirmedException(user));
605 } else if (this.getUserLockReason() == null) {
607 throw new NullPointerException("userLockReason is null"); //NOI18N
608 } else if (this.getUserLockReason().isEmpty()) {
610 throw new IllegalArgumentException("userLockReason is empty"); //NOI18N
613 // Init updated user instance
614 final User updatedUser;
618 final String baseUrl = FacesUtils.generateBaseUrl();
620 // Call EJB to lock account
621 updatedUser = this.adminUserBean.lockUserAccount(user, this.getUserLockReason(), baseUrl);
622 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
624 throw new FacesException(ex);
628 this.userLockedEvent.fire(new AdminLockedUserEvent(updatedUser));
633 // Should go fine at this point, redirect to user profile
634 return "admin_show_user"; //NOI18N
638 * Unlocks selected user's account. This method makes sure that the account
641 * @return Redirect outcome
643 public String unlockUserAccount () {
645 final User user = this.beanHelper.getUser();
647 // Is the user instance valid and CONFIRMED?
650 throw new NullPointerException("user is null"); //NOI18N
651 } else if (user.getUserId() == null) {
653 throw new NullPointerException("user.userId is null"); //NOI18N
654 } else if (user.getUserId() < 1) {
656 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
657 } else if (user.getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
658 // User account is locked
659 throw new FacesException(new UserStatusConfirmedException(user));
660 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
661 // User account is locked
662 throw new FacesException(new UserStatusUnconfirmedException(user));
665 // Init updated user instance
666 final User updatedUser;
670 final String baseUrl = FacesUtils.generateBaseUrl();
672 // Call EJB to unlock account
673 updatedUser = this.adminUserBean.unlockUserAccount(user, baseUrl);
674 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
676 throw new FacesException(ex);
680 this.userUnlockedEvent.fire(new AdminUnlockedUserEvent(updatedUser));
685 // Should go fine at this point, redirect to user profile
686 return "admin_show_user"; //NOI18N
692 private void clear () {
694 this.setContact(null);
695 this.setUserDeleteReason(null);
696 this.setUserLockReason(null);
697 this.setUserMustChangePassword(null);
698 this.setUserName(null);
699 this.setUserPassword(null);
700 this.setUserPasswordRepeat(null);
701 this.setUserProfileMode(null);
706 * Creates a new user instance from all currently saved data from this bean
708 * @return New user instance
710 private User createUserInstance () {
711 // Init variable for password and contact
712 final String password;
713 final Contact userContact;
715 // Is a contact instance in helper set?
716 if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
717 // Empty password entered, then generate one
718 password = UserLoginUtils.createRandomPassword(JobsUserWebRequestController.MINIMUM_PASSWORD_LENGTH);
719 } else if (!this.isSamePasswordEntered()) {
720 // Both passwords don't match
721 throw new FacesException(new UserPasswordRepeatMismatchException());
723 // Both match, so get it from this bean
724 password = this.getUserPassword();
727 // Is contact instance given? Else create one
728 if (this.getContact() instanceof Contact) {
729 // Then use it for contact linking
730 userContact = this.getContact();
732 // Create contact instance
733 userContact = this.contactController.createContactInstance();
736 // Create new instance
737 final User newUser = new LoginUser(
739 this.getUserProfileMode(),
740 this.getUserMustChangePassword(),
741 UserLoginUtils.encryptPassword(password),
742 UserAccountStatus.CONFIRMED,
746 // Get locale from view-root
747 final Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
750 newUser.setUserLocale(locale);
757 * Checks if same password is entered and that they are not empty.
759 * @return Whether the same password was entered
761 private boolean isSamePasswordEntered () {
762 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));