2 * Copyright (C) 2016, 2017 Roland Häder
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;
22 import javax.annotation.PostConstruct;
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.view.facelets.FaceletException;
29 import javax.inject.Inject;
30 import javax.inject.Named;
31 import javax.naming.Context;
32 import javax.naming.InitialContext;
33 import javax.naming.NamingException;
34 import org.mxchange.jcontacts.contact.Contact;
35 import org.mxchange.jcoreee.events.locale.ObservableLocaleChangeEvent;
36 import org.mxchange.jcoreee.utils.FacesUtils;
37 import org.mxchange.jjobs.beans.BaseJobsController;
38 import org.mxchange.jjobs.beans.contact.JobsAdminContactWebRequestController;
39 import org.mxchange.jjobs.beans.contact.JobsContactWebSessionController;
40 import org.mxchange.jjobs.beans.helper.JobsWebRequestHelperController;
41 import org.mxchange.jjobs.beans.localization.JobsLocalizationSessionController;
42 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
43 import org.mxchange.jusercore.events.user.add.ObservableAdminAddedUserEvent;
44 import org.mxchange.jusercore.events.user.created.ObservableCreatedUserEvent;
45 import org.mxchange.jusercore.events.user.delete.AdminDeletedUserEvent;
46 import org.mxchange.jusercore.events.user.delete.ObservableAdminDeletedUserEvent;
47 import org.mxchange.jusercore.events.user.linked.AdminLinkedUserEvent;
48 import org.mxchange.jusercore.events.user.linked.ObservableAdminLinkedUserEvent;
49 import org.mxchange.jusercore.events.user.locked.AdminLockedUserEvent;
50 import org.mxchange.jusercore.events.user.locked.ObservableAdminLockedUserEvent;
51 import org.mxchange.jusercore.events.user.unlocked.AdminUnlockedUserEvent;
52 import org.mxchange.jusercore.events.user.unlocked.ObservableAdminUnlockedUserEvent;
53 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
54 import org.mxchange.jusercore.events.user.update.ObservableAdminUpdatedUserDataEvent;
55 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
56 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
57 import org.mxchange.jusercore.exceptions.UserNotFoundException;
58 import org.mxchange.jusercore.exceptions.UserStatusConfirmedException;
59 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
60 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
61 import org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote;
62 import org.mxchange.jusercore.model.user.LoginUser;
63 import org.mxchange.jusercore.model.user.User;
64 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
65 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
66 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
67 import org.mxchange.juserlogincore.container.login.UserLoginContainer;
68 import org.mxchange.juserlogincore.events.registration.ObservableUserRegisteredEvent;
69 import org.mxchange.juserlogincore.exceptions.UserPasswordRepeatMismatchException;
70 import org.mxchange.juserlogincore.login.UserLoginUtils;
73 * A user controller (bean)
75 * @author Roland Häder<roland@mxchange.org>
77 @Named ("adminUserController")
79 public class JobsAdminUserWebRequestBean extends BaseJobsController implements JobsAdminUserWebRequestController {
84 private static final long serialVersionUID = 542_145_347_916L;
87 * An event fired when the administrator has added a new user
91 private Event<ObservableAdminAddedUserEvent> addedUserEvent;
94 * Regular contact controller
97 private JobsAdminContactWebRequestController adminContactController;
100 * Administrative user EJB
102 private AdminUserSessionBeanRemote adminUserBean;
108 private JobsWebRequestHelperController beanHelper;
113 private Contact contact;
116 * Regular contact controller
119 private JobsContactWebSessionController contactController;
122 * Event being fired when admin has deleted user
126 private Event<ObservableAdminDeletedUserEvent> deleteUserEvent;
131 private Locale locale;
134 * Localization controller
137 private JobsLocalizationSessionController localizationController;
140 * An event fired when the administrator has updated a new user
144 private Event<ObservableAdminUpdatedUserDataEvent> updatedUserDataEvent;
154 private UserSessionBeanRemote userBean;
157 * Regular user controller
160 private JobsUserWebSessionController userController;
165 private String userDeleteReason;
168 * An event fired when the administrator has linked a user with existing
173 private Event<ObservableAdminLinkedUserEvent> userLinkedEvent;
178 private String userLockReason;
181 * Event being fired when an administrator has locked a user
185 private Event<ObservableAdminLockedUserEvent> userLockedEvent;
188 * Flag whether user must change password after login
190 private Boolean userMustChangePassword;
195 private String userName;
198 * User password (clear-text from web form)
200 private String userPassword;
203 * User password repeated (clear-text from web form)
205 private String userPasswordRepeat;
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.
227 * @return Redirect outcome
229 public String addUser () {
230 // As the form cannot validate the data (required="true"), check it here
231 if (this.getUserName() == null) {
233 throw new NullPointerException("userName is null"); //NOI18N
234 } else if (this.getUserName().isEmpty()) {
236 throw new IllegalArgumentException("userName is null"); //NOI18N
237 } else if (this.getContact() == null) {
238 // No contact instance set, so test required fields: gender, first name and family name
239 this.adminContactController.validateContactData();
242 // Create new user instance
243 User newUser = new LoginUser();
245 // Set user name, CONFIRMED and INVISIBLE
246 newUser.setUserName(this.getUserName());
247 newUser.setUserMustChangePassword(this.getUserMustChangePassword());
248 newUser.setUserAccountStatus(UserAccountStatus.CONFIRMED);
249 newUser.setUserProfileMode(ProfileMode.INVISIBLE);
252 newUser.setUserLocale(this.getLocale());
257 // Is a contact instance in helper set?
258 if (this.getContact() instanceof Contact) {
259 // Then use it for contact linking
260 userContact = this.getContact();
262 // Create contact instance
263 userContact = this.contactController.createContactInstance();
266 // Set contact in user
267 newUser.setUserContact(userContact);
269 // Init variable for password
270 String password = null;
272 // Is the user name or email address used already?
273 // @TODO Add password length check
274 if (this.userController.isUserNameRegistered(newUser)) {
275 // User name is already used
276 throw new FaceletException(new UserNameAlreadyRegisteredException(newUser));
277 } else if ((this.getContact() == null) && (this.contactController.isEmailAddressRegistered(newUser.getUserContact()))) {
278 // Email address is already used
279 this.showFacesMessage("admin_add_user:emailAddress", "ERROR_EMAIL_ADDRESS_ALREADY_USED"); //NOI18N
281 // Always clear password
282 this.setUserPassword(null);
283 this.setUserPasswordRepeat(null);
287 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
288 // Empty password entered, then generate one
289 password = UserLoginUtils.createRandomPassword(JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
290 } else if (!this.isSamePasswordEntered()) {
291 // Both passwords don't match
292 throw new FaceletException(new UserPasswordRepeatMismatchException(newUser));
294 // Both match, so get it from this bean
295 password = this.getUserPassword();
298 // The password should not be null and at least 5 characters long
299 assert (password != null) : "password is null"; //NOI18N
300 assert (password.length() >= JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
302 // Encrypt password and set it
303 newUser.setUserEncryptedPassword(UserLoginUtils.encryptPassword(password));
306 // Now, that all is set, call EJB
307 if (this.getContact() instanceof Contact) {
308 // Link contact with this user
309 User updatedUser = this.adminUserBean.linkUser(newUser);
312 this.userLinkedEvent.fire(new AdminLinkedUserEvent(updatedUser));
315 User updatedUser = this.adminUserBean.addUser(newUser);
318 this.addedUserEvent.fire(new AdminAddedUserEvent(updatedUser));
320 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
322 throw new FaceletException(ex);
326 this.setContact(null);
331 // Return to user list (for now)
332 return "admin_list_user"; //NOI18N
336 * Event observer for when a bean helper has successfully created a user
337 * instance, means the user exists. If the user does not exist, this event
338 * should not fire but instead a proper exception must be thrown.
340 * @param event User created event
342 public void afterCreatedUserEvent (@Observes final ObservableCreatedUserEvent event) {
343 // Is the instance valid?
346 throw new NullPointerException("event is null"); //NOI18N
347 } else if (event.getCreatedUser() == null) {
349 throw new NullPointerException("event.createdUser is null"); //NOI18N
350 } else if (event.getCreatedUser().getUserId() == null) {
352 throw new NullPointerException("event.createdUser.userId is null"); //NOI18N
353 } else if (event.getCreatedUser().getUserId() < 1) {
355 throw new NullPointerException(MessageFormat.format("event.createdUser.userId={0} is not valid", event.getCreatedUser().getUserId())); //NOI18N
359 this.setUser(event.getCreatedUser());
363 * Observer method for events being fired when the application's locale has
366 * @param event Event being fired
368 public void afterLocaleChangeEvent (@Observes final ObservableLocaleChangeEvent event) {
369 // Is the parameter valid?
372 throw new NullPointerException("event is null");
373 } else if (event.getLocale() == null) {
375 throw new NullPointerException("event.locale is null");
379 this.setLocale(event.getLocale());
383 * Event observer for new user registrations
385 * @param event User registration event
387 public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
388 // event should not be null
391 throw new NullPointerException("event is null"); //NOI18N
392 } else if (event.getRegisteredUser() == null) {
394 throw new NullPointerException("event.user is null"); //NOI18N
395 } else if (event.getRegisteredUser().getUserId() == null) {
397 throw new NullPointerException("event.user.userId is null"); //NOI18N
398 } else if (event.getRegisteredUser().getUserId() < 1) {
400 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
404 User registeredUser = event.getRegisteredUser();
406 // @TODO Nothing to do with the user here?
412 * Deletes given user account
414 * @return Redirect outcome
416 public String deleteUserData () {
417 // Is the user instance valid and CONFIRMED?
418 if (this.getUser() == null) {
420 throw new NullPointerException("user is null"); //NOI18N
421 } else if (this.getUser().getUserId() == null) {
423 throw new NullPointerException("user.userId is null"); //NOI18N
424 } else if (this.getUser().getUserId() < 1) {
426 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
430 // All fine, delete it
431 this.adminUserBean.deleteUser(this.getUser(), this.getUserDeleteReason());
432 } catch (final UserNotFoundException ex) {
433 // Should not happen, so throw again
434 throw new FaceletException(ex);
438 this.deleteUserEvent.fire(new AdminDeletedUserEvent(this.getUser(), this.getUserDeleteReason()));
441 return "admin_list_user"; //NOI18N
445 * Edits currently loaded user's data in database.
447 * @return Redirect outcome
449 public String editUserData () {
450 // Null password means not setting it
451 String encryptedPassword = null;
453 // Check if user instance is in helper and valid
454 if (this.getUser() == null) {
456 throw new NullPointerException("beanHelper.user is null"); //NOI18N
457 } else if (this.getUser().getUserId() == null) {
459 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
460 } else if (this.getUser().getUserId() < 1) {
462 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", this.getUser().getUserId())); //NOI18N
463 } else if (this.getUserName() == null) {
464 // Not all required fields are set
465 throw new NullPointerException("this.userName is null"); //NOI18N
466 } else if (this.getUserName().isEmpty()) {
467 // Not all required fields are set
468 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
469 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
470 // Clear password fields
471 this.setUserPassword(null);
472 this.setUserPasswordRepeat(null);
474 // Not same password entered
475 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT"); //NOI18N
477 } else if ((!Objects.equals(this.getUser().getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
481 // User name already exists
482 this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS"); //NOI18N
484 } else if (this.isSamePasswordEntered()) {
485 // Same password entered, create container
486 if ((Objects.equals(this.getUser().getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserLoginUtils.ifPasswordMatches(new UserLoginContainer(this.getUser(), this.getUserPassword())))) {
487 // Clear password fields
488 this.setUserPassword(null);
489 this.setUserPasswordRepeat(null);
491 // Same password entered
492 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD"); //NOI18N
497 encryptedPassword = UserLoginUtils.encryptPassword(this.getUserPassword());
500 // Set user name and flag
501 this.getUser().setUserName(this.getUserName());
502 this.getUser().setUserMustChangePassword(this.getUserMustChangePassword());
504 // Is a password set?
505 if (encryptedPassword != null) {
507 this.getUser().setUserEncryptedPassword(encryptedPassword);
510 // Call EJB for updating user data
511 User updatedUser = this.userBean.updateUserData(this.getUser());
514 this.updatedUserDataEvent.fire(new AdminUpdatedUserDataEvent(updatedUser));
516 // Return to user list (for now)
517 return "admin_list_user"; //NOI18N
521 * Getter for contact instance
523 * @return Contact instance
525 public Contact getContact () {
530 * Setter for contact instance
532 * @param contact Contact instance
534 public void setContact (final Contact contact) {
535 this.contact = contact;
539 * Getter for user instance
541 * @return User instance
543 public User getUser () {
548 * Setter for user instance
550 * @param user User instance
552 public void setUser (final User user) {
557 * Getter for user delete reason
559 * @return User delete reason
561 public String getUserDeleteReason () {
562 return this.userDeleteReason;
566 * Setter for user delete reason
568 * @param userDeleteReason User delete reason
570 public void setUserDeleteReason (final String userDeleteReason) {
571 this.userDeleteReason = userDeleteReason;
575 * Getter for user lock reason
577 * @return User lock reason
579 public String getUserLockReason () {
580 return this.userLockReason;
584 * Setter for user lock reason
586 * @param userLockReason User lock reason
588 public void setUserLockReason (final String userLockReason) {
589 this.userLockReason = userLockReason;
593 * Getter for flag if user needs to change password
595 * @return Flag if user needs to change password
597 public Boolean getUserMustChangePassword () {
598 return this.userMustChangePassword;
602 * Setter for flag if user needs to change password
604 * @param userMustChangePassword Flag if user needs to change password
606 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
607 this.userMustChangePassword = userMustChangePassword;
611 * Getter for user name
615 public String getUserName () {
616 return this.userName;
620 * Setter for user name
622 * @param userName User name
624 public void setUserName (final String userName) {
625 this.userName = userName;
629 * Getter for clear-text user password
631 * @return Clear-text user password
633 public String getUserPassword () {
634 return this.userPassword;
638 * Setter for clear-text user password
640 * @param userPassword Clear-text user password
642 public void setUserPassword (final String userPassword) {
643 this.userPassword = userPassword;
647 * Getter for clear-text user password repeated
649 * @return Clear-text user password repeated
651 public String getUserPasswordRepeat () {
652 return this.userPasswordRepeat;
656 * Setter for clear-text user password repeated
658 * @param userPasswordRepeat Clear-text user password repeated
660 public void setUserPasswordRepeat (final String userPasswordRepeat) {
661 this.userPasswordRepeat = userPasswordRepeat;
665 * Post-construction method
668 public void init () {
671 // Get initial context
672 Context context = new InitialContext();
675 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/jfinancials-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
676 this.adminUserBean = (AdminUserSessionBeanRemote) context.lookup("java:global/jfinancials-ejb/adminUser!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote"); //NOI18N
677 } catch (final NamingException e) {
679 throw new FaceletException(e);
684 * Locks selected user's account. This method makes sure that a lock reason
685 * is provided that th user later can read on login attempts.
687 * @return Redirect outcome
689 public String lockUserAccount () {
690 // Is the user instance valid and CONFIRMED?
691 if (this.getUser() == null) {
693 throw new NullPointerException("this.user is null"); //NOI18N
694 } else if (this.getUser().getUserId() == null) {
696 throw new NullPointerException("this.user.userId is null"); //NOI18N
697 } else if (this.getUser().getUserId() < 1) {
699 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
700 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.LOCKED) {
701 // User account is locked
702 throw new FacesException(new UserStatusLockedException(this.getUser()));
703 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
704 // User account is locked
705 throw new FaceletException(new UserStatusUnconfirmedException(this.getUser()));
706 } else if (this.getUserLockReason() == null) {
708 throw new NullPointerException("this.userLockReason is null"); //NOI18N
709 } else if (this.getUserLockReason().isEmpty()) {
711 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
714 // Init updated user instance
719 String baseUrl = FacesUtils.generateBaseUrl();
721 // Call EJB to lock account
722 updatedUser = this.adminUserBean.lockUserAccount(this.getUser(), this.getUserLockReason(), baseUrl);
723 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
725 throw new FaceletException(ex);
729 this.userLockedEvent.fire(new AdminLockedUserEvent(updatedUser));
734 // Should go fine at this point, redirect to user profile
735 return "admin_show_user"; //NOI18N
739 * Unlocks selected user's account. This method makes sure that the account
742 * @return Redirect outcome
744 public String unlockUserAccount () {
745 // Is the user instance valid and CONFIRMED?
746 if (this.getUser() == null) {
748 throw new NullPointerException("this.user is null"); //NOI18N
749 } else if (this.getUser().getUserId() == null) {
751 throw new NullPointerException("this.user.userId is null"); //NOI18N
752 } else if (this.getUser().getUserId() < 1) {
754 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
755 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
756 // User account is locked
757 throw new FacesException(new UserStatusConfirmedException(this.getUser()));
758 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
759 // User account is locked
760 throw new FaceletException(new UserStatusUnconfirmedException(this.getUser()));
763 // Init updated user instance
768 String baseUrl = FacesUtils.generateBaseUrl();
770 // Call EJB to unlock account
771 updatedUser = this.adminUserBean.unlockUserAccount(this.getUser(), baseUrl);
772 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
774 throw new FaceletException(ex);
778 this.userUnlockedEvent.fire(new AdminUnlockedUserEvent(updatedUser));
783 // Should go fine at this point, redirect to user profile
784 return "admin_show_user"; //NOI18N
790 private void clear () {
792 this.setContact(null);
793 this.setUserLockReason(null);
794 this.setUserMustChangePassword(null);
795 this.setUserName(null);
799 * Getter for locale instance
801 * @return Locale instance
803 private Locale getLocale () {
808 * Setter for locale instance
810 * @param locale Locale instance
812 private void setLocale (final Locale locale) {
813 this.locale = locale;
817 * Checks if same password is entered and that they are not empty.
819 * @return Whether the same password was entered
821 private boolean isSamePasswordEntered () {
822 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));