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;
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 org.mxchange.jcontacts.model.contact.Contact;
33 import org.mxchange.jcoreee.utils.FacesUtils;
34 import org.mxchange.jjobs.beans.BaseJobsBean;
35 import org.mxchange.jjobs.beans.contact.JobsAdminContactWebRequestController;
36 import org.mxchange.jjobs.beans.contact.JobsContactWebRequestController;
37 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
38 import org.mxchange.jusercore.events.user.add.ObservableAdminAddedUserEvent;
39 import org.mxchange.jusercore.events.user.created.ObservableCreatedUserEvent;
40 import org.mxchange.jusercore.events.user.delete.AdminDeletedUserEvent;
41 import org.mxchange.jusercore.events.user.delete.ObservableAdminDeletedUserEvent;
42 import org.mxchange.jusercore.events.user.linked.AdminLinkedUserEvent;
43 import org.mxchange.jusercore.events.user.linked.ObservableAdminLinkedUserEvent;
44 import org.mxchange.jusercore.events.user.locked.AdminLockedUserEvent;
45 import org.mxchange.jusercore.events.user.locked.ObservableAdminLockedUserEvent;
46 import org.mxchange.jusercore.events.user.unlocked.AdminUnlockedUserEvent;
47 import org.mxchange.jusercore.events.user.unlocked.ObservableAdminUnlockedUserEvent;
48 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
49 import org.mxchange.jusercore.events.user.update.ObservableAdminUpdatedUserDataEvent;
50 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
51 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
52 import org.mxchange.jusercore.exceptions.UserNotFoundException;
53 import org.mxchange.jusercore.exceptions.UserStatusConfirmedException;
54 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
55 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
56 import org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote;
57 import org.mxchange.jusercore.model.user.LoginUser;
58 import org.mxchange.jusercore.model.user.User;
59 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
60 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
61 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
62 import org.mxchange.juserlogincore.container.login.UserLoginContainer;
63 import org.mxchange.juserlogincore.events.registration.ObservableUserRegisteredEvent;
64 import org.mxchange.juserlogincore.exceptions.UserPasswordRepeatMismatchException;
65 import org.mxchange.juserlogincore.login.UserLoginUtils;
68 * A user controller (bean)
70 * @author Roland Häder<roland@mxchange.org>
72 @Named ("adminUserController")
74 public class JobsAdminUserWebRequestBean extends BaseJobsBean implements JobsAdminUserWebRequestController {
79 private static final long serialVersionUID = 542_145_347_916L;
82 * An event fired when the administrator has added a new user
86 private Event<ObservableAdminAddedUserEvent> addedUserEvent;
89 * Regular contact controller
92 private JobsAdminContactWebRequestController adminContactController;
95 * Administrative user EJB
97 @EJB (lookup = "java:global/jjobs-ejb/adminUser!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote")
98 private AdminUserSessionBeanRemote adminUserBean;
103 private Contact contact;
106 * Regular contact controller
109 private JobsContactWebRequestController contactController;
112 * Event being fired when admin has deleted user
116 private Event<ObservableAdminDeletedUserEvent> deleteUserEvent;
119 * Localization controller
122 private JobsLocalizationSessionController localizationController;
125 * An event fired when the administrator has updated a new user
129 private Event<ObservableAdminUpdatedUserDataEvent> updatedUserDataEvent;
139 @EJB (lookup = "java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote")
140 private UserSessionBeanRemote userBean;
143 * Regular user controller
146 private JobsUserWebRequestController userController;
151 private String userDeleteReason;
154 * An event fired when the administrator has linked a user with existing
159 private Event<ObservableAdminLinkedUserEvent> userLinkedEvent;
164 private String userLockReason;
167 * Event being fired when an administrator has locked a user
171 private Event<ObservableAdminLockedUserEvent> userLockedEvent;
174 * Flag whether user must change password after login
176 private Boolean userMustChangePassword;
181 private String userName;
184 * User password (clear-text from web form)
186 private String userPassword;
189 * User password repeated (clear-text from web form)
191 private String userPasswordRepeat;
194 * Event being fired when administrator unlocks an account
198 private Event<ObservableAdminUnlockedUserEvent> userUnlockedEvent;
201 * Default constructor
203 public JobsAdminUserWebRequestBean () {
204 // Call super constructor
209 * Adds user instance to database by preparing a complete user instance and
210 * sending it to the EJB. The data set in the controller is being verified,
211 * e.g. if the user name or email address is not used yet.
213 * @return Redirect outcome
215 public String addUser () {
216 // As the form cannot validate the data (required="true"), check it here
217 if (this.getUserName() == null) {
219 throw new NullPointerException("userName is null"); //NOI18N
220 } else if (this.getUserName().isEmpty()) {
222 throw new IllegalArgumentException("userName is null"); //NOI18N
223 } else if (this.getContact() == null) {
224 // No contact instance set, so test required fields: gender, first name and family name
225 this.adminContactController.validateContactData();
228 // Create new user instance
229 final User newUser = new LoginUser();
231 // Set user name, CONFIRMED and INVISIBLE
232 newUser.setUserName(this.getUserName());
233 newUser.setUserMustChangePassword(this.getUserMustChangePassword());
234 newUser.setUserAccountStatus(UserAccountStatus.CONFIRMED);
235 newUser.setUserProfileMode(ProfileMode.INVISIBLE);
237 // Get locale from view-root
238 final Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
241 newUser.setUserLocale(locale);
246 // Is a contact instance in helper set?
247 if (this.getContact() instanceof Contact) {
248 // Then use it for contact linking
249 userContact = this.getContact();
251 // Create contact instance
252 userContact = this.contactController.createContactInstance();
255 // Set contact in user
256 newUser.setUserContact(userContact);
258 // Init variable for password
259 String password = null;
261 // Is the user name or email address used already?
262 // @TODO Add password length check
263 if (this.userController.isUserNameRegistered(newUser)) {
264 // User name is already used
265 throw new FaceletException(new UserNameAlreadyRegisteredException(newUser));
266 } else if ((this.getContact() == null) && (this.contactController.isEmailAddressRegistered(newUser.getUserContact()))) {
267 // Email address is already used
268 this.showFacesMessage("admin_add_user:emailAddress", "ERROR_EMAIL_ADDRESS_ALREADY_USED"); //NOI18N
270 // Always clear password
271 this.setUserPassword(null);
272 this.setUserPasswordRepeat(null);
276 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
277 // Empty password entered, then generate one
278 password = UserLoginUtils.createRandomPassword(JobsUserWebRequestController.MINIMUM_PASSWORD_LENGTH);
279 } else if (!this.isSamePasswordEntered()) {
280 // Both passwords don't match
281 throw new FaceletException(new UserPasswordRepeatMismatchException(newUser));
283 // Both match, so get it from this bean
284 password = this.getUserPassword();
287 // The password should not be null and at least 5 characters long
288 assert (password != null) : "password is null"; //NOI18N
289 assert (password.length() >= JobsUserWebRequestController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
291 // Encrypt password and set it
292 newUser.setUserEncryptedPassword(UserLoginUtils.encryptPassword(password));
295 // Now, that all is set, call EJB
296 if (this.getContact() instanceof Contact) {
297 // Link contact with this user
298 final User updatedUser = this.adminUserBean.linkUser(newUser);
301 this.userLinkedEvent.fire(new AdminLinkedUserEvent(updatedUser));
304 final User updatedUser = this.adminUserBean.addUser(newUser);
307 this.addedUserEvent.fire(new AdminAddedUserEvent(updatedUser));
309 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
311 throw new FaceletException(ex);
315 this.setContact(null);
320 // Return to user list (for now)
321 return "admin_list_user"; //NOI18N
325 * Event observer for when a bean helper has successfully created a user
326 * instance, means the user exists. If the user does not exist, this event
327 * should not fire but instead a proper exception must be thrown.
329 * @param event User created event
331 public void afterCreatedUserEvent (@Observes final ObservableCreatedUserEvent event) {
332 // Is the instance valid?
335 throw new NullPointerException("event is null"); //NOI18N
336 } else if (event.getCreatedUser() == null) {
338 throw new NullPointerException("event.createdUser is null"); //NOI18N
339 } else if (event.getCreatedUser().getUserId() == null) {
341 throw new NullPointerException("event.createdUser.userId is null"); //NOI18N
342 } else if (event.getCreatedUser().getUserId() < 1) {
344 throw new NullPointerException(MessageFormat.format("event.createdUser.userId={0} is not valid", event.getCreatedUser().getUserId())); //NOI18N
348 this.setUser(event.getCreatedUser());
352 * Event observer for new user registrations
354 * @param event User registration event
356 public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
357 // event should not be null
360 throw new NullPointerException("event is null"); //NOI18N
361 } else if (event.getRegisteredUser() == null) {
363 throw new NullPointerException("event.user is null"); //NOI18N
364 } else if (event.getRegisteredUser().getUserId() == null) {
366 throw new NullPointerException("event.user.userId is null"); //NOI18N
367 } else if (event.getRegisteredUser().getUserId() < 1) {
369 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
373 final User registeredUser = event.getRegisteredUser();
375 // @TODO Nothing to do with the user here?
381 * Deletes given user account
383 * @return Redirect outcome
385 public String deleteUserData () {
386 // Is the user instance valid and CONFIRMED?
387 if (this.getUser() == null) {
389 throw new NullPointerException("user is null"); //NOI18N
390 } else if (this.getUser().getUserId() == null) {
392 throw new NullPointerException("user.userId is null"); //NOI18N
393 } else if (this.getUser().getUserId() < 1) {
395 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
399 // All fine, delete it
400 this.adminUserBean.deleteUser(this.getUser(), this.getUserDeleteReason());
401 } catch (final UserNotFoundException ex) {
402 // Should not happen, so throw again
403 throw new FaceletException(ex);
407 this.deleteUserEvent.fire(new AdminDeletedUserEvent(this.getUser(), this.getUserDeleteReason()));
410 return "admin_list_user"; //NOI18N
414 * Edits currently loaded user's data in database.
416 * @return Redirect outcome
418 public String editUserData () {
419 // Null password means not setting it
420 String encryptedPassword = null;
422 // Check if user instance is in helper and valid
423 if (this.getUser() == null) {
425 throw new NullPointerException("beanHelper.user is null"); //NOI18N
426 } else if (this.getUser().getUserId() == null) {
428 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
429 } else if (this.getUser().getUserId() < 1) {
431 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", this.getUser().getUserId())); //NOI18N
432 } else if (this.getUserName() == null) {
433 // Not all required fields are set
434 throw new NullPointerException("this.userName is null"); //NOI18N
435 } else if (this.getUserName().isEmpty()) {
436 // Not all required fields are set
437 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
438 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
439 // Clear password fields
440 this.setUserPassword(null);
441 this.setUserPasswordRepeat(null);
443 // Not same password entered
444 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT"); //NOI18N
446 } else if ((!Objects.equals(this.getUser().getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
450 // User name already exists
451 this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS"); //NOI18N
453 } else if (this.isSamePasswordEntered()) {
454 // Same password entered, create container
455 if ((Objects.equals(this.getUser().getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserLoginUtils.ifPasswordMatches(new UserLoginContainer(this.getUser(), this.getUserPassword())))) {
456 // Clear password fields
457 this.setUserPassword(null);
458 this.setUserPasswordRepeat(null);
460 // Same password entered
461 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD"); //NOI18N
466 encryptedPassword = UserLoginUtils.encryptPassword(this.getUserPassword());
469 // Set user name and flag
470 this.getUser().setUserName(this.getUserName());
471 this.getUser().setUserMustChangePassword(this.getUserMustChangePassword());
473 // Is a password set?
474 if (encryptedPassword != null) {
476 this.getUser().setUserEncryptedPassword(encryptedPassword);
479 // Call EJB for updating user data
480 final User updatedUser = this.userBean.updateUserData(this.getUser());
483 this.updatedUserDataEvent.fire(new AdminUpdatedUserDataEvent(updatedUser));
485 // Return to user list (for now)
486 return "admin_list_user"; //NOI18N
490 * Getter for contact instance
492 * @return Contact instance
494 public Contact getContact () {
499 * Setter for contact instance
501 * @param contact Contact instance
503 public void setContact (final Contact contact) {
504 this.contact = contact;
508 * Getter for user instance
510 * @return User instance
512 public User getUser () {
517 * Setter for user instance
519 * @param user User instance
521 public void setUser (final User user) {
526 * Getter for user delete reason
528 * @return User delete reason
530 public String getUserDeleteReason () {
531 return this.userDeleteReason;
535 * Setter for user delete reason
537 * @param userDeleteReason User delete reason
539 public void setUserDeleteReason (final String userDeleteReason) {
540 this.userDeleteReason = userDeleteReason;
544 * Getter for user lock reason
546 * @return User lock reason
548 public String getUserLockReason () {
549 return this.userLockReason;
553 * Setter for user lock reason
555 * @param userLockReason User lock reason
557 public void setUserLockReason (final String userLockReason) {
558 this.userLockReason = userLockReason;
562 * Getter for flag if user needs to change password
564 * @return Flag if user needs to change password
566 public Boolean getUserMustChangePassword () {
567 return this.userMustChangePassword;
571 * Setter for flag if user needs to change password
573 * @param userMustChangePassword Flag if user needs to change password
575 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
576 this.userMustChangePassword = userMustChangePassword;
580 * Getter for user name
584 public String getUserName () {
585 return this.userName;
589 * Setter for user name
591 * @param userName User name
593 public void setUserName (final String userName) {
594 this.userName = userName;
598 * Getter for clear-text user password
600 * @return Clear-text user password
602 public String getUserPassword () {
603 return this.userPassword;
607 * Setter for clear-text user password
609 * @param userPassword Clear-text user password
611 public void setUserPassword (final String userPassword) {
612 this.userPassword = userPassword;
616 * Getter for clear-text user password repeated
618 * @return Clear-text user password repeated
620 public String getUserPasswordRepeat () {
621 return this.userPasswordRepeat;
625 * Setter for clear-text user password repeated
627 * @param userPasswordRepeat Clear-text user password repeated
629 public void setUserPasswordRepeat (final String userPasswordRepeat) {
630 this.userPasswordRepeat = userPasswordRepeat;
634 * Locks selected user's account. This method makes sure that a lock reason
635 * is provided that th user later can read on login attempts.
637 * @return Redirect outcome
639 public String lockUserAccount () {
640 // Is the user instance valid and CONFIRMED?
641 if (this.getUser() == null) {
643 throw new NullPointerException("this.user is null"); //NOI18N
644 } else if (this.getUser().getUserId() == null) {
646 throw new NullPointerException("this.user.userId is null"); //NOI18N
647 } else if (this.getUser().getUserId() < 1) {
649 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
650 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.LOCKED) {
651 // User account is locked
652 throw new FacesException(new UserStatusLockedException(this.getUser()));
653 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
654 // User account is locked
655 throw new FaceletException(new UserStatusUnconfirmedException(this.getUser()));
656 } else if (this.getUserLockReason() == null) {
658 throw new NullPointerException("this.userLockReason is null"); //NOI18N
659 } else if (this.getUserLockReason().isEmpty()) {
661 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
664 // Init updated user instance
665 final User updatedUser;
669 final String baseUrl = FacesUtils.generateBaseUrl();
671 // Call EJB to lock account
672 updatedUser = this.adminUserBean.lockUserAccount(this.getUser(), this.getUserLockReason(), baseUrl);
673 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
675 throw new FaceletException(ex);
679 this.userLockedEvent.fire(new AdminLockedUserEvent(updatedUser));
684 // Should go fine at this point, redirect to user profile
685 return "admin_show_user"; //NOI18N
689 * Unlocks selected user's account. This method makes sure that the account
692 * @return Redirect outcome
694 public String unlockUserAccount () {
695 // Is the user instance valid and CONFIRMED?
696 if (this.getUser() == null) {
698 throw new NullPointerException("this.user is null"); //NOI18N
699 } else if (this.getUser().getUserId() == null) {
701 throw new NullPointerException("this.user.userId is null"); //NOI18N
702 } else if (this.getUser().getUserId() < 1) {
704 throw new IllegalArgumentException(MessageFormat.format("this.user.userId={0} is not valid", this.getUser().getUserId())); //NOI18N
705 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
706 // User account is locked
707 throw new FacesException(new UserStatusConfirmedException(this.getUser()));
708 } else if (this.getUser().getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
709 // User account is locked
710 throw new FaceletException(new UserStatusUnconfirmedException(this.getUser()));
713 // Init updated user instance
714 final User updatedUser;
718 final String baseUrl = FacesUtils.generateBaseUrl();
720 // Call EJB to unlock account
721 updatedUser = this.adminUserBean.unlockUserAccount(this.getUser(), baseUrl);
722 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
724 throw new FaceletException(ex);
728 this.userUnlockedEvent.fire(new AdminUnlockedUserEvent(updatedUser));
733 // Should go fine at this point, redirect to user profile
734 return "admin_show_user"; //NOI18N
740 private void clear () {
742 this.setContact(null);
743 this.setUserLockReason(null);
744 this.setUserMustChangePassword(null);
745 this.setUserName(null);
749 * Checks if same password is entered and that they are not empty.
751 * @return Whether the same password was entered
753 private boolean isSamePasswordEntered () {
754 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));