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.Objects;
21 import javax.annotation.PostConstruct;
22 import javax.enterprise.context.RequestScoped;
23 import javax.enterprise.event.Event;
24 import javax.enterprise.event.Observes;
25 import javax.enterprise.inject.Any;
26 import javax.faces.FacesException;
27 import javax.faces.view.facelets.FaceletException;
28 import javax.inject.Inject;
29 import javax.inject.Named;
30 import javax.naming.Context;
31 import javax.naming.InitialContext;
32 import javax.naming.NamingException;
33 import org.mxchange.jcontacts.contact.Contact;
34 import org.mxchange.jcoreee.utils.FacesUtils;
35 import org.mxchange.jjobs.beans.BaseJobsController;
36 import org.mxchange.jjobs.beans.contact.JobsAdminContactWebRequestController;
37 import org.mxchange.jjobs.beans.contact.JobsContactWebSessionController;
38 import org.mxchange.jjobs.beans.helper.JobsWebRequestHelperController;
39 import org.mxchange.jjobs.beans.localization.JobsLocalizationSessionController;
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.created.ObservableCreatedUserEvent;
43 import org.mxchange.jusercore.events.user.delete.AdminDeletedUserEvent;
44 import org.mxchange.jusercore.events.user.delete.ObservableAdminDeletedUserEvent;
45 import org.mxchange.jusercore.events.user.linked.AdminLinkedUserEvent;
46 import org.mxchange.jusercore.events.user.linked.ObservableAdminLinkedUserEvent;
47 import org.mxchange.jusercore.events.user.locked.AdminLockedUserEvent;
48 import org.mxchange.jusercore.events.user.locked.ObservableAdminLockedUserEvent;
49 import org.mxchange.jusercore.events.user.unlocked.AdminUnlockedUserEvent;
50 import org.mxchange.jusercore.events.user.unlocked.ObservableAdminUnlockedUserEvent;
51 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
52 import org.mxchange.jusercore.events.user.update.ObservableAdminUpdatedUserDataEvent;
53 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
54 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
55 import org.mxchange.jusercore.exceptions.UserNotFoundException;
56 import org.mxchange.jusercore.exceptions.UserStatusConfirmedException;
57 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
58 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
59 import org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote;
60 import org.mxchange.jusercore.model.user.LoginUser;
61 import org.mxchange.jusercore.model.user.User;
62 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
63 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
64 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
65 import org.mxchange.juserlogincore.container.login.UserLoginContainer;
66 import org.mxchange.juserlogincore.events.registration.ObservableUserRegisteredEvent;
67 import org.mxchange.juserlogincore.exceptions.UserPasswordRepeatMismatchException;
68 import org.mxchange.juserlogincore.login.UserLoginUtils;
71 * A user controller (bean)
73 * @author Roland Häder<roland@mxchange.org>
75 @Named ("adminUserController")
77 public class JobsAdminUserWebRequestBean extends BaseJobsController implements JobsAdminUserWebRequestController {
82 private static final long serialVersionUID = 542_145_347_916L;
85 * An event fired when the administrator has added a new user
89 private Event<ObservableAdminAddedUserEvent> addedUserEvent;
92 * Regular contact controller
95 private JobsAdminContactWebRequestController adminContactController;
98 * Administrative user EJB
100 private AdminUserSessionBeanRemote adminUserBean;
106 private JobsWebRequestHelperController beanHelper;
111 private Contact contact;
114 * Regular contact controller
117 private JobsContactWebSessionController contactController;
120 * Event being fired when admin has deleted user
124 private Event<ObservableAdminDeletedUserEvent> deleteUserEvent;
127 * Localization controller
130 private JobsLocalizationSessionController localizationController;
133 * An event fired when the administrator has updated a new user
137 private Event<ObservableAdminUpdatedUserDataEvent> updatedUserDataEvent;
147 private UserSessionBeanRemote userBean;
150 * Regular user controller
153 private JobsUserWebSessionController userController;
158 private String userDeleteReason;
161 * An event fired when the administrator has linked a user with existing
166 private Event<ObservableAdminLinkedUserEvent> userLinkedEvent;
171 private String userLockReason;
174 * Event being fired when an administrator has locked a user
178 private Event<ObservableAdminLockedUserEvent> userLockedEvent;
181 * Flag whether user must change password after login
183 private Boolean userMustChangePassword;
188 private String userName;
191 * User password (clear-text from web form)
193 private String userPassword;
196 * User password repeated (clear-text from web form)
198 private String userPasswordRepeat;
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.
220 * @return Redirect outcome
222 public String 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: gender, first name and family name
232 this.adminContactController.validateContactData();
235 // Create new user instance
236 User newUser = new LoginUser();
238 // Set user name, CONFIRMED and INVISIBLE
239 newUser.setUserName(this.getUserName());
240 newUser.setUserMustChangePassword(this.getUserMustChangePassword());
241 newUser.setUserAccountStatus(UserAccountStatus.CONFIRMED);
242 newUser.setUserProfileMode(ProfileMode.INVISIBLE);
245 newUser.setUserLocale(this.localizationController.getLocale());
250 // Is a contact instance in helper set?
251 if (this.getContact() instanceof Contact) {
252 // Then use it for contact linking
253 userContact = this.getContact();
255 // Create contact instance
256 userContact = this.contactController.createContactInstance();
259 // Set contact in user
260 newUser.setUserContact(userContact);
262 // Init variable for password
263 String password = null;
265 // Is the user name or email address used already?
266 // @TODO Add password length check
267 if (this.userController.isUserNameRegistered(newUser)) {
268 // User name is already used
269 throw new FaceletException(new UserNameAlreadyRegisteredException(newUser));
270 } else if ((this.getContact() == null) && (this.contactController.isEmailAddressRegistered(newUser.getUserContact()))) {
271 // Email address is already used
272 this.showFacesMessage("admin_add_user:emailAddress", "ERROR_EMAIL_ADDRESS_ALREADY_USED"); //NOI18N
274 // Always clear password
275 this.setUserPassword(null);
276 this.setUserPasswordRepeat(null);
280 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
281 // Empty password entered, then generate one
282 password = UserLoginUtils.createRandomPassword(JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
283 } else if (!this.isSamePasswordEntered()) {
284 // Both passwords don't match
285 throw new FaceletException(new UserPasswordRepeatMismatchException(newUser));
287 // Both match, so get it from this bean
288 password = this.getUserPassword();
291 // The password should not be null and at least 5 characters long
292 assert (password != null) : "password is null"; //NOI18N
293 assert (password.length() >= JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
295 // Encrypt password and set it
296 newUser.setUserEncryptedPassword(UserLoginUtils.encryptPassword(password));
299 // Now, that all is set, call EJB
300 if (this.getContact() instanceof Contact) {
301 // Link contact with this user
302 User updatedUser = this.adminUserBean.linkUser(newUser);
305 this.userLinkedEvent.fire(new AdminLinkedUserEvent(updatedUser));
308 User updatedUser = this.adminUserBean.addUser(newUser);
311 this.addedUserEvent.fire(new AdminAddedUserEvent(updatedUser));
313 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
315 throw new FaceletException(ex);
319 this.setContact(null);
324 // Return to user list (for now)
325 return "admin_list_user"; //NOI18N
329 * Event observer for when a bean helper has successfully created a user
330 * instance, means the user exists. If the user does not exist, this event
331 * should not fire but instead a proper exception must be thrown.
333 * @param event User created event
335 public void afterCreatedUserEvent (@Observes final ObservableCreatedUserEvent event) {
336 // Is the instance valid?
339 throw new NullPointerException("event is null"); //NOI18N
340 } else if (event.getCreatedUser() == null) {
342 throw new NullPointerException("event.createdUser is null"); //NOI18N
343 } else if (event.getCreatedUser().getUserId() == null) {
345 throw new NullPointerException("event.createdUser.userId is null"); //NOI18N
346 } else if (event.getCreatedUser().getUserId() < 1) {
348 throw new NullPointerException(MessageFormat.format("event.createdUser.userId={0} is not valid", event.getCreatedUser().getUserId())); //NOI18N
352 this.setUser(event.getCreatedUser());
356 * Event observer for new user registrations
358 * @param event User registration event
360 public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
361 // event should not be null
364 throw new NullPointerException("event is null"); //NOI18N
365 } else if (event.getRegisteredUser() == null) {
367 throw new NullPointerException("event.user is null"); //NOI18N
368 } else if (event.getRegisteredUser().getUserId() == null) {
370 throw new NullPointerException("event.user.userId is null"); //NOI18N
371 } else if (event.getRegisteredUser().getUserId() < 1) {
373 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
377 User registeredUser = event.getRegisteredUser();
379 // @TODO Nothing to do with the user here?
385 * Deletes given user account
387 * @return Redirect outcome
389 public String deleteUserData () {
390 // Is the user instance valid and CONFIRMED?
391 if (this.getUser() == null) {
393 throw new NullPointerException("user is null"); //NOI18N
394 } else if (this.getUser().getUserId() == null) {
396 throw new NullPointerException("user.userId is null"); //NOI18N
397 } else if (this.getUser().getUserId() < 1) {
399 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
403 // All fine, delete it
404 this.adminUserBean.deleteUser(this.getUser(), this.getUserDeleteReason());
405 } catch (final UserNotFoundException ex) {
406 // Should not happen, so throw again
407 throw new FaceletException(ex);
411 this.deleteUserEvent.fire(new AdminDeletedUserEvent(this.getUser(), this.getUserDeleteReason()));
414 return "admin_list_user"; //NOI18N
418 * Edits currently loaded user's data in database.
420 * @return Redirect outcome
422 public String editUserData () {
423 // Null password means not setting it
424 String encryptedPassword = null;
426 // Check if user instance is in helper and valid
427 if (this.getUser() == null) {
429 throw new NullPointerException("beanHelper.user is null"); //NOI18N
430 } else if (this.getUser().getUserId() == null) {
432 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
433 } else if (this.getUser().getUserId() < 1) {
435 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", this.getUser().getUserId())); //NOI18N
436 } else if (this.getUserName() == null) {
437 // Not all required fields are set
438 throw new NullPointerException("this.userName is null"); //NOI18N
439 } else if (this.getUserName().isEmpty()) {
440 // Not all required fields are set
441 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
442 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
443 // Clear password fields
444 this.setUserPassword(null);
445 this.setUserPasswordRepeat(null);
447 // Not same password entered
448 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT"); //NOI18N
450 } else if ((!Objects.equals(this.getUser().getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
454 // User name already exists
455 this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS"); //NOI18N
457 } else if (this.isSamePasswordEntered()) {
458 // Same password entered, create container
459 if ((Objects.equals(this.getUser().getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserLoginUtils.ifPasswordMatches(new UserLoginContainer(this.getUser(), this.getUserPassword())))) {
460 // Clear password fields
461 this.setUserPassword(null);
462 this.setUserPasswordRepeat(null);
464 // Same password entered
465 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD"); //NOI18N
470 encryptedPassword = UserLoginUtils.encryptPassword(this.getUserPassword());
473 // Set user name and flag
474 this.getUser().setUserName(this.getUserName());
475 this.getUser().setUserMustChangePassword(this.getUserMustChangePassword());
477 // Is a password set?
478 if (encryptedPassword != null) {
480 this.getUser().setUserEncryptedPassword(encryptedPassword);
483 // Call EJB for updating user data
484 User updatedUser = this.userBean.updateUserData(this.getUser());
487 this.updatedUserDataEvent.fire(new AdminUpdatedUserDataEvent(updatedUser));
489 // Return to user list (for now)
490 return "admin_list_user"; //NOI18N
494 * Getter for contact instance
496 * @return Contact instance
498 public Contact getContact () {
503 * Setter for contact instance
505 * @param contact Contact instance
507 public void setContact (final Contact contact) {
508 this.contact = contact;
512 * Getter for user instance
514 * @return User instance
516 public User getUser () {
521 * Setter for user instance
523 * @param user User instance
525 public void setUser (final User user) {
530 * Getter for user delete reason
532 * @return User delete reason
534 public String getUserDeleteReason () {
535 return this.userDeleteReason;
539 * Setter for user delete reason
541 * @param userDeleteReason User delete reason
543 public void setUserDeleteReason (final String userDeleteReason) {
544 this.userDeleteReason = userDeleteReason;
548 * Getter for user lock reason
550 * @return User lock reason
552 public String getUserLockReason () {
553 return this.userLockReason;
557 * Setter for user lock reason
559 * @param userLockReason User lock reason
561 public void setUserLockReason (final String userLockReason) {
562 this.userLockReason = userLockReason;
566 * Getter for flag if user needs to change password
568 * @return Flag if user needs to change password
570 public Boolean getUserMustChangePassword () {
571 return this.userMustChangePassword;
575 * Setter for flag if user needs to change password
577 * @param userMustChangePassword Flag if user needs to change password
579 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
580 this.userMustChangePassword = userMustChangePassword;
584 * Getter for user name
588 public String getUserName () {
589 return this.userName;
593 * Setter for user name
595 * @param userName User name
597 public void setUserName (final String userName) {
598 this.userName = userName;
602 * Getter for clear-text user password
604 * @return Clear-text user password
606 public String getUserPassword () {
607 return this.userPassword;
611 * Setter for clear-text user password
613 * @param userPassword Clear-text user password
615 public void setUserPassword (final String userPassword) {
616 this.userPassword = userPassword;
620 * Getter for clear-text user password repeated
622 * @return Clear-text user password repeated
624 public String getUserPasswordRepeat () {
625 return this.userPasswordRepeat;
629 * Setter for clear-text user password repeated
631 * @param userPasswordRepeat Clear-text user password repeated
633 public void setUserPasswordRepeat (final String userPasswordRepeat) {
634 this.userPasswordRepeat = userPasswordRepeat;
638 * Post-construction method
641 public void init () {
644 // Get initial context
645 Context context = new InitialContext();
648 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/jfinancials-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
649 this.adminUserBean = (AdminUserSessionBeanRemote) context.lookup("java:global/jfinancials-ejb/adminUser!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote"); //NOI18N
650 } catch (final NamingException e) {
652 throw new FaceletException(e);
657 * Locks selected user's account. This method makes sure that a lock reason
658 * is provided that th user later can read on login attempts.
660 * @return Redirect outcome
662 public String lockUserAccount () {
663 // Is the user instance valid and CONFIRMED?
664 if (this.getUser() == null) {
666 throw new NullPointerException("this.user is null"); //NOI18N
667 } else if (this.getUser().getUserId() == null) {
669 throw new NullPointerException("this.user.userId is null"); //NOI18N
670 } else if (this.getUser().getUserId() < 1) {
672 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
673 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.LOCKED) {
674 // User account is locked
675 throw new FacesException(new UserStatusLockedException(this.getUser()));
676 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
677 // User account is locked
678 throw new FaceletException(new UserStatusUnconfirmedException(this.getUser()));
679 } else if (this.getUserLockReason() == null) {
681 throw new NullPointerException("this.userLockReason is null"); //NOI18N
682 } else if (this.getUserLockReason().isEmpty()) {
684 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
687 // Init updated user instance
692 String baseUrl = FacesUtils.generateBaseUrl();
694 // Call EJB to lock account
695 updatedUser = this.adminUserBean.lockUserAccount(this.getUser(), this.getUserLockReason(), baseUrl);
696 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
698 throw new FaceletException(ex);
702 this.userLockedEvent.fire(new AdminLockedUserEvent(updatedUser));
707 // Should go fine at this point, redirect to user profile
708 return "admin_show_user"; //NOI18N
712 * Unlocks selected user's account. This method makes sure that the account
715 * @return Redirect outcome
717 public String unlockUserAccount () {
718 // Is the user instance valid and CONFIRMED?
719 if (this.getUser() == null) {
721 throw new NullPointerException("this.user is null"); //NOI18N
722 } else if (this.getUser().getUserId() == null) {
724 throw new NullPointerException("this.user.userId is null"); //NOI18N
725 } else if (this.getUser().getUserId() < 1) {
727 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
728 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
729 // User account is locked
730 throw new FacesException(new UserStatusConfirmedException(this.getUser()));
731 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
732 // User account is locked
733 throw new FaceletException(new UserStatusUnconfirmedException(this.getUser()));
736 // Init updated user instance
741 String baseUrl = FacesUtils.generateBaseUrl();
743 // Call EJB to unlock account
744 updatedUser = this.adminUserBean.unlockUserAccount(this.getUser(), baseUrl);
745 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
747 throw new FaceletException(ex);
751 this.userUnlockedEvent.fire(new AdminUnlockedUserEvent(updatedUser));
756 // Should go fine at this point, redirect to user profile
757 return "admin_show_user"; //NOI18N
763 private void clear () {
765 this.setContact(null);
766 this.setUserLockReason(null);
767 this.setUserMustChangePassword(null);
768 this.setUserName(null);
772 * Checks if same password is entered and that they are not empty.
774 * @return Whether the same password was entered
776 private boolean isSamePasswordEntered () {
777 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));