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.container.login.UserLoginContainer;
41 import org.mxchange.jusercore.events.registration.ObservableUserRegisteredEvent;
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.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.UserPasswordRepeatMismatchException;
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.UserUtils;
66 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
67 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
70 * A user controller (bean)
72 * @author Roland Häder<roland@mxchange.org>
74 @Named ("adminUserController")
76 public class JobsAdminUserWebRequestBean extends BaseJobsController implements JobsAdminUserWebRequestController {
81 private static final long serialVersionUID = 542_145_347_916L;
84 * An event fired when the administrator has added a new user
88 private Event<ObservableAdminAddedUserEvent> addedUserEvent;
91 * Regular contact controller
94 private JobsAdminContactWebRequestController adminContactController;
97 * Administrative user EJB
99 private AdminUserSessionBeanRemote adminUserBean;
105 private JobsWebRequestHelperController beanHelper;
108 * Regular contact controller
111 private JobsContactWebSessionController contactController;
114 * Event being fired when admin has deleted user
118 private Event<ObservableAdminDeletedUserEvent> deleteUserEvent;
121 * Localization controller
124 private JobsLocalizationSessionController localizationController;
127 * An event fired when the administrator has updated a new user
131 private Event<ObservableAdminUpdatedUserDataEvent> updatedUserDataEvent;
136 private UserSessionBeanRemote userBean;
139 * Regular user controller
142 private JobsUserWebSessionController userController;
147 private String userDeleteReason;
150 * An event fired when the administrator has linked a user with existing
155 private Event<ObservableAdminLinkedUserEvent> userLinkedEvent;
160 private String userLockReason;
163 * Event being fired when an administrator has locked a user
167 private Event<ObservableAdminLockedUserEvent> userLockedEvent;
170 * Flag whether user must change password after login
172 private Boolean userMustChangePassword;
177 private String userName;
180 * User password (clear-text from web form)
182 private String userPassword;
185 * User password repeated (clear-text from web form)
187 private String userPasswordRepeat;
190 * Event being fired when admin unlocks an account
194 private Event<ObservableAdminUnlockedUserEvent> userUnlockedEvent;
197 * Default constructor
199 public JobsAdminUserWebRequestBean () {
200 // Call super constructor
205 public String addUser () {
206 // As the form cannot validate the data (required="true"), check it here
207 if (this.getUserName() == null) {
209 throw new NullPointerException("userName is null"); //NOI18N
210 } else if (this.getUserName().isEmpty()) {
212 throw new IllegalArgumentException("userName is null"); //NOI18N
213 } else if (this.beanHelper.getContact() == null) {
214 // No contact instance set, so test required fields: gender, first name and family name
215 if (this.contactController.getPersonalTitle() == null) {
217 throw new NullPointerException("contactController.gender is null"); //NOI18N
218 } else if (this.contactController.getFirstName() == null) {
220 throw new NullPointerException("contactController.firstName is null"); //NOI18N
221 } else if (this.adminContactController.getFirstName().isEmpty()) {
223 throw new IllegalArgumentException("contactController.firstName is empty"); //NOI18N
224 } else if (this.adminContactController.getFamilyName() == null) {
226 throw new NullPointerException("contactController.familyName is null"); //NOI18N
227 } else if (this.contactController.getFamilyName().isEmpty()) {
229 throw new IllegalArgumentException("contactController.familyName is empty"); //NOI18N
230 } else if (this.adminContactController.getEmailAddress() == null) {
232 throw new NullPointerException("contactController.emailAddress is null"); //NOI18N
233 } else if (this.adminContactController.getEmailAddress().isEmpty()) {
235 throw new IllegalArgumentException("contactController.emailAddress is empty"); //NOI18N
239 // Create new user instance
240 User user = new LoginUser();
242 // Set user name, CONFIRMED and INVISIBLE
243 user.setUserName(this.getUserName());
244 user.setUserMustChangePassword(this.getUserMustChangePassword());
245 user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
246 user.setUserProfileMode(ProfileMode.INVISIBLE);
251 // Is a contact instance in helper set?
252 if (this.beanHelper.getContact() instanceof Contact) {
253 // Then use it for contact linking
254 contact = this.beanHelper.getContact();
256 // Create contact instance
257 contact = this.contactController.createContactInstance();
260 // Set contact in user
261 user.setUserContact(contact);
263 // Init variable for password
264 String password = null;
266 // Is the user name or email address used already?
267 // @TODO Add password length check
268 if (this.userController.isUserNameRegistered(user)) {
269 // User name is already used
270 throw new FaceletException(new UserNameAlreadyRegisteredException(user));
271 } else if ((this.beanHelper.getContact() == null) && (this.contactController.isEmailAddressRegistered(user.getUserContact()))) {
272 // Email address is already used
273 this.showFacesMessage("admin_add_user:emailAddress", "ERROR_EMAIL_ADDRESS_ALREADY_USED"); //NOI18N
275 // Always clear password
276 this.setUserPassword(null);
277 this.setUserPasswordRepeat(null);
281 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
282 // Empty password entered, then generate one
283 password = UserUtils.createRandomPassword(JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
284 } else if (!this.isSamePasswordEntered()) {
285 // Both passwords don't match
286 throw new FaceletException(new UserPasswordRepeatMismatchException(user));
288 // Both match, so get it from this bean
289 password = this.getUserPassword();
292 // The password should not be null and at least 5 characters long
293 assert (password != null) : "password is null"; //NOI18N
294 assert (password.length() >= JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
296 // Encrypt password and set it
297 user.setUserEncryptedPassword(UserUtils.encryptPassword(password));
300 // Now, that all is set, call EJB
301 if (this.beanHelper.getContact() instanceof Contact) {
302 // Link contact with this user
303 User updatedUser = this.adminUserBean.linkUser(user);
306 this.userLinkedEvent.fire(new AdminLinkedUserEvent(updatedUser));
308 // Remove contact instance
309 this.beanHelper.setContact(null);
312 User updatedUser = this.adminUserBean.addUser(user);
315 this.addedUserEvent.fire(new AdminAddedUserEvent(updatedUser));
317 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
319 throw new FaceletException(ex);
323 this.beanHelper.setContact(null);
328 // Return to user list (for now)
329 return "admin_list_user"; //NOI18N
333 * Event observer for new user registrations
335 * @param event User registration event
337 public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
338 // event should not be null
341 throw new NullPointerException("event is null"); //NOI18N
342 } else if (event.getRegisteredUser() == null) {
344 throw new NullPointerException("event.user is null"); //NOI18N
345 } else if (event.getRegisteredUser().getUserId() == null) {
347 throw new NullPointerException("event.user.userId is null"); //NOI18N
348 } else if (event.getRegisteredUser().getUserId() < 1) {
350 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
354 User registeredUser = event.getRegisteredUser();
356 // @TODO Nothing to do with the user here?
362 public String deleteUserData (final User user) {
363 // Is the user instance valid and CONFIRMED?
366 throw new NullPointerException("user is null"); //NOI18N
367 } else if (user.getUserId() == null) {
369 throw new NullPointerException("user.userId is null"); //NOI18N
370 } else if (user.getUserId() < 1) {
372 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
376 // All fine, delete it
377 this.adminUserBean.deleteUser(user, this.getUserDeleteReason());
378 } catch (final UserNotFoundException ex) {
379 // Should not happen, so throw again
380 throw new FaceletException(ex);
384 this.deleteUserEvent.fire(new AdminDeletedUserEvent(user, this.getUserDeleteReason()));
387 return "admin_list_user"; //NOI18N
391 public String editUserData () {
393 User user = this.beanHelper.getUser();
395 // Null password means not setting it
396 String encryptedPassword = null;
398 // Check if user instance is in helper and valid
401 throw new NullPointerException("beanHelper.user is null"); //NOI18N
402 } else if (user.getUserId() == null) {
404 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
405 } else if (user.getUserId() < 1) {
407 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N
408 } else if (this.getUserName() == null) {
409 // Not all required fields are set
410 throw new NullPointerException("this.userName is null"); //NOI18N
411 } else if (this.getUserName().isEmpty()) {
412 // Not all required fields are set
413 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
414 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
415 // Clear password fields
416 this.setUserPassword(null);
417 this.setUserPasswordRepeat(null);
419 // Not same password entered
420 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT"); //NOI18N
422 } else if ((!Objects.equals(user.getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
426 // User name already exists
427 this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS"); //NOI18N
429 } else if (this.isSamePasswordEntered()) {
430 // Same password entered, create container
431 if ((Objects.equals(user.getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword())))) {
432 // Clear password fields
433 this.setUserPassword(null);
434 this.setUserPasswordRepeat(null);
436 // Same password entered
437 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD"); //NOI18N
442 encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
445 // Set user name and flag
446 user.setUserName(this.getUserName());
447 user.setUserMustChangePassword(this.getUserMustChangePassword());
449 // Is a password set?
450 if (encryptedPassword != null) {
452 user.setUserEncryptedPassword(encryptedPassword);
455 // Call EJB for updating user data
456 User updatedUser = this.userBean.updateUserData(user);
459 this.updatedUserDataEvent.fire(new AdminUpdatedUserDataEvent(updatedUser));
461 // Return to user list (for now)
462 return "admin_list_user"; //NOI18N
466 public String getUserDeleteReason () {
467 return this.userDeleteReason;
471 public void setUserDeleteReason (final String userDeleteReason) {
472 this.userDeleteReason = userDeleteReason;
476 public String getUserLockReason () {
477 return this.userLockReason;
481 public void setUserLockReason (final String userLockReason) {
482 this.userLockReason = userLockReason;
486 public Boolean getUserMustChangePassword () {
487 return this.userMustChangePassword;
491 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
492 this.userMustChangePassword = userMustChangePassword;
496 public String getUserName () {
497 return this.userName;
501 public void setUserName (final String userName) {
502 this.userName = userName;
506 public String getUserPassword () {
507 return this.userPassword;
511 public void setUserPassword (final String userPassword) {
512 this.userPassword = userPassword;
516 public String getUserPasswordRepeat () {
517 return this.userPasswordRepeat;
521 public void setUserPasswordRepeat (final String userPasswordRepeat) {
522 this.userPasswordRepeat = userPasswordRepeat;
526 * Post-construction method
529 public void init () {
532 // Get initial context
533 Context context = new InitialContext();
536 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
537 this.adminUserBean = (AdminUserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/adminUser!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote"); //NOI18N
538 } catch (final NamingException e) {
540 throw new FaceletException(e);
545 public String lockUserAccount (final User user) {
546 // Is the user instance valid and CONFIRMED?
549 throw new NullPointerException("user is null"); //NOI18N
550 } else if (user.getUserId() == null) {
552 throw new NullPointerException("user.userId is null"); //NOI18N
553 } else if (user.getUserId() < 1) {
555 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
556 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
557 // User account is locked
558 throw new FacesException(new UserStatusLockedException(user));
559 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
560 // User account is locked
561 throw new FaceletException(new UserStatusUnconfirmedException(user));
562 } else if (this.getUserLockReason() == null) {
564 throw new NullPointerException("this.userLockReason is null"); //NOI18N
565 } else if (this.getUserLockReason().isEmpty()) {
567 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
570 // Init updated user instance
575 String baseUrl = FacesUtils.generateBaseUrl();
577 // Call EJB to lock account
578 updatedUser = this.adminUserBean.lockUserAccount(user, this.getUserLockReason(), baseUrl);
579 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
581 throw new FaceletException(ex);
585 this.userLockedEvent.fire(new AdminLockedUserEvent(updatedUser));
590 // Should go fine at this point, redirect to user profile
591 return "admin_show_user"; //NOI18N
595 public String unlockUserAccount (final User user) {
596 // Is the user instance valid and CONFIRMED?
599 throw new NullPointerException("user is null"); //NOI18N
600 } else if (user.getUserId() == null) {
602 throw new NullPointerException("user.userId is null"); //NOI18N
603 } else if (user.getUserId() < 1) {
605 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
606 } else if (user.getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
607 // User account is locked
608 throw new FacesException(new UserStatusConfirmedException(user));
609 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
610 // User account is locked
611 throw new FaceletException(new UserStatusUnconfirmedException(user));
614 // Init updated user instance
619 String baseUrl = FacesUtils.generateBaseUrl();
621 // Call EJB to unlock account
622 updatedUser = this.adminUserBean.unlockUserAccount(user, baseUrl);
623 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
625 throw new FaceletException(ex);
629 this.userUnlockedEvent.fire(new AdminUnlockedUserEvent(updatedUser));
634 // Should go fine at this point, redirect to user profile
635 return "admin_show_user"; //NOI18N
641 private void clear () {
644 this.setUserName(null);
645 this.setUserPassword(null);
646 this.setUserPasswordRepeat(null);
647 this.setUserMustChangePassword(null);
651 * Checks if same password is entered and that they are not empty.
653 * @return Whether the same password was entered
655 private boolean isSamePasswordEntered () {
656 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));