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.faces.view.facelets.FaceletException;
31 import javax.inject.Inject;
32 import javax.inject.Named;
33 import org.mxchange.jcontacts.model.contact.Contact;
34 import org.mxchange.jcoreee.utils.FacesUtils;
35 import org.mxchange.jjobs.beans.BaseJobsBean;
36 import org.mxchange.jjobs.beans.contact.JobsAdminContactWebRequestController;
37 import org.mxchange.jjobs.beans.contact.JobsContactWebRequestController;
38 import org.mxchange.jjobs.beans.features.JobsFeaturesWebApplicationController;
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.AdminUpdatedUserDataEvent;
51 import org.mxchange.jusercore.events.user.update.ObservableAdminUpdatedUserDataEvent;
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<ObservableAdminUpdatedUserDataEvent> 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;
166 private String userLockReason;
169 * Event being fired when an administrator has locked a user
173 private Event<ObservableAdminLockedUserEvent> userLockedEvent;
176 * Flag whether user must change password after login
178 private Boolean userMustChangePassword;
183 private String userName;
186 * User password (clear-text from web form)
188 private String userPassword;
191 * User password repeated (clear-text from web form)
193 private String userPasswordRepeat;
196 * Whether the user wants a public profile
198 private ProfileMode userProfileMode;
201 * Event being fired when administrator unlocks an account
205 private Event<ObservableAdminUnlockedUserEvent> userUnlockedEvent;
208 * Default constructor
210 public JobsAdminUserWebRequestBean () {
211 // Call super constructor
216 * Adds user instance to database by preparing a complete user instance and
217 * sending it to the EJB. The data set in the controller is being verified,
218 * e.g. if the user name or email address is not used yet.
221 public void 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", FacesMessage.SEVERITY_WARN); //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);
282 * Event observer for when a bean helper has successfully created a user
283 * instance, means the user exists. If the user does not exist, this event
284 * should not fire but instead a proper exception must be thrown.
286 * @param event User created event
288 public void afterCreatedUserEvent (@Observes final ObservableCreatedUserEvent event) {
289 // Is the instance valid?
292 throw new NullPointerException("event is null"); //NOI18N
293 } else if (event.getCreatedUser() == null) {
295 throw new NullPointerException("event.createdUser is null"); //NOI18N
296 } else if (event.getCreatedUser().getUserId() == null) {
298 throw new NullPointerException("event.createdUser.userId is null"); //NOI18N
299 } else if (event.getCreatedUser().getUserId() < 1) {
301 throw new NullPointerException(MessageFormat.format("event.createdUser.userId={0} is not valid", event.getCreatedUser().getUserId())); //NOI18N
305 this.setUser(event.getCreatedUser());
309 * Event observer for new user registrations
311 * @param event User registration event
313 public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
314 // event should not be null
317 throw new NullPointerException("event is null"); //NOI18N
318 } else if (event.getRegisteredUser() == null) {
320 throw new NullPointerException("event.user is null"); //NOI18N
321 } else if (event.getRegisteredUser().getUserId() == null) {
323 throw new NullPointerException("event.user.userId is null"); //NOI18N
324 } else if (event.getRegisteredUser().getUserId() < 1) {
326 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
330 final User registeredUser = event.getRegisteredUser();
332 // @TODO Nothing to do with the user here?
338 * Deletes given user account
340 public void deleteUserData () {
341 // Is the user instance valid and CONFIRMED?
342 if (this.getUser() == null) {
344 throw new NullPointerException("user is null"); //NOI18N
345 } else if (this.getUser().getUserId() == null) {
347 throw new NullPointerException("user.userId is null"); //NOI18N
348 } else if (this.getUser().getUserId() < 1) {
350 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
354 // All fine, delete it
355 this.adminUserBean.deleteUser(this.getUser(), this.getUserDeleteReason());
356 } catch (final UserNotFoundException ex) {
357 // Should not happen, so throw again
358 throw new FaceletException(ex);
362 this.deleteUserEvent.fire(new AdminDeletedUserEvent(this.getUser(), this.getUserDeleteReason()));
366 * Edits currently loaded user's data in database.
368 public void editUserData () {
369 // Null password means not setting it
370 String encryptedPassword = null;
372 // Check if user instance is in helper and valid
373 if (this.getUser() == null) {
375 throw new NullPointerException("beanHelper.user is null"); //NOI18N
376 } else if (this.getUser().getUserId() == null) {
378 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
379 } else if (this.getUser().getUserId() < 1) {
381 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", this.getUser().getUserId())); //NOI18N
382 } else if (this.getUserName() == null) {
383 // Not all required fields are set
384 throw new NullPointerException("this.userName is null"); //NOI18N
385 } else if (this.getUserName().isEmpty()) {
386 // Not all required fields are set
387 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
388 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
389 // Clear password fields
390 this.setUserPassword(null);
391 this.setUserPasswordRepeat(null);
393 // Not same password entered
394 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT", FacesMessage.SEVERITY_INFO); //NOI18N
396 } else if ((!Objects.equals(this.getUser().getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
400 // User name already exists
401 this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS", FacesMessage.SEVERITY_WARN); //NOI18N
403 } else if (this.isSamePasswordEntered()) {
404 // Same password entered, create container
405 if ((Objects.equals(this.getUser().getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserLoginUtils.ifPasswordMatches(new UserLoginContainer(this.getUser(), this.getUserPassword())))) {
406 // Clear password fields
407 this.setUserPassword(null);
408 this.setUserPasswordRepeat(null);
410 // Same password entered
411 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD", FacesMessage.SEVERITY_WARN); //NOI18N
416 encryptedPassword = UserLoginUtils.encryptPassword(this.getUserPassword());
419 // Set user name and flag
420 this.getUser().setUserName(this.getUserName());
421 this.getUser().setUserMustChangePassword(this.getUserMustChangePassword());
423 // Is a password set?
424 if (encryptedPassword != null) {
426 this.getUser().setUserEncryptedPassword(encryptedPassword);
429 // Call EJB for updating user data
430 final User updatedUser = this.userBean.updateUserData(this.getUser());
433 this.updatedUserDataEvent.fire(new AdminUpdatedUserDataEvent(updatedUser));
437 * Getter for contact instance
439 * @return Contact instance
441 public Contact getContact () {
446 * Setter for contact instance
448 * @param contact Contact instance
450 public void setContact (final Contact contact) {
451 this.contact = contact;
455 * Getter for user instance
457 * @return User instance
459 public User getUser () {
464 * Setter for user instance
466 * @param user User instance
468 public void setUser (final User user) {
473 * Getter for user delete reason
475 * @return User delete reason
477 public String getUserDeleteReason () {
478 return this.userDeleteReason;
482 * Setter for user delete reason
484 * @param userDeleteReason User delete reason
486 public void setUserDeleteReason (final String userDeleteReason) {
487 this.userDeleteReason = userDeleteReason;
491 * Getter for user lock reason
493 * @return User lock reason
495 public String getUserLockReason () {
496 return this.userLockReason;
500 * Setter for user lock reason
502 * @param userLockReason User lock reason
504 public void setUserLockReason (final String userLockReason) {
505 this.userLockReason = userLockReason;
509 * Getter for flag if user needs to change password
511 * @return Flag if user needs to change password
513 public Boolean getUserMustChangePassword () {
514 return this.userMustChangePassword;
518 * Setter for flag if user needs to change password
520 * @param userMustChangePassword Flag if user needs to change password
522 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
523 this.userMustChangePassword = userMustChangePassword;
527 * Getter for user name
531 public String getUserName () {
532 return this.userName;
536 * Setter for user name
538 * @param userName User name
540 public void setUserName (final String userName) {
541 this.userName = userName;
545 * Getter for clear-text user password
547 * @return Clear-text user password
549 public String getUserPassword () {
550 return this.userPassword;
554 * Setter for clear-text user password
556 * @param userPassword Clear-text user password
558 public void setUserPassword (final String userPassword) {
559 this.userPassword = userPassword;
563 * Getter for clear-text user password repeated
565 * @return Clear-text user password repeated
567 public String getUserPasswordRepeat () {
568 return this.userPasswordRepeat;
572 * Setter for clear-text user password repeated
574 * @param userPasswordRepeat Clear-text user password repeated
576 public void setUserPasswordRepeat (final String userPasswordRepeat) {
577 this.userPasswordRepeat = userPasswordRepeat;
581 * Getter for user profile mode
583 * @return User profile mode
585 public ProfileMode getUserProfileMode () {
586 return this.userProfileMode;
590 * Setter for user profile mode
592 * @param userProfileMode User profile mode
594 public void setUserProfileMode (final ProfileMode userProfileMode) {
595 this.userProfileMode = userProfileMode;
599 * Locks selected user's account. This method makes sure that a lock reason
600 * is provided that th user later can read on login attempts.
602 * @return Redirect outcome
604 public String lockUserAccount () {
605 // Is the user instance valid and CONFIRMED?
606 if (this.getUser() == null) {
608 throw new NullPointerException("this.user is null"); //NOI18N
609 } else if (this.getUser().getUserId() == null) {
611 throw new NullPointerException("this.user.userId is null"); //NOI18N
612 } else if (this.getUser().getUserId() < 1) {
614 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
615 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.LOCKED) {
616 // User account is locked
617 throw new FacesException(new UserStatusLockedException(this.getUser()));
618 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
619 // User account is locked
620 throw new FaceletException(new UserStatusUnconfirmedException(this.getUser()));
621 } else if (this.getUserLockReason() == null) {
623 throw new NullPointerException("this.userLockReason is null"); //NOI18N
624 } else if (this.getUserLockReason().isEmpty()) {
626 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
629 // Init updated user instance
630 final User updatedUser;
634 final String baseUrl = FacesUtils.generateBaseUrl();
636 // Call EJB to lock account
637 updatedUser = this.adminUserBean.lockUserAccount(this.getUser(), this.getUserLockReason(), baseUrl);
638 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
640 throw new FaceletException(ex);
644 this.userLockedEvent.fire(new AdminLockedUserEvent(updatedUser));
649 // Should go fine at this point, redirect to user profile
650 return "admin_show_user"; //NOI18N
654 * Unlocks selected user's account. This method makes sure that the account
657 * @return Redirect outcome
659 public String unlockUserAccount () {
660 // Is the user instance valid and CONFIRMED?
661 if (this.getUser() == null) {
663 throw new NullPointerException("this.user is null"); //NOI18N
664 } else if (this.getUser().getUserId() == null) {
666 throw new NullPointerException("this.user.userId is null"); //NOI18N
667 } else if (this.getUser().getUserId() < 1) {
669 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
670 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
671 // User account is locked
672 throw new FacesException(new UserStatusConfirmedException(this.getUser()));
673 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
674 // User account is locked
675 throw new FaceletException(new UserStatusUnconfirmedException(this.getUser()));
678 // Init updated user instance
679 final User updatedUser;
683 final String baseUrl = FacesUtils.generateBaseUrl();
685 // Call EJB to unlock account
686 updatedUser = this.adminUserBean.unlockUserAccount(this.getUser(), baseUrl);
687 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
689 throw new FaceletException(ex);
693 this.userUnlockedEvent.fire(new AdminUnlockedUserEvent(updatedUser));
698 // Should go fine at this point, redirect to user profile
699 return "admin_show_user"; //NOI18N
705 private void clear () {
707 this.setContact(null);
708 this.setUserDeleteReason(null);
710 this.setUserLockReason(null);
711 this.setUserMustChangePassword(null);
712 this.setUserName(null);
713 this.setUserPassword(null);
714 this.setUserPasswordRepeat(null);
715 this.setUserProfileMode(null);
720 * Creates a new user instance from all currently saved data from this bean
722 * @return New user instance
724 private User createUserInstance () {
725 // Init variable for password
726 String password = null;
729 final Contact userContact;
731 // Is a contact instance in helper set?
732 if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
733 // Empty password entered, then generate one
734 password = UserLoginUtils.createRandomPassword(JobsUserWebRequestController.MINIMUM_PASSWORD_LENGTH);
735 } else if (!this.isSamePasswordEntered()) {
736 // Both passwords don't match
737 throw new FaceletException(new UserPasswordRepeatMismatchException());
739 // Both match, so get it from this bean
740 password = this.getUserPassword();
743 // The password should not be null and at least 5 characters long
744 assert (password != null) : "password is null"; //NOI18N
745 assert (password.length() >= JobsUserWebRequestController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
747 // Is contact instance given? Else create one
748 if (this.getContact() instanceof Contact) {
749 // Then use it for contact linking
750 userContact = this.getContact();
752 // Create contact instance
753 userContact = this.contactController.createContactInstance();
756 // Create new instance
757 final User newUser = new LoginUser(this.getUserName(), this.getUserProfileMode(), this.getUserMustChangePassword(), UserLoginUtils.encryptPassword(password), UserAccountStatus.CONFIRMED, userContact);
759 // Get locale from view-root
760 final Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
763 newUser.setUserLocale(locale);
770 * Checks if same password is entered and that they are not empty.
772 * @return Whether the same password was entered
774 private boolean isSamePasswordEntered () {
775 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));