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.context.FacesContext;
29 import javax.faces.view.facelets.FaceletException;
30 import javax.inject.Inject;
31 import javax.inject.Named;
32 import javax.naming.Context;
33 import javax.naming.InitialContext;
34 import javax.naming.NamingException;
35 import org.mxchange.jcontacts.contact.Contact;
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;
129 * Localization controller
132 private JobsLocalizationSessionController localizationController;
135 * An event fired when the administrator has updated a new user
139 private Event<ObservableAdminUpdatedUserDataEvent> updatedUserDataEvent;
149 private UserSessionBeanRemote userBean;
152 * Regular user controller
155 private JobsUserWebSessionController userController;
160 private String userDeleteReason;
163 * An event fired when the administrator has linked a user with existing
168 private Event<ObservableAdminLinkedUserEvent> userLinkedEvent;
173 private String userLockReason;
176 * Event being fired when an administrator has locked a user
180 private Event<ObservableAdminLockedUserEvent> userLockedEvent;
183 * Flag whether user must change password after login
185 private Boolean userMustChangePassword;
190 private String userName;
193 * User password (clear-text from web form)
195 private String userPassword;
198 * User password repeated (clear-text from web form)
200 private String userPasswordRepeat;
203 * Event being fired when administrator unlocks an account
207 private Event<ObservableAdminUnlockedUserEvent> userUnlockedEvent;
210 * Default constructor
212 public JobsAdminUserWebRequestBean () {
213 // Call super constructor
218 * Adds user instance to database by preparing a complete user instance and
219 * sending it to the EJB. The data set in the controller is being verified,
220 * e.g. if the user name or email address is not used yet.
222 * @return Redirect outcome
224 public String addUser () {
225 System.out.println("addUser: this.contact="+this.getContact());
226 // As the form cannot validate the data (required="true"), check it here
227 if (this.getUserName() == null) {
229 throw new NullPointerException("userName is null"); //NOI18N
230 } else if (this.getUserName().isEmpty()) {
232 throw new IllegalArgumentException("userName is null"); //NOI18N
233 } else if (this.getContact() == null) {
234 // No contact instance set, so test required fields: gender, first name and family name
235 this.adminContactController.validateContactData();
238 // Create new user instance
239 User newUser = new LoginUser();
241 // Set user name, CONFIRMED and INVISIBLE
242 newUser.setUserName(this.getUserName());
243 newUser.setUserMustChangePassword(this.getUserMustChangePassword());
244 newUser.setUserAccountStatus(UserAccountStatus.CONFIRMED);
245 newUser.setUserProfileMode(ProfileMode.INVISIBLE);
247 // Get locale from view-root
248 Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
251 newUser.setUserLocale(locale);
256 // Is a contact instance in helper set?
257 if (this.getContact() instanceof Contact) {
258 // Then use it for contact linking
259 userContact = this.getContact();
261 // Create contact instance
262 userContact = this.contactController.createContactInstance();
265 // Set contact in user
266 newUser.setUserContact(userContact);
268 // Init variable for password
269 String password = null;
271 // Is the user name or email address used already?
272 // @TODO Add password length check
273 if (this.userController.isUserNameRegistered(newUser)) {
274 // User name is already used
275 throw new FaceletException(new UserNameAlreadyRegisteredException(newUser));
276 } else if ((this.getContact() == null) && (this.contactController.isEmailAddressRegistered(newUser.getUserContact()))) {
277 // Email address is already used
278 this.showFacesMessage("admin_add_user:emailAddress", "ERROR_EMAIL_ADDRESS_ALREADY_USED"); //NOI18N
280 // Always clear password
281 this.setUserPassword(null);
282 this.setUserPasswordRepeat(null);
286 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
287 // Empty password entered, then generate one
288 password = UserLoginUtils.createRandomPassword(JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
289 } else if (!this.isSamePasswordEntered()) {
290 // Both passwords don't match
291 throw new FaceletException(new UserPasswordRepeatMismatchException(newUser));
293 // Both match, so get it from this bean
294 password = this.getUserPassword();
297 // The password should not be null and at least 5 characters long
298 assert (password != null) : "password is null"; //NOI18N
299 assert (password.length() >= JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
301 // Encrypt password and set it
302 newUser.setUserEncryptedPassword(UserLoginUtils.encryptPassword(password));
305 // Now, that all is set, call EJB
306 if (this.getContact() instanceof Contact) {
307 // Link contact with this user
308 User updatedUser = this.adminUserBean.linkUser(newUser);
311 this.userLinkedEvent.fire(new AdminLinkedUserEvent(updatedUser));
314 User updatedUser = this.adminUserBean.addUser(newUser);
317 this.addedUserEvent.fire(new AdminAddedUserEvent(updatedUser));
319 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
321 throw new FaceletException(ex);
325 this.setContact(null);
330 // Return to user list (for now)
331 return "admin_list_user"; //NOI18N
335 * Event observer for when a bean helper has successfully created a user
336 * instance, means the user exists. If the user does not exist, this event
337 * should not fire but instead a proper exception must be thrown.
339 * @param event User created event
341 public void afterCreatedUserEvent (@Observes final ObservableCreatedUserEvent event) {
342 // Is the instance valid?
345 throw new NullPointerException("event is null"); //NOI18N
346 } else if (event.getCreatedUser() == null) {
348 throw new NullPointerException("event.createdUser is null"); //NOI18N
349 } else if (event.getCreatedUser().getUserId() == null) {
351 throw new NullPointerException("event.createdUser.userId is null"); //NOI18N
352 } else if (event.getCreatedUser().getUserId() < 1) {
354 throw new NullPointerException(MessageFormat.format("event.createdUser.userId={0} is not valid", event.getCreatedUser().getUserId())); //NOI18N
358 this.setUser(event.getCreatedUser());
362 * Event observer for new user registrations
364 * @param event User registration event
366 public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
367 // event should not be null
370 throw new NullPointerException("event is null"); //NOI18N
371 } else if (event.getRegisteredUser() == null) {
373 throw new NullPointerException("event.user is null"); //NOI18N
374 } else if (event.getRegisteredUser().getUserId() == null) {
376 throw new NullPointerException("event.user.userId is null"); //NOI18N
377 } else if (event.getRegisteredUser().getUserId() < 1) {
379 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
383 User registeredUser = event.getRegisteredUser();
385 // @TODO Nothing to do with the user here?
391 * Deletes given user account
393 * @return Redirect outcome
395 public String deleteUserData () {
396 // Is the user instance valid and CONFIRMED?
397 if (this.getUser() == null) {
399 throw new NullPointerException("user is null"); //NOI18N
400 } else if (this.getUser().getUserId() == null) {
402 throw new NullPointerException("user.userId is null"); //NOI18N
403 } else if (this.getUser().getUserId() < 1) {
405 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
409 // All fine, delete it
410 this.adminUserBean.deleteUser(this.getUser(), this.getUserDeleteReason());
411 } catch (final UserNotFoundException ex) {
412 // Should not happen, so throw again
413 throw new FaceletException(ex);
417 this.deleteUserEvent.fire(new AdminDeletedUserEvent(this.getUser(), this.getUserDeleteReason()));
420 return "admin_list_user"; //NOI18N
424 * Edits currently loaded user's data in database.
426 * @return Redirect outcome
428 public String editUserData () {
429 // Null password means not setting it
430 String encryptedPassword = null;
432 // Check if user instance is in helper and valid
433 if (this.getUser() == null) {
435 throw new NullPointerException("beanHelper.user is null"); //NOI18N
436 } else if (this.getUser().getUserId() == null) {
438 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
439 } else if (this.getUser().getUserId() < 1) {
441 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", this.getUser().getUserId())); //NOI18N
442 } else if (this.getUserName() == null) {
443 // Not all required fields are set
444 throw new NullPointerException("this.userName is null"); //NOI18N
445 } else if (this.getUserName().isEmpty()) {
446 // Not all required fields are set
447 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
448 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
449 // Clear password fields
450 this.setUserPassword(null);
451 this.setUserPasswordRepeat(null);
453 // Not same password entered
454 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT"); //NOI18N
456 } else if ((!Objects.equals(this.getUser().getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
460 // User name already exists
461 this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS"); //NOI18N
463 } else if (this.isSamePasswordEntered()) {
464 // Same password entered, create container
465 if ((Objects.equals(this.getUser().getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserLoginUtils.ifPasswordMatches(new UserLoginContainer(this.getUser(), this.getUserPassword())))) {
466 // Clear password fields
467 this.setUserPassword(null);
468 this.setUserPasswordRepeat(null);
470 // Same password entered
471 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD"); //NOI18N
476 encryptedPassword = UserLoginUtils.encryptPassword(this.getUserPassword());
479 // Set user name and flag
480 this.getUser().setUserName(this.getUserName());
481 this.getUser().setUserMustChangePassword(this.getUserMustChangePassword());
483 // Is a password set?
484 if (encryptedPassword != null) {
486 this.getUser().setUserEncryptedPassword(encryptedPassword);
489 // Call EJB for updating user data
490 User updatedUser = this.userBean.updateUserData(this.getUser());
493 this.updatedUserDataEvent.fire(new AdminUpdatedUserDataEvent(updatedUser));
495 // Return to user list (for now)
496 return "admin_list_user"; //NOI18N
500 * Getter for contact instance
502 * @return Contact instance
504 public Contact getContact () {
509 * Setter for contact instance
511 * @param contact Contact instance
513 public void setContact (final Contact contact) {
514 this.contact = contact;
518 * Getter for user instance
520 * @return User instance
522 public User getUser () {
527 * Setter for user instance
529 * @param user User instance
531 public void setUser (final User user) {
536 * Getter for user delete reason
538 * @return User delete reason
540 public String getUserDeleteReason () {
541 return this.userDeleteReason;
545 * Setter for user delete reason
547 * @param userDeleteReason User delete reason
549 public void setUserDeleteReason (final String userDeleteReason) {
550 this.userDeleteReason = userDeleteReason;
554 * Getter for user lock reason
556 * @return User lock reason
558 public String getUserLockReason () {
559 return this.userLockReason;
563 * Setter for user lock reason
565 * @param userLockReason User lock reason
567 public void setUserLockReason (final String userLockReason) {
568 this.userLockReason = userLockReason;
572 * Getter for flag if user needs to change password
574 * @return Flag if user needs to change password
576 public Boolean getUserMustChangePassword () {
577 return this.userMustChangePassword;
581 * Setter for flag if user needs to change password
583 * @param userMustChangePassword Flag if user needs to change password
585 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
586 this.userMustChangePassword = userMustChangePassword;
590 * Getter for user name
594 public String getUserName () {
595 return this.userName;
599 * Setter for user name
601 * @param userName User name
603 public void setUserName (final String userName) {
604 this.userName = userName;
608 * Getter for clear-text user password
610 * @return Clear-text user password
612 public String getUserPassword () {
613 return this.userPassword;
617 * Setter for clear-text user password
619 * @param userPassword Clear-text user password
621 public void setUserPassword (final String userPassword) {
622 this.userPassword = userPassword;
626 * Getter for clear-text user password repeated
628 * @return Clear-text user password repeated
630 public String getUserPasswordRepeat () {
631 return this.userPasswordRepeat;
635 * Setter for clear-text user password repeated
637 * @param userPasswordRepeat Clear-text user password repeated
639 public void setUserPasswordRepeat (final String userPasswordRepeat) {
640 this.userPasswordRepeat = userPasswordRepeat;
644 * Post-construction method
647 public void init () {
650 // Get initial context
651 Context context = new InitialContext();
654 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
655 this.adminUserBean = (AdminUserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/adminUser!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote"); //NOI18N
656 } catch (final NamingException e) {
658 throw new FaceletException(e);
663 * Locks selected user's account. This method makes sure that a lock reason
664 * is provided that th user later can read on login attempts.
666 * @return Redirect outcome
668 public String lockUserAccount () {
669 // Is the user instance valid and CONFIRMED?
670 if (this.getUser() == null) {
672 throw new NullPointerException("this.user is null"); //NOI18N
673 } else if (this.getUser().getUserId() == null) {
675 throw new NullPointerException("this.user.userId is null"); //NOI18N
676 } else if (this.getUser().getUserId() < 1) {
678 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
679 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.LOCKED) {
680 // User account is locked
681 throw new FacesException(new UserStatusLockedException(this.getUser()));
682 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
683 // User account is locked
684 throw new FaceletException(new UserStatusUnconfirmedException(this.getUser()));
685 } else if (this.getUserLockReason() == null) {
687 throw new NullPointerException("this.userLockReason is null"); //NOI18N
688 } else if (this.getUserLockReason().isEmpty()) {
690 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
693 // Init updated user instance
698 String baseUrl = FacesUtils.generateBaseUrl();
700 // Call EJB to lock account
701 updatedUser = this.adminUserBean.lockUserAccount(this.getUser(), this.getUserLockReason(), baseUrl);
702 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
704 throw new FaceletException(ex);
708 this.userLockedEvent.fire(new AdminLockedUserEvent(updatedUser));
713 // Should go fine at this point, redirect to user profile
714 return "admin_show_user"; //NOI18N
718 * Unlocks selected user's account. This method makes sure that the account
721 * @return Redirect outcome
723 public String unlockUserAccount () {
724 // Is the user instance valid and CONFIRMED?
725 if (this.getUser() == null) {
727 throw new NullPointerException("this.user is null"); //NOI18N
728 } else if (this.getUser().getUserId() == null) {
730 throw new NullPointerException("this.user.userId is null"); //NOI18N
731 } else if (this.getUser().getUserId() < 1) {
733 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
734 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
735 // User account is locked
736 throw new FacesException(new UserStatusConfirmedException(this.getUser()));
737 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
738 // User account is locked
739 throw new FaceletException(new UserStatusUnconfirmedException(this.getUser()));
742 // Init updated user instance
747 String baseUrl = FacesUtils.generateBaseUrl();
749 // Call EJB to unlock account
750 updatedUser = this.adminUserBean.unlockUserAccount(this.getUser(), baseUrl);
751 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
753 throw new FaceletException(ex);
757 this.userUnlockedEvent.fire(new AdminUnlockedUserEvent(updatedUser));
762 // Should go fine at this point, redirect to user profile
763 return "admin_show_user"; //NOI18N
769 private void clear () {
771 this.setContact(null);
772 this.setUserLockReason(null);
773 this.setUserMustChangePassword(null);
774 this.setUserName(null);
778 * Checks if same password is entered and that they are not empty.
780 * @return Whether the same password was entered
782 private boolean isSamePasswordEntered () {
783 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));