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.localization.JobsLocalizationSessionController;
41 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
42 import org.mxchange.jusercore.events.user.add.ObservableAdminAddedUserEvent;
43 import org.mxchange.jusercore.events.user.created.ObservableCreatedUserEvent;
44 import org.mxchange.jusercore.events.user.delete.AdminDeletedUserEvent;
45 import org.mxchange.jusercore.events.user.delete.ObservableAdminDeletedUserEvent;
46 import org.mxchange.jusercore.events.user.linked.AdminLinkedUserEvent;
47 import org.mxchange.jusercore.events.user.linked.ObservableAdminLinkedUserEvent;
48 import org.mxchange.jusercore.events.user.locked.AdminLockedUserEvent;
49 import org.mxchange.jusercore.events.user.locked.ObservableAdminLockedUserEvent;
50 import org.mxchange.jusercore.events.user.unlocked.AdminUnlockedUserEvent;
51 import org.mxchange.jusercore.events.user.unlocked.ObservableAdminUnlockedUserEvent;
52 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
53 import org.mxchange.jusercore.events.user.update.ObservableAdminUpdatedUserDataEvent;
54 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
55 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
56 import org.mxchange.jusercore.exceptions.UserNotFoundException;
57 import org.mxchange.jusercore.exceptions.UserStatusConfirmedException;
58 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
59 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
60 import org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote;
61 import org.mxchange.jusercore.model.user.LoginUser;
62 import org.mxchange.jusercore.model.user.User;
63 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
64 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
65 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
66 import org.mxchange.juserlogincore.container.login.UserLoginContainer;
67 import org.mxchange.juserlogincore.events.registration.ObservableUserRegisteredEvent;
68 import org.mxchange.juserlogincore.exceptions.UserPasswordRepeatMismatchException;
69 import org.mxchange.juserlogincore.login.UserLoginUtils;
72 * A user controller (bean)
74 * @author Roland Häder<roland@mxchange.org>
76 @Named ("adminUserController")
78 public class JobsAdminUserWebRequestBean extends BaseJobsController implements JobsAdminUserWebRequestController {
83 private static final long serialVersionUID = 542_145_347_916L;
86 * An event fired when the administrator has added a new user
90 private Event<ObservableAdminAddedUserEvent> addedUserEvent;
93 * Regular contact controller
96 private JobsAdminContactWebRequestController adminContactController;
99 * Administrative user EJB
101 private AdminUserSessionBeanRemote adminUserBean;
106 private Contact contact;
109 * Regular contact controller
112 private JobsContactWebSessionController contactController;
115 * Event being fired when admin has deleted user
119 private Event<ObservableAdminDeletedUserEvent> deleteUserEvent;
122 * Localization controller
125 private JobsLocalizationSessionController localizationController;
128 * An event fired when the administrator has updated a new user
132 private Event<ObservableAdminUpdatedUserDataEvent> updatedUserDataEvent;
142 private UserSessionBeanRemote userBean;
145 * Regular user controller
148 private JobsUserWebSessionController 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 * Event being fired when administrator unlocks an account
200 private Event<ObservableAdminUnlockedUserEvent> userUnlockedEvent;
203 * Default constructor
205 public JobsAdminUserWebRequestBean () {
206 // Call super constructor
211 * Adds user instance to database by preparing a complete user instance and
212 * sending it to the EJB. The data set in the controller is being verified,
213 * e.g. if the user name or email address is not used yet.
215 * @return Redirect outcome
217 public String addUser () {
218 System.out.println("addUser: this.contact="+this.getContact());
219 // As the form cannot validate the data (required="true"), check it here
220 if (this.getUserName() == null) {
222 throw new NullPointerException("userName is null"); //NOI18N
223 } else if (this.getUserName().isEmpty()) {
225 throw new IllegalArgumentException("userName is null"); //NOI18N
226 } else if (this.getContact() == null) {
227 // No contact instance set, so test required fields: gender, first name and family name
228 this.adminContactController.validateContactData();
231 // Create new user instance
232 User newUser = new LoginUser();
234 // Set user name, CONFIRMED and INVISIBLE
235 newUser.setUserName(this.getUserName());
236 newUser.setUserMustChangePassword(this.getUserMustChangePassword());
237 newUser.setUserAccountStatus(UserAccountStatus.CONFIRMED);
238 newUser.setUserProfileMode(ProfileMode.INVISIBLE);
240 // Get locale from view-root
241 Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
244 newUser.setUserLocale(locale);
249 // Is a contact instance in helper set?
250 if (this.getContact() instanceof Contact) {
251 // Then use it for contact linking
252 userContact = this.getContact();
254 // Create contact instance
255 userContact = this.contactController.createContactInstance();
258 // Set contact in user
259 newUser.setUserContact(userContact);
261 // Init variable for password
262 String password = null;
264 // Is the user name or email address used already?
265 // @TODO Add password length check
266 if (this.userController.isUserNameRegistered(newUser)) {
267 // User name is already used
268 throw new FaceletException(new UserNameAlreadyRegisteredException(newUser));
269 } else if ((this.getContact() == null) && (this.contactController.isEmailAddressRegistered(newUser.getUserContact()))) {
270 // Email address is already used
271 this.showFacesMessage("admin_add_user:emailAddress", "ERROR_EMAIL_ADDRESS_ALREADY_USED"); //NOI18N
273 // Always clear password
274 this.setUserPassword(null);
275 this.setUserPasswordRepeat(null);
279 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
280 // Empty password entered, then generate one
281 password = UserLoginUtils.createRandomPassword(JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
282 } else if (!this.isSamePasswordEntered()) {
283 // Both passwords don't match
284 throw new FaceletException(new UserPasswordRepeatMismatchException(newUser));
286 // Both match, so get it from this bean
287 password = this.getUserPassword();
290 // The password should not be null and at least 5 characters long
291 assert (password != null) : "password is null"; //NOI18N
292 assert (password.length() >= JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
294 // Encrypt password and set it
295 newUser.setUserEncryptedPassword(UserLoginUtils.encryptPassword(password));
298 // Now, that all is set, call EJB
299 if (this.getContact() instanceof Contact) {
300 // Link contact with this user
301 User updatedUser = this.adminUserBean.linkUser(newUser);
304 this.userLinkedEvent.fire(new AdminLinkedUserEvent(updatedUser));
307 User updatedUser = this.adminUserBean.addUser(newUser);
310 this.addedUserEvent.fire(new AdminAddedUserEvent(updatedUser));
312 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
314 throw new FaceletException(ex);
318 this.setContact(null);
323 // Return to user list (for now)
324 return "admin_list_user"; //NOI18N
328 * Event observer for when a bean helper has successfully created a user
329 * instance, means the user exists. If the user does not exist, this event
330 * should not fire but instead a proper exception must be thrown.
332 * @param event User created event
334 public void afterCreatedUserEvent (@Observes final ObservableCreatedUserEvent event) {
335 // Is the instance valid?
338 throw new NullPointerException("event is null"); //NOI18N
339 } else if (event.getCreatedUser() == null) {
341 throw new NullPointerException("event.createdUser is null"); //NOI18N
342 } else if (event.getCreatedUser().getUserId() == null) {
344 throw new NullPointerException("event.createdUser.userId is null"); //NOI18N
345 } else if (event.getCreatedUser().getUserId() < 1) {
347 throw new NullPointerException(MessageFormat.format("event.createdUser.userId={0} is not valid", event.getCreatedUser().getUserId())); //NOI18N
351 this.setUser(event.getCreatedUser());
355 * Event observer for new user registrations
357 * @param event User registration event
359 public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
360 // event should not be null
363 throw new NullPointerException("event is null"); //NOI18N
364 } else if (event.getRegisteredUser() == null) {
366 throw new NullPointerException("event.user is null"); //NOI18N
367 } else if (event.getRegisteredUser().getUserId() == null) {
369 throw new NullPointerException("event.user.userId is null"); //NOI18N
370 } else if (event.getRegisteredUser().getUserId() < 1) {
372 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
376 User registeredUser = event.getRegisteredUser();
378 // @TODO Nothing to do with the user here?
384 * Deletes given user account
386 * @return Redirect outcome
388 public String deleteUserData () {
389 // Is the user instance valid and CONFIRMED?
390 if (this.getUser() == null) {
392 throw new NullPointerException("user is null"); //NOI18N
393 } else if (this.getUser().getUserId() == null) {
395 throw new NullPointerException("user.userId is null"); //NOI18N
396 } else if (this.getUser().getUserId() < 1) {
398 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
402 // All fine, delete it
403 this.adminUserBean.deleteUser(this.getUser(), this.getUserDeleteReason());
404 } catch (final UserNotFoundException ex) {
405 // Should not happen, so throw again
406 throw new FaceletException(ex);
410 this.deleteUserEvent.fire(new AdminDeletedUserEvent(this.getUser(), this.getUserDeleteReason()));
413 return "admin_list_user"; //NOI18N
417 * Edits currently loaded user's data in database.
419 * @return Redirect outcome
421 public String editUserData () {
422 // Null password means not setting it
423 String encryptedPassword = null;
425 // Check if user instance is in helper and valid
426 if (this.getUser() == null) {
428 throw new NullPointerException("beanHelper.user is null"); //NOI18N
429 } else if (this.getUser().getUserId() == null) {
431 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
432 } else if (this.getUser().getUserId() < 1) {
434 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", this.getUser().getUserId())); //NOI18N
435 } else if (this.getUserName() == null) {
436 // Not all required fields are set
437 throw new NullPointerException("this.userName is null"); //NOI18N
438 } else if (this.getUserName().isEmpty()) {
439 // Not all required fields are set
440 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
441 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
442 // Clear password fields
443 this.setUserPassword(null);
444 this.setUserPasswordRepeat(null);
446 // Not same password entered
447 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT"); //NOI18N
449 } else if ((!Objects.equals(this.getUser().getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
453 // User name already exists
454 this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS"); //NOI18N
456 } else if (this.isSamePasswordEntered()) {
457 // Same password entered, create container
458 if ((Objects.equals(this.getUser().getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserLoginUtils.ifPasswordMatches(new UserLoginContainer(this.getUser(), this.getUserPassword())))) {
459 // Clear password fields
460 this.setUserPassword(null);
461 this.setUserPasswordRepeat(null);
463 // Same password entered
464 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD"); //NOI18N
469 encryptedPassword = UserLoginUtils.encryptPassword(this.getUserPassword());
472 // Set user name and flag
473 this.getUser().setUserName(this.getUserName());
474 this.getUser().setUserMustChangePassword(this.getUserMustChangePassword());
476 // Is a password set?
477 if (encryptedPassword != null) {
479 this.getUser().setUserEncryptedPassword(encryptedPassword);
482 // Call EJB for updating user data
483 User updatedUser = this.userBean.updateUserData(this.getUser());
486 this.updatedUserDataEvent.fire(new AdminUpdatedUserDataEvent(updatedUser));
488 // Return to user list (for now)
489 return "admin_list_user"; //NOI18N
493 * Getter for contact instance
495 * @return Contact instance
497 public Contact getContact () {
502 * Setter for contact instance
504 * @param contact Contact instance
506 public void setContact (final Contact contact) {
507 this.contact = contact;
511 * Getter for user instance
513 * @return User instance
515 public User getUser () {
520 * Setter for user instance
522 * @param user User instance
524 public void setUser (final User user) {
529 * Getter for user delete reason
531 * @return User delete reason
533 public String getUserDeleteReason () {
534 return this.userDeleteReason;
538 * Setter for user delete reason
540 * @param userDeleteReason User delete reason
542 public void setUserDeleteReason (final String userDeleteReason) {
543 this.userDeleteReason = userDeleteReason;
547 * Getter for user lock reason
549 * @return User lock reason
551 public String getUserLockReason () {
552 return this.userLockReason;
556 * Setter for user lock reason
558 * @param userLockReason User lock reason
560 public void setUserLockReason (final String userLockReason) {
561 this.userLockReason = userLockReason;
565 * Getter for flag if user needs to change password
567 * @return Flag if user needs to change password
569 public Boolean getUserMustChangePassword () {
570 return this.userMustChangePassword;
574 * Setter for flag if user needs to change password
576 * @param userMustChangePassword Flag if user needs to change password
578 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
579 this.userMustChangePassword = userMustChangePassword;
583 * Getter for user name
587 public String getUserName () {
588 return this.userName;
592 * Setter for user name
594 * @param userName User name
596 public void setUserName (final String userName) {
597 this.userName = userName;
601 * Getter for clear-text user password
603 * @return Clear-text user password
605 public String getUserPassword () {
606 return this.userPassword;
610 * Setter for clear-text user password
612 * @param userPassword Clear-text user password
614 public void setUserPassword (final String userPassword) {
615 this.userPassword = userPassword;
619 * Getter for clear-text user password repeated
621 * @return Clear-text user password repeated
623 public String getUserPasswordRepeat () {
624 return this.userPasswordRepeat;
628 * Setter for clear-text user password repeated
630 * @param userPasswordRepeat Clear-text user password repeated
632 public void setUserPasswordRepeat (final String userPasswordRepeat) {
633 this.userPasswordRepeat = userPasswordRepeat;
637 * Post-construction method
640 public void init () {
643 // Get initial context
644 Context context = new InitialContext();
647 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
648 this.adminUserBean = (AdminUserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/adminUser!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote"); //NOI18N
649 } catch (final NamingException e) {
651 throw new FaceletException(e);
656 * Locks selected user's account. This method makes sure that a lock reason
657 * is provided that th user later can read on login attempts.
659 * @return Redirect outcome
661 public String lockUserAccount () {
662 // Is the user instance valid and CONFIRMED?
663 if (this.getUser() == null) {
665 throw new NullPointerException("this.user is null"); //NOI18N
666 } else if (this.getUser().getUserId() == null) {
668 throw new NullPointerException("this.user.userId is null"); //NOI18N
669 } else if (this.getUser().getUserId() < 1) {
671 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
672 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.LOCKED) {
673 // User account is locked
674 throw new FacesException(new UserStatusLockedException(this.getUser()));
675 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
676 // User account is locked
677 throw new FaceletException(new UserStatusUnconfirmedException(this.getUser()));
678 } else if (this.getUserLockReason() == null) {
680 throw new NullPointerException("this.userLockReason is null"); //NOI18N
681 } else if (this.getUserLockReason().isEmpty()) {
683 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
686 // Init updated user instance
691 String baseUrl = FacesUtils.generateBaseUrl();
693 // Call EJB to lock account
694 updatedUser = this.adminUserBean.lockUserAccount(this.getUser(), this.getUserLockReason(), baseUrl);
695 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
697 throw new FaceletException(ex);
701 this.userLockedEvent.fire(new AdminLockedUserEvent(updatedUser));
706 // Should go fine at this point, redirect to user profile
707 return "admin_show_user"; //NOI18N
711 * Unlocks selected user's account. This method makes sure that the account
714 * @return Redirect outcome
716 public String unlockUserAccount () {
717 // Is the user instance valid and CONFIRMED?
718 if (this.getUser() == null) {
720 throw new NullPointerException("this.user is null"); //NOI18N
721 } else if (this.getUser().getUserId() == null) {
723 throw new NullPointerException("this.user.userId is null"); //NOI18N
724 } else if (this.getUser().getUserId() < 1) {
726 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
727 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
728 // User account is locked
729 throw new FacesException(new UserStatusConfirmedException(this.getUser()));
730 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
731 // User account is locked
732 throw new FaceletException(new UserStatusUnconfirmedException(this.getUser()));
735 // Init updated user instance
740 String baseUrl = FacesUtils.generateBaseUrl();
742 // Call EJB to unlock account
743 updatedUser = this.adminUserBean.unlockUserAccount(this.getUser(), baseUrl);
744 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
746 throw new FaceletException(ex);
750 this.userUnlockedEvent.fire(new AdminUnlockedUserEvent(updatedUser));
755 // Should go fine at this point, redirect to user profile
756 return "admin_show_user"; //NOI18N
762 private void clear () {
764 this.setContact(null);
765 this.setUserLockReason(null);
766 this.setUserMustChangePassword(null);
767 this.setUserName(null);
771 * Checks if same password is entered and that they are not empty.
773 * @return Whether the same password was entered
775 private boolean isSamePasswordEntered () {
776 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));