2 * Copyright (C) 2016 - 2018 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.
219 * @return Redirect outcome
221 public String addUser () {
222 // As the form cannot validate the data (required="true"), check it here
223 if (this.getUserName() == null) {
225 throw new NullPointerException("userName is null"); //NOI18N
226 } else if (this.getUserName().isEmpty()) {
228 throw new IllegalArgumentException("userName is null"); //NOI18N
229 } else if (this.getContact() == null) {
230 // No contact instance set, so test required fields: gender, first name and family name
231 this.adminContactController.validateContactData();
234 // Create new user instance
235 final User newUser = this.createUserInstance();
237 // Is the user name or email address used already?
238 // @TODO Add password length check
239 if ((this.featureController.isFeatureEnabled("user_login_require_user_name")) && (this.userController.isUserNameRegistered(newUser))) {
240 // User name is already used
241 throw new FaceletException(new UserNameAlreadyRegisteredException(newUser));
242 } else if ((this.getContact() == null) && (this.contactController.isEmailAddressRegistered(newUser.getUserContact()))) {
243 // Email address is already used
244 this.showFacesMessage("admin_add_user:emailAddress", "ERROR_EMAIL_ADDRESS_ALREADY_USED"); //NOI18N
246 // Always clear password
247 this.setUserPassword(null);
248 this.setUserPasswordRepeat(null);
255 // Now, that all is set, call EJB
256 if (this.getContact() instanceof Contact) {
257 // Link contact with this user
258 final User updatedUser = this.adminUserBean.linkUser(newUser);
261 this.userLinkedEvent.fire(new AdminLinkedUserEvent(updatedUser));
264 final User updatedUser = this.adminUserBean.addUser(newUser);
267 this.addedUserEvent.fire(new AdminAddedUserEvent(updatedUser));
269 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
271 throw new FaceletException(ex);
275 this.setContact(null);
280 // Return to user list (for now)
281 return "admin_list_user"; //NOI18N
285 * Event observer for when a bean helper has successfully created a user
286 * instance, means the user exists. If the user does not exist, this event
287 * should not fire but instead a proper exception must be thrown.
289 * @param event User created event
291 public void afterCreatedUserEvent (@Observes final ObservableCreatedUserEvent event) {
292 // Is the instance valid?
295 throw new NullPointerException("event is null"); //NOI18N
296 } else if (event.getCreatedUser() == null) {
298 throw new NullPointerException("event.createdUser is null"); //NOI18N
299 } else if (event.getCreatedUser().getUserId() == null) {
301 throw new NullPointerException("event.createdUser.userId is null"); //NOI18N
302 } else if (event.getCreatedUser().getUserId() < 1) {
304 throw new NullPointerException(MessageFormat.format("event.createdUser.userId={0} is not valid", event.getCreatedUser().getUserId())); //NOI18N
308 this.setUser(event.getCreatedUser());
312 * Event observer for new user registrations
314 * @param event User registration event
316 public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
317 // event should not be null
320 throw new NullPointerException("event is null"); //NOI18N
321 } else if (event.getRegisteredUser() == null) {
323 throw new NullPointerException("event.user is null"); //NOI18N
324 } else if (event.getRegisteredUser().getUserId() == null) {
326 throw new NullPointerException("event.user.userId is null"); //NOI18N
327 } else if (event.getRegisteredUser().getUserId() < 1) {
329 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
333 final User registeredUser = event.getRegisteredUser();
335 // @TODO Nothing to do with the user here?
341 * Deletes given user account
343 * @return Redirect outcome
345 public String deleteUserData () {
346 // Is the user instance valid and CONFIRMED?
347 if (this.getUser() == null) {
349 throw new NullPointerException("user is null"); //NOI18N
350 } else if (this.getUser().getUserId() == null) {
352 throw new NullPointerException("user.userId is null"); //NOI18N
353 } else if (this.getUser().getUserId() < 1) {
355 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
359 // All fine, delete it
360 this.adminUserBean.deleteUser(this.getUser(), this.getUserDeleteReason());
361 } catch (final UserNotFoundException ex) {
362 // Should not happen, so throw again
363 throw new FaceletException(ex);
367 this.deleteUserEvent.fire(new AdminDeletedUserEvent(this.getUser(), this.getUserDeleteReason()));
370 return "admin_list_user"; //NOI18N
374 * Edits currently loaded user's data in database.
376 * @return Redirect outcome
378 public String editUserData () {
379 // Null password means not setting it
380 String encryptedPassword = null;
382 // Check if user instance is in helper and valid
383 if (this.getUser() == null) {
385 throw new NullPointerException("beanHelper.user is null"); //NOI18N
386 } else if (this.getUser().getUserId() == null) {
388 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
389 } else if (this.getUser().getUserId() < 1) {
391 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", this.getUser().getUserId())); //NOI18N
392 } else if (this.getUserName() == null) {
393 // Not all required fields are set
394 throw new NullPointerException("this.userName is null"); //NOI18N
395 } else if (this.getUserName().isEmpty()) {
396 // Not all required fields are set
397 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
398 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
399 // Clear password fields
400 this.setUserPassword(null);
401 this.setUserPasswordRepeat(null);
403 // Not same password entered
404 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT"); //NOI18N
406 } else if ((!Objects.equals(this.getUser().getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
410 // User name already exists
411 this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS"); //NOI18N
413 } else if (this.isSamePasswordEntered()) {
414 // Same password entered, create container
415 if ((Objects.equals(this.getUser().getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserLoginUtils.ifPasswordMatches(new UserLoginContainer(this.getUser(), this.getUserPassword())))) {
416 // Clear password fields
417 this.setUserPassword(null);
418 this.setUserPasswordRepeat(null);
420 // Same password entered
421 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD"); //NOI18N
426 encryptedPassword = UserLoginUtils.encryptPassword(this.getUserPassword());
429 // Set user name and flag
430 this.getUser().setUserName(this.getUserName());
431 this.getUser().setUserMustChangePassword(this.getUserMustChangePassword());
433 // Is a password set?
434 if (encryptedPassword != null) {
436 this.getUser().setUserEncryptedPassword(encryptedPassword);
439 // Call EJB for updating user data
440 final User updatedUser = this.userBean.updateUserData(this.getUser());
443 this.updatedUserDataEvent.fire(new AdminUpdatedUserDataEvent(updatedUser));
445 // Return to user list (for now)
446 return "admin_list_user"; //NOI18N
450 * Getter for contact instance
452 * @return Contact instance
454 public Contact getContact () {
459 * Setter for contact instance
461 * @param contact Contact instance
463 public void setContact (final Contact contact) {
464 this.contact = contact;
468 * Getter for user instance
470 * @return User instance
472 public User getUser () {
477 * Setter for user instance
479 * @param user User instance
481 public void setUser (final User user) {
486 * Getter for user delete reason
488 * @return User delete reason
490 public String getUserDeleteReason () {
491 return this.userDeleteReason;
495 * Setter for user delete reason
497 * @param userDeleteReason User delete reason
499 public void setUserDeleteReason (final String userDeleteReason) {
500 this.userDeleteReason = userDeleteReason;
504 * Getter for user lock reason
506 * @return User lock reason
508 public String getUserLockReason () {
509 return this.userLockReason;
513 * Setter for user lock reason
515 * @param userLockReason User lock reason
517 public void setUserLockReason (final String userLockReason) {
518 this.userLockReason = userLockReason;
522 * Getter for flag if user needs to change password
524 * @return Flag if user needs to change password
526 public Boolean getUserMustChangePassword () {
527 return this.userMustChangePassword;
531 * Setter for flag if user needs to change password
533 * @param userMustChangePassword Flag if user needs to change password
535 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
536 this.userMustChangePassword = userMustChangePassword;
540 * Getter for user name
544 public String getUserName () {
545 return this.userName;
549 * Setter for user name
551 * @param userName User name
553 public void setUserName (final String userName) {
554 this.userName = userName;
558 * Getter for clear-text user password
560 * @return Clear-text user password
562 public String getUserPassword () {
563 return this.userPassword;
567 * Setter for clear-text user password
569 * @param userPassword Clear-text user password
571 public void setUserPassword (final String userPassword) {
572 this.userPassword = userPassword;
576 * Getter for clear-text user password repeated
578 * @return Clear-text user password repeated
580 public String getUserPasswordRepeat () {
581 return this.userPasswordRepeat;
585 * Setter for clear-text user password repeated
587 * @param userPasswordRepeat Clear-text user password repeated
589 public void setUserPasswordRepeat (final String userPasswordRepeat) {
590 this.userPasswordRepeat = userPasswordRepeat;
594 * Getter for user profile mode
596 * @return User profile mode
598 public ProfileMode getUserProfileMode () {
599 return this.userProfileMode;
603 * Setter for user profile mode
605 * @param userProfileMode User profile mode
607 public void setUserProfileMode (final ProfileMode userProfileMode) {
608 this.userProfileMode = userProfileMode;
612 * Locks selected user's account. This method makes sure that a lock reason
613 * is provided that th user later can read on login attempts.
615 * @return Redirect outcome
617 public String lockUserAccount () {
618 // Is the user instance valid and CONFIRMED?
619 if (this.getUser() == null) {
621 throw new NullPointerException("this.user is null"); //NOI18N
622 } else if (this.getUser().getUserId() == null) {
624 throw new NullPointerException("this.user.userId is null"); //NOI18N
625 } else if (this.getUser().getUserId() < 1) {
627 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
628 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.LOCKED) {
629 // User account is locked
630 throw new FacesException(new UserStatusLockedException(this.getUser()));
631 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
632 // User account is locked
633 throw new FaceletException(new UserStatusUnconfirmedException(this.getUser()));
634 } else if (this.getUserLockReason() == null) {
636 throw new NullPointerException("this.userLockReason is null"); //NOI18N
637 } else if (this.getUserLockReason().isEmpty()) {
639 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
642 // Init updated user instance
643 final User updatedUser;
647 final String baseUrl = FacesUtils.generateBaseUrl();
649 // Call EJB to lock account
650 updatedUser = this.adminUserBean.lockUserAccount(this.getUser(), this.getUserLockReason(), baseUrl);
651 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
653 throw new FaceletException(ex);
657 this.userLockedEvent.fire(new AdminLockedUserEvent(updatedUser));
662 // Should go fine at this point, redirect to user profile
663 return "admin_show_user"; //NOI18N
667 * Unlocks selected user's account. This method makes sure that the account
670 * @return Redirect outcome
672 public String unlockUserAccount () {
673 // Is the user instance valid and CONFIRMED?
674 if (this.getUser() == null) {
676 throw new NullPointerException("this.user is null"); //NOI18N
677 } else if (this.getUser().getUserId() == null) {
679 throw new NullPointerException("this.user.userId is null"); //NOI18N
680 } else if (this.getUser().getUserId() < 1) {
682 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
683 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
684 // User account is locked
685 throw new FacesException(new UserStatusConfirmedException(this.getUser()));
686 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
687 // User account is locked
688 throw new FaceletException(new UserStatusUnconfirmedException(this.getUser()));
691 // Init updated user instance
692 final User updatedUser;
696 final String baseUrl = FacesUtils.generateBaseUrl();
698 // Call EJB to unlock account
699 updatedUser = this.adminUserBean.unlockUserAccount(this.getUser(), baseUrl);
700 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
702 throw new FaceletException(ex);
706 this.userUnlockedEvent.fire(new AdminUnlockedUserEvent(updatedUser));
711 // Should go fine at this point, redirect to user profile
712 return "admin_show_user"; //NOI18N
718 private void clear () {
720 this.setContact(null);
721 this.setUserDeleteReason(null);
723 this.setUserLockReason(null);
724 this.setUserMustChangePassword(null);
725 this.setUserName(null);
726 this.setUserPassword(null);
727 this.setUserPasswordRepeat(null);
728 this.setUserProfileMode(null);
733 * Creates a new user instance from all currently saved data from this bean
735 * @return New user instance
737 private User createUserInstance () {
738 // Init variable for password
739 String password = null;
742 final Contact userContact;
744 // Is a contact instance in helper set?
745 if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
746 // Empty password entered, then generate one
747 password = UserLoginUtils.createRandomPassword(JobsUserWebRequestController.MINIMUM_PASSWORD_LENGTH);
748 } else if (!this.isSamePasswordEntered()) {
749 // Both passwords don't match
750 throw new FaceletException(new UserPasswordRepeatMismatchException());
752 // Both match, so get it from this bean
753 password = this.getUserPassword();
756 // The password should not be null and at least 5 characters long
757 assert (password != null) : "password is null"; //NOI18N
758 assert (password.length() >= JobsUserWebRequestController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
760 // Is contact instance given? Else create one
761 if (this.getContact() instanceof Contact) {
762 // Then use it for contact linking
763 userContact = this.getContact();
765 // Create contact instance
766 userContact = this.contactController.createContactInstance();
769 // Create new instance
770 final User newUser = new LoginUser(this.getUserName(), this.getUserProfileMode(), this.getUserMustChangePassword(), UserLoginUtils.encryptPassword(password), UserAccountStatus.CONFIRMED, userContact);
772 // Get locale from view-root
773 final Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
776 newUser.setUserLocale(locale);
783 * Checks if same password is entered and that they are not empty.
785 * @return Whether the same password was entered
787 private boolean isSamePasswordEntered () {
788 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));