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.delete.AdminDeletedUserEvent;
43 import org.mxchange.jusercore.events.user.delete.ObservableAdminDeletedUserEvent;
44 import org.mxchange.jusercore.events.user.helper.created.ObservableHelperCreatedUserEvent;
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;
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;
137 private UserSessionBeanRemote userBean;
140 * Regular user controller
143 private JobsUserWebSessionController userController;
148 private String userDeleteReason;
151 * An event fired when the administrator has linked a user with existing
156 private Event<ObservableAdminLinkedUserEvent> userLinkedEvent;
161 private String userLockReason;
164 * Event being fired when an administrator has locked a user
168 private Event<ObservableAdminLockedUserEvent> userLockedEvent;
171 * Flag whether user must change password after login
173 private Boolean userMustChangePassword;
178 private String userName;
181 * User password (clear-text from web form)
183 private String userPassword;
186 * User password repeated (clear-text from web form)
188 private String userPasswordRepeat;
191 * Event being fired when administrator unlocks an account
195 private Event<ObservableAdminUnlockedUserEvent> userUnlockedEvent;
198 * Default constructor
200 public JobsAdminUserWebRequestBean () {
201 // Call super constructor
206 * Adds user instance to database by preparing a complete user instance and
207 * sending it to the EJB. The data set in the controller is being verified,
208 * e.g. if the user name or email address is not used yet.
210 * @return Redirect outcome
212 public String addUser () {
213 // Get contact from bean helper to "cache" it locally
214 Contact contact = this.beanHelper.getContact();
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 (contact == 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 User user = new LoginUser();
231 // Set user name, CONFIRMED and INVISIBLE
232 user.setUserName(this.getUserName());
233 user.setUserMustChangePassword(this.getUserMustChangePassword());
234 user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
235 user.setUserProfileMode(ProfileMode.INVISIBLE);
238 user.setUserLocale(this.localizationController.getLocale());
243 // Is a contact instance in helper set?
244 if (contact instanceof Contact) {
245 // Then use it for contact linking
246 userContact = contact;
248 // Create contact instance
249 userContact = this.contactController.createContactInstance();
252 // Set contact in user
253 user.setUserContact(userContact);
255 // Init variable for password
256 String password = null;
258 // Is the user name or email address used already?
259 // @TODO Add password length check
260 if (this.userController.isUserNameRegistered(user)) {
261 // User name is already used
262 throw new FaceletException(new UserNameAlreadyRegisteredException(user));
263 } else if ((contact == null) && (this.contactController.isEmailAddressRegistered(user.getUserContact()))) {
264 // Email address is already used
265 this.showFacesMessage("admin_add_user:emailAddress", "ERROR_EMAIL_ADDRESS_ALREADY_USED"); //NOI18N
267 // Always clear password
268 this.setUserPassword(null);
269 this.setUserPasswordRepeat(null);
273 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
274 // Empty password entered, then generate one
275 password = UserLoginUtils.createRandomPassword(JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
276 } else if (!this.isSamePasswordEntered()) {
277 // Both passwords don't match
278 throw new FaceletException(new UserPasswordRepeatMismatchException(user));
280 // Both match, so get it from this bean
281 password = this.getUserPassword();
284 // The password should not be null and at least 5 characters long
285 assert (password != null) : "password is null"; //NOI18N
286 assert (password.length() >= JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
288 // Encrypt password and set it
289 user.setUserEncryptedPassword(UserLoginUtils.encryptPassword(password));
292 // Now, that all is set, call EJB
293 if (contact instanceof Contact) {
294 // Link contact with this user
295 User updatedUser = this.adminUserBean.linkUser(user);
298 this.userLinkedEvent.fire(new AdminLinkedUserEvent(updatedUser));
301 User updatedUser = this.adminUserBean.addUser(user);
304 this.addedUserEvent.fire(new AdminAddedUserEvent(updatedUser));
306 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
308 throw new FaceletException(ex);
312 this.beanHelper.setContact(null);
317 // Return to user list (for now)
318 return "admin_list_user"; //NOI18N
322 * Event observer for when a bean helper has successfully created a user
323 * instance, means the user exists. If the user does not exist, this event
324 * should not fire but instead a proper exception must be thrown.
326 * @param event User created event
328 public void afterHelperCreatedUserEvent (@Observes final ObservableHelperCreatedUserEvent event) {
329 // Is the instance valid?
332 throw new NullPointerException("event is null"); //NOI18N
333 } else if (event.getCreatedUser() == null) {
335 throw new NullPointerException("event.createdUser is null"); //NOI18N
336 } else if (event.getCreatedUser().getUserId() == null) {
338 throw new NullPointerException("event.createdUser.userId is null"); //NOI18N
339 } else if (event.getCreatedUser().getUserId() < 1) {
341 throw new NullPointerException(MessageFormat.format("event.createdUser.userId={0} is not valid", event.getCreatedUser().getUserId())); //NOI18N
345 User user = event.getCreatedUser();
347 // Set all fields here
348 this.setUserName(user.getUserName());
349 this.setUserLockReason(user.getUserLastLockedReason());
353 * Event observer for new user registrations
355 * @param event User registration event
357 public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
358 // event should not be null
361 throw new NullPointerException("event is null"); //NOI18N
362 } else if (event.getRegisteredUser() == null) {
364 throw new NullPointerException("event.user is null"); //NOI18N
365 } else if (event.getRegisteredUser().getUserId() == null) {
367 throw new NullPointerException("event.user.userId is null"); //NOI18N
368 } else if (event.getRegisteredUser().getUserId() < 1) {
370 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
374 User registeredUser = event.getRegisteredUser();
376 // @TODO Nothing to do with the user here?
382 * Deletes given user account
384 * @return Redirect outcome
386 public String deleteUserData () {
387 // Get user instance into local variable
388 User user = this.beanHelper.getUser();
390 // Is the user instance valid and CONFIRMED?
393 throw new NullPointerException("user is null"); //NOI18N
394 } else if (user.getUserId() == null) {
396 throw new NullPointerException("user.userId is null"); //NOI18N
397 } else if (user.getUserId() < 1) {
399 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
403 // All fine, delete it
404 this.adminUserBean.deleteUser(user, 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(user, 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 () {
424 User user = this.beanHelper.getUser();
426 // Null password means not setting it
427 String encryptedPassword = null;
429 // Check if user instance is in helper and valid
432 throw new NullPointerException("beanHelper.user is null"); //NOI18N
433 } else if (user.getUserId() == null) {
435 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
436 } else if (user.getUserId() < 1) {
438 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N
439 } else if (this.getUserName() == null) {
440 // Not all required fields are set
441 throw new NullPointerException("this.userName is null"); //NOI18N
442 } else if (this.getUserName().isEmpty()) {
443 // Not all required fields are set
444 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
445 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
446 // Clear password fields
447 this.setUserPassword(null);
448 this.setUserPasswordRepeat(null);
450 // Not same password entered
451 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT"); //NOI18N
453 } else if ((!Objects.equals(user.getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
457 // User name already exists
458 this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS"); //NOI18N
460 } else if (this.isSamePasswordEntered()) {
461 // Same password entered, create container
462 if ((Objects.equals(user.getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserLoginUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword())))) {
463 // Clear password fields
464 this.setUserPassword(null);
465 this.setUserPasswordRepeat(null);
467 // Same password entered
468 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD"); //NOI18N
473 encryptedPassword = UserLoginUtils.encryptPassword(this.getUserPassword());
476 // Set user name and flag
477 user.setUserName(this.getUserName());
478 user.setUserMustChangePassword(this.getUserMustChangePassword());
480 // Is a password set?
481 if (encryptedPassword != null) {
483 user.setUserEncryptedPassword(encryptedPassword);
486 // Call EJB for updating user data
487 User updatedUser = this.userBean.updateUserData(user);
490 this.updatedUserDataEvent.fire(new AdminUpdatedUserDataEvent(updatedUser));
492 // Return to user list (for now)
493 return "admin_list_user"; //NOI18N
497 * Getter for user delete reason
499 * @return User delete reason
501 public String getUserDeleteReason () {
502 return this.userDeleteReason;
506 * Setter for user delete reason
508 * @param userDeleteReason User delete reason
510 public void setUserDeleteReason (final String userDeleteReason) {
511 this.userDeleteReason = userDeleteReason;
515 * Getter for user lock reason
517 * @return User lock reason
519 public String getUserLockReason () {
520 return this.userLockReason;
524 * Setter for user lock reason
526 * @param userLockReason User lock reason
528 public void setUserLockReason (final String userLockReason) {
529 this.userLockReason = userLockReason;
533 * Getter for flag if user needs to change password
535 * @return Flag if user needs to change password
537 public Boolean getUserMustChangePassword () {
538 return this.userMustChangePassword;
542 * Setter for flag if user needs to change password
544 * @param userMustChangePassword Flag if user needs to change password
546 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
547 this.userMustChangePassword = userMustChangePassword;
551 * Getter for user name
555 public String getUserName () {
556 return this.userName;
560 * Setter for user name
562 * @param userName User name
564 public void setUserName (final String userName) {
565 this.userName = userName;
569 * Getter for clear-text user password
571 * @return Clear-text user password
573 public String getUserPassword () {
574 return this.userPassword;
578 * Setter for clear-text user password
580 * @param userPassword Clear-text user password
582 public void setUserPassword (final String userPassword) {
583 this.userPassword = userPassword;
587 * Getter for clear-text user password repeated
589 * @return Clear-text user password repeated
591 public String getUserPasswordRepeat () {
592 return this.userPasswordRepeat;
596 * Setter for clear-text user password repeated
598 * @param userPasswordRepeat Clear-text user password repeated
600 public void setUserPasswordRepeat (final String userPasswordRepeat) {
601 this.userPasswordRepeat = userPasswordRepeat;
605 * Post-construction method
608 public void init () {
611 // Get initial context
612 Context context = new InitialContext();
615 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
616 this.adminUserBean = (AdminUserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/adminUser!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote"); //NOI18N
617 } catch (final NamingException e) {
619 throw new FaceletException(e);
624 * Locks selected user's account. This method makes sure that a lock reason
625 * is provided that th user later can read on login attempts.
627 * @return Redirect outcome
629 public String lockUserAccount () {
631 User user = this.beanHelper.getUser();
633 // Is the user instance valid and CONFIRMED?
636 throw new NullPointerException("user is null"); //NOI18N
637 } else if (user.getUserId() == null) {
639 throw new NullPointerException("user.userId is null"); //NOI18N
640 } else if (user.getUserId() < 1) {
642 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
643 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
644 // User account is locked
645 throw new FacesException(new UserStatusLockedException(user));
646 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
647 // User account is locked
648 throw new FaceletException(new UserStatusUnconfirmedException(user));
649 } else if (this.getUserLockReason() == null) {
651 throw new NullPointerException("this.userLockReason is null"); //NOI18N
652 } else if (this.getUserLockReason().isEmpty()) {
654 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
657 // Init updated user instance
662 String baseUrl = FacesUtils.generateBaseUrl();
664 // Call EJB to lock account
665 updatedUser = this.adminUserBean.lockUserAccount(user, this.getUserLockReason(), baseUrl);
666 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
668 throw new FaceletException(ex);
672 this.userLockedEvent.fire(new AdminLockedUserEvent(updatedUser));
677 // Should go fine at this point, redirect to user profile
678 return "admin_show_user"; //NOI18N
682 * Unlocks selected user's account. This method makes sure that the account
685 * @return Redirect outcome
687 public String unlockUserAccount () {
689 User user = this.beanHelper.getUser();
691 // Is the user instance valid and CONFIRMED?
694 throw new NullPointerException("user is null"); //NOI18N
695 } else if (user.getUserId() == null) {
697 throw new NullPointerException("user.userId is null"); //NOI18N
698 } else if (user.getUserId() < 1) {
700 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
701 } else if (user.getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
702 // User account is locked
703 throw new FacesException(new UserStatusConfirmedException(user));
704 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
705 // User account is locked
706 throw new FaceletException(new UserStatusUnconfirmedException(user));
709 // Init updated user instance
714 String baseUrl = FacesUtils.generateBaseUrl();
716 // Call EJB to unlock account
717 updatedUser = this.adminUserBean.unlockUserAccount(user, baseUrl);
718 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
720 throw new FaceletException(ex);
724 this.userUnlockedEvent.fire(new AdminUnlockedUserEvent(updatedUser));
729 // Should go fine at this point, redirect to user profile
730 return "admin_show_user"; //NOI18N
736 private void clear () {
739 this.setUserName(null);
740 this.setUserPassword(null);
741 this.setUserPasswordRepeat(null);
742 this.setUserMustChangePassword(null);
746 * Checks if same password is entered and that they are not empty.
748 * @return Whether the same password was entered
750 private boolean isSamePasswordEntered () {
751 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));