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.jfinancials.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.jfinancials.beans.BaseFinancialsBean;
35 import org.mxchange.jfinancials.beans.contact.FinancialsAdminContactWebRequestController;
36 import org.mxchange.jfinancials.beans.contact.FinancialsContactWebRequestController;
37 import org.mxchange.jfinancials.beans.features.FinancialsFeaturesWebApplicationController;
38 import org.mxchange.jfinancials.beans.helper.FinancialsWebViewHelperController;
39 import org.mxchange.jfinancials.beans.user.list.FinancialsUserListWebViewController;
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 bean (controller)
72 * @author Roland Häder<roland@mxchange.org>
74 @Named ("adminUserController")
76 public class FinancialsAdminUserWebRequestBean extends BaseFinancialsBean implements FinancialsAdminUserWebRequestController {
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 FinancialsAdminContactWebRequestController adminContactController;
97 * Administrative user EJB
99 @EJB (lookup = "java:global/jfinancials-ejb/adminUser!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote")
100 private AdminUserSessionBeanRemote adminUserBean;
106 private FinancialsWebViewHelperController beanHelper;
111 private Contact contact;
114 * Regular contact controller
117 private FinancialsContactWebRequestController contactController;
120 * Event being fired when administrator has deleted user
124 private Event<ObservableAdminDeletedUserEvent> deleteUserEvent;
127 * Features controller
130 private FinancialsFeaturesWebApplicationController featureController;
133 * An event fired when the administrator has updated a new user
137 private Event<ObservableAdminPostUserDataUpdatedEvent> updatedUserDataEvent;
142 @EJB (lookup = "java:global/jfinancials-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote")
143 private UserSessionBeanRemote userBean;
148 private String userDeleteReason;
151 * An event fired when the administrator has linked a user with existing
156 private Event<ObservableAdminLinkedUserEvent> userLinkedEvent;
159 * Regular user controller
162 private FinancialsUserListWebViewController userListController;
167 private String userLockReason;
170 * Event being fired when an administrator has locked a user
174 private Event<ObservableAdminLockedUserEvent> userLockedEvent;
177 * Flag whether user must change password after login
179 private Boolean userMustChangePassword;
184 private String userName;
187 * User password (clear-text from web form)
189 private String userPassword;
192 * User password repeated (clear-text from web form)
194 private String userPasswordRepeat;
197 * Whether the user wants a public profile
199 private ProfileMode userProfileMode;
202 * Event being fired when administrator unlocks an account
206 private Event<ObservableAdminUnlockedUserEvent> userUnlockedEvent;
209 * Default constructor
211 public FinancialsAdminUserWebRequestBean () {
212 // Call super constructor
217 * Adds user instance to database by preparing a complete user instance and
218 * sending it to the EJB. The data set in the controller is being verified,
219 * e.g. if the user name or email address is not used yet.
222 public void addUser () {
223 // As the form cannot validate the data (required="true"), check it here
224 if (this.getUserName() == null) {
226 throw new NullPointerException("userName is null"); //NOI18N
227 } else if (this.getUserName().isEmpty()) {
229 throw new IllegalArgumentException("userName is null"); //NOI18N
230 } else if (this.getContact() == null) {
231 // No contact instance set, so test required fields: personal title, first name and family name
232 this.adminContactController.validateContactData();
235 // Create new user instance
236 final User newUser = this.createUserInstance();
238 // Is the user name or email address used already?
239 // @TODO Add password length check
240 if ((this.featureController.isFeatureEnabled("user_login_require_user_name")) && (this.userListController.isUserNameRegistered(newUser))) {
241 // User name is already used
242 throw new FacesException(new UserNameAlreadyRegisteredException(newUser));
243 } else if ((this.getContact() == null) && (this.contactController.isEmailAddressRegistered(newUser.getUserContact()))) {
244 // Email address is already used
245 this.showFacesMessage("admin_add_user:emailAddress", "ERROR_EMAIL_ADDRESS_ALREADY_USED", FacesMessage.SEVERITY_WARN); //NOI18N
247 // Always clear password
248 this.setUserPassword(null);
249 this.setUserPasswordRepeat(null);
256 final User updatedUser;
259 // Now, that all is set, call EJB
260 if (this.getContact() instanceof Contact) {
261 // Link contact with this user
262 updatedUser = this.adminUserBean.linkUser(newUser);
265 updatedUser = this.adminUserBean.addUser(newUser);
267 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
269 throw new FacesException(ex);
272 // Now, that all is set, call EJB
273 if (this.getContact() instanceof Contact) {
275 this.userLinkedEvent.fire(new AdminLinkedUserEvent(updatedUser));
278 this.addedUserEvent.fire(new AdminAddedUserEvent(updatedUser));
281 this.setContact(null);
288 * Event observer for new user registrations
290 * @param event User registration event
292 public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
293 // Event and contained entity instance should not be null
296 throw new NullPointerException("event is null"); //NOI18N
297 } else if (event.getRegisteredUser() == null) {
299 throw new NullPointerException("event.user is null"); //NOI18N
300 } else if (event.getRegisteredUser().getUserId() == null) {
302 throw new NullPointerException("event.user.userId is null"); //NOI18N
303 } else if (event.getRegisteredUser().getUserId() < 1) {
305 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
309 final User registeredUser = event.getRegisteredUser();
311 // @TODO Nothing to do with the user here?
317 * Deletes given user account
319 public void deleteUserData () {
321 final User user = this.beanHelper.getUser();
323 // Is the user instance valid and CONFIRMED?
326 throw new NullPointerException("user is null"); //NOI18N
327 } else if (user.getUserId() == null) {
329 throw new NullPointerException("user.userId is null"); //NOI18N
330 } else if (user.getUserId() < 1) {
332 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
336 // All fine, delete it
337 this.adminUserBean.deleteUser(user, this.getUserDeleteReason());
338 } catch (final UserNotFoundException ex) {
339 // Should not happen, so throw again
340 throw new FacesException(ex);
344 this.deleteUserEvent.fire(new AdminDeletedUserEvent(user, this.getUserDeleteReason()));
348 * Edits currently loaded user's data in database.
350 public void editUserData () {
352 final User user = this.beanHelper.getUser();
354 // Null password means not setting it
355 String encryptedPassword = null;
357 // Check if user instance is in helper and valid
360 throw new NullPointerException("beanHelper.user is null"); //NOI18N
361 } else if (user.getUserId() == null) {
363 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
364 } else if (user.getUserId() < 1) {
366 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N
367 } else if (this.getUserName() == null) {
368 // Not all required fields are set
369 throw new NullPointerException("userName is null"); //NOI18N
370 } else if (this.getUserName().isEmpty()) {
371 // Not all required fields are set
372 throw new IllegalArgumentException("userName is empty"); //NOI18N
373 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
374 // Clear password fields
375 this.setUserPassword(null);
376 this.setUserPasswordRepeat(null);
378 // Not same password entered
379 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT", FacesMessage.SEVERITY_INFO); //NOI18N
381 } else if ((!Objects.equals(user.getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
385 // User name already exists
386 this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS", FacesMessage.SEVERITY_WARN); //NOI18N
388 } else if (this.isSamePasswordEntered()) {
389 // Same password entered, create container
390 if ((Objects.equals(user.getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserLoginUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword())))) {
391 // Clear password fields
392 this.setUserPassword(null);
393 this.setUserPasswordRepeat(null);
395 // Same password entered
396 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD", FacesMessage.SEVERITY_WARN); //NOI18N
401 encryptedPassword = UserLoginUtils.encryptPassword(this.getUserPassword());
404 // Set user name and flag
405 user.setUserName(this.getUserName());
406 user.setUserMustChangePassword(this.getUserMustChangePassword());
408 // Is a password set?
409 if (encryptedPassword != null) {
411 user.setUserEncryptedPassword(encryptedPassword);
414 // Init updated User instance
415 final User updatedUser;
418 // Call EJB for updating user data
419 updatedUser = this.userBean.updateUserData(user);
420 } catch (final UserNotFoundException ex) {
422 throw new FacesException(ex);
426 this.updatedUserDataEvent.fire(new AdminPostUserDataUpdatedEvent(updatedUser));
430 * Getter for contact instance
432 * @return Contact instance
434 public Contact getContact () {
439 * Setter for contact instance
441 * @param contact Contact instance
443 public void setContact (final Contact contact) {
444 this.contact = contact;
448 * Getter for user delete reason
450 * @return User delete reason
452 public String getUserDeleteReason () {
453 return this.userDeleteReason;
457 * Setter for user delete reason
459 * @param userDeleteReason User delete reason
461 public void setUserDeleteReason (final String userDeleteReason) {
462 this.userDeleteReason = userDeleteReason;
466 * Getter for user lock reason
468 * @return User lock reason
470 public String getUserLockReason () {
471 return this.userLockReason;
475 * Setter for user lock reason
477 * @param userLockReason User lock reason
479 public void setUserLockReason (final String userLockReason) {
480 this.userLockReason = userLockReason;
484 * Getter for flag if user needs to change password
486 * @return Flag if user needs to change password
488 public Boolean getUserMustChangePassword () {
489 return this.userMustChangePassword;
493 * Setter for flag if user needs to change password
495 * @param userMustChangePassword Flag if user needs to change password
497 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
498 this.userMustChangePassword = userMustChangePassword;
502 * Getter for user name
506 public String getUserName () {
507 return this.userName;
511 * Setter for user name
513 * @param userName User name
515 public void setUserName (final String userName) {
516 this.userName = userName;
520 * Getter for clear-text user password
522 * @return Clear-text user password
524 public String getUserPassword () {
525 return this.userPassword;
529 * Setter for clear-text user password
531 * @param userPassword Clear-text user password
533 public void setUserPassword (final String userPassword) {
534 this.userPassword = userPassword;
538 * Getter for clear-text user password repeated
540 * @return Clear-text user password repeated
542 public String getUserPasswordRepeat () {
543 return this.userPasswordRepeat;
547 * Setter for clear-text user password repeated
549 * @param userPasswordRepeat Clear-text user password repeated
551 public void setUserPasswordRepeat (final String userPasswordRepeat) {
552 this.userPasswordRepeat = userPasswordRepeat;
556 * Getter for user profile mode
558 * @return User profile mode
560 public ProfileMode getUserProfileMode () {
561 return this.userProfileMode;
565 * Setter for user profile mode
567 * @param userProfileMode User profile mode
569 public void setUserProfileMode (final ProfileMode userProfileMode) {
570 this.userProfileMode = userProfileMode;
574 * Locks selected user's account. This method makes sure that a lock reason
575 * is provided that th user later can read on login attempts.
577 * @return Redirect outcome
579 public String lockUserAccount () {
581 final User user = this.beanHelper.getUser();
583 // Is the user instance valid and CONFIRMED?
586 throw new NullPointerException("user is null"); //NOI18N
587 } else if (user.getUserId() == null) {
589 throw new NullPointerException("user.userId is null"); //NOI18N
590 } else if (user.getUserId() < 1) {
592 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
593 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
594 // User account is locked
595 throw new FacesException(new UserStatusLockedException(user));
596 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
597 // User account is locked
598 throw new FacesException(new UserStatusUnconfirmedException(user));
599 } else if (this.getUserLockReason() == null) {
601 throw new NullPointerException("userLockReason is null"); //NOI18N
602 } else if (this.getUserLockReason().isEmpty()) {
604 throw new IllegalArgumentException("userLockReason is empty"); //NOI18N
607 // Init updated user instance
608 final User updatedUser;
612 final String baseUrl = FacesUtils.generateBaseUrl();
614 // Call EJB to lock account
615 updatedUser = this.adminUserBean.lockUserAccount(user, this.getUserLockReason(), baseUrl);
616 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
618 throw new FacesException(ex);
622 this.userLockedEvent.fire(new AdminLockedUserEvent(updatedUser));
627 // Should go fine at this point, redirect to user profile
628 return "admin_show_user"; //NOI18N
632 * Unlocks selected user's account. This method makes sure that the account
635 * @return Redirect outcome
637 public String unlockUserAccount () {
639 final User user = this.beanHelper.getUser();
641 // Is the user instance valid and CONFIRMED?
644 throw new NullPointerException("user is null"); //NOI18N
645 } else if (user.getUserId() == null) {
647 throw new NullPointerException("user.userId is null"); //NOI18N
648 } else if (user.getUserId() < 1) {
650 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
651 } else if (user.getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
652 // User account is locked
653 throw new FacesException(new UserStatusConfirmedException(user));
654 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
655 // User account is locked
656 throw new FacesException(new UserStatusUnconfirmedException(user));
659 // Init updated user instance
660 final User updatedUser;
664 final String baseUrl = FacesUtils.generateBaseUrl();
666 // Call EJB to unlock account
667 updatedUser = this.adminUserBean.unlockUserAccount(user, baseUrl);
668 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
670 throw new FacesException(ex);
674 this.userUnlockedEvent.fire(new AdminUnlockedUserEvent(updatedUser));
679 // Should go fine at this point, redirect to user profile
680 return "admin_show_user"; //NOI18N
686 private void clear () {
688 this.setContact(null);
689 this.setUserDeleteReason(null);
690 this.setUserLockReason(null);
691 this.setUserMustChangePassword(null);
692 this.setUserName(null);
693 this.setUserPassword(null);
694 this.setUserPasswordRepeat(null);
695 this.setUserProfileMode(null);
700 * Creates a new user instance from all currently saved data from this bean
702 * @return New user instance
704 private User createUserInstance () {
705 // Init variable for password and contact
706 final String password;
707 final Contact userContact;
709 // Is a contact instance in helper set?
710 if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
711 // Empty password entered, then generate one
712 password = UserLoginUtils.createRandomPassword(FinancialsUserWebRequestController.MINIMUM_PASSWORD_LENGTH);
713 } else if (!this.isSamePasswordEntered()) {
714 // Both passwords don't match
715 throw new FacesException(new UserPasswordRepeatMismatchException());
717 // Both match, so get it from this bean
718 password = this.getUserPassword();
721 // Is contact instance given? Else create one
722 if (this.getContact() instanceof Contact) {
723 // Then use it for contact linking
724 userContact = this.getContact();
726 // Create contact instance
727 userContact = this.contactController.createContactInstance();
730 // Create new instance
731 final User newUser = new LoginUser(
733 this.getUserProfileMode(),
734 this.getUserMustChangePassword(),
735 UserLoginUtils.encryptPassword(password),
736 UserAccountStatus.CONFIRMED,
740 // Get locale from view-root
741 final Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
744 newUser.setUserLocale(locale);
751 * Checks if same password is entered and that they are not empty.
753 * @return Whether the same password was entered
755 private boolean isSamePasswordEntered () {
756 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));