2 * Copyright (C) 2016 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.pizzaapplication.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.jusercore.container.login.UserLoginContainer;
36 import org.mxchange.jusercore.events.registration.ObservableUserRegisteredEvent;
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.delete.AdminDeletedUserEvent;
40 import org.mxchange.jusercore.events.user.delete.ObservableAdminDeletedUserEvent;
41 import org.mxchange.jusercore.events.user.linked.AdminLinkedUserEvent;
42 import org.mxchange.jusercore.events.user.linked.ObservableAdminLinkedUserEvent;
43 import org.mxchange.jusercore.events.user.locked.AdminLockedUserEvent;
44 import org.mxchange.jusercore.events.user.locked.ObservableAdminLockedUserEvent;
45 import org.mxchange.jusercore.events.user.unlocked.AdminUnlockedUserEvent;
46 import org.mxchange.jusercore.events.user.unlocked.ObservableAdminUnlockedUserEvent;
47 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
48 import org.mxchange.jusercore.events.user.update.ObservableAdminUpdatedUserDataEvent;
49 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
50 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
51 import org.mxchange.jusercore.exceptions.UserNotFoundException;
52 import org.mxchange.jusercore.exceptions.UserPasswordRepeatMismatchException;
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.UserUtils;
61 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
62 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
63 import org.mxchange.pizzaapplication.beans.BasePizzaController;
64 import org.mxchange.pizzaapplication.beans.contact.PizzaAdminContactWebRequestController;
65 import org.mxchange.pizzaapplication.beans.contact.PizzaContactWebSessionController;
66 import org.mxchange.pizzaapplication.beans.helper.PizzaWebRequestHelperController;
67 import org.mxchange.pizzaapplication.beans.localization.PizzaLocalizationSessionController;
70 * Administrative user bean (controller)
72 * @author Roland Häder<roland@mxchange.org>
74 @Named ("adminUserController")
76 public class PizzaAdminUserWebRequestBean extends BasePizzaController implements PizzaAdminUserWebRequestController {
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 PizzaAdminContactWebRequestController adminContactController;
97 * Administrative user EJB
99 private AdminUserSessionBeanRemote adminUserBean;
105 private PizzaWebRequestHelperController beanHelper;
108 * Regular contact controller
111 private PizzaContactWebSessionController contactController;
114 * Event being fired when admin has deleted user
118 private Event<ObservableAdminDeletedUserEvent> deleteUserEvent;
121 * Localization controller
124 private PizzaLocalizationSessionController 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 PizzaUserWebSessionController 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 PizzaAdminUserWebRequestBean () {
203 public String addUser () {
204 // As the form cannot validate the data (required="true"), check it here
205 if (this.getUserName() == null) {
207 throw new NullPointerException("userName is null"); //NOI18N
208 } else if (this.getUserName().isEmpty()) {
210 throw new IllegalArgumentException("userName is null"); //NOI18N
211 } else if (this.beanHelper.getContact() == null) {
212 // No contact instance set, so test required fields: gender, first name and family name
213 if (this.contactController.getGender() == null) {
215 throw new NullPointerException("contactController.gender is null"); //NOI18N
216 } else if (this.contactController.getFirstName() == null) {
218 throw new NullPointerException("contactController.firstName is null"); //NOI18N
219 } else if (this.adminContactController.getFirstName().isEmpty()) {
221 throw new IllegalArgumentException("contactController.firstName is empty"); //NOI18N
222 } else if (this.adminContactController.getFamilyName() == null) {
224 throw new NullPointerException("contactController.familyName is null"); //NOI18N
225 } else if (this.contactController.getFamilyName().isEmpty()) {
227 throw new IllegalArgumentException("contactController.familyName is empty"); //NOI18N
228 } else if (this.adminContactController.getEmailAddress() == null) {
230 throw new NullPointerException("contactController.emailAddress is null"); //NOI18N
231 } else if (this.adminContactController.getEmailAddress().isEmpty()) {
233 throw new IllegalArgumentException("contactController.emailAddress is empty"); //NOI18N
237 // Create new user instance
238 User user = new LoginUser();
240 // Set user name, CONFIRMED and INVISIBLE
241 user.setUserName(this.getUserName());
242 user.setUserMustChangePassword(this.getUserMustChangePassword());
243 user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
244 user.setUserProfileMode(ProfileMode.INVISIBLE);
249 // Is a contact instance in helper set?
250 if (this.beanHelper.getContact() instanceof Contact) {
251 // Then use it for contact linking
252 contact = this.beanHelper.getContact();
254 // Create contact instance
255 contact = this.contactController.createContactInstance();
258 // Set contact in user
259 user.setUserContact(contact);
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(user)) {
267 // User name is already used
268 throw new FaceletException(new UserNameAlreadyRegisteredException(user));
269 } else if ((this.beanHelper.getContact() == null) && (this.contactController.isEmailAddressRegistered(user.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 = UserUtils.createRandomPassword(PizzaUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
282 } else if (!this.isSamePasswordEntered()) {
283 // Both passwords don't match
284 throw new FaceletException(new UserPasswordRepeatMismatchException(user));
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() >= PizzaUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
294 // Encrypt password and set it
295 user.setUserEncryptedPassword(UserUtils.encryptPassword(password));
298 // Now, that all is set, call EJB
299 if (this.beanHelper.getContact() instanceof Contact) {
300 // Link contact with this user
301 User updatedUser = this.adminUserBean.linkUser(user);
304 this.userLinkedEvent.fire(new AdminLinkedUserEvent(updatedUser));
306 // Remove contact instance
307 this.beanHelper.setContact(null);
310 User updatedUser = this.adminUserBean.addUser(user);
313 this.addedUserEvent.fire(new AdminAddedUserEvent(updatedUser));
315 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
317 throw new FaceletException(ex);
321 this.beanHelper.setContact(null);
326 // Return to user list (for now)
327 return "admin_list_user"; //NOI18N
331 * Event observer for new user registrations
333 * @param event User registration event
335 public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
336 // event should not be null
339 throw new NullPointerException("event is null"); //NOI18N
340 } else if (event.getRegisteredUser() == null) {
342 throw new NullPointerException("event.user is null"); //NOI18N
343 } else if (event.getRegisteredUser().getUserId() == null) {
345 throw new NullPointerException("event.user.userId is null"); //NOI18N
346 } else if (event.getRegisteredUser().getUserId() < 1) {
348 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
352 User registeredUser = event.getRegisteredUser();
354 // @TODO Nothing to do with the user here?
360 public String deleteUserData (final User user) {
361 // Is the user instance valid and CONFIRMED?
364 throw new NullPointerException("user is null"); //NOI18N
365 } else if (user.getUserId() == null) {
367 throw new NullPointerException("user.userId is null"); //NOI18N
368 } else if (user.getUserId() < 1) {
370 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
374 // All fine, delete it
375 this.adminUserBean.deleteUser(user, this.getUserDeleteReason());
376 } catch (final UserNotFoundException ex) {
377 // Should not happen, so throw again
378 throw new FaceletException(ex);
382 this.deleteUserEvent.fire(new AdminDeletedUserEvent(user, this.getUserDeleteReason()));
385 return "admin_list_user"; //NOI18N
389 public String editUserData () {
391 User user = this.beanHelper.getUser();
393 // Null password means not setting it
394 String encryptedPassword = null;
396 // Check if user instance is in helper and valid
399 throw new NullPointerException("beanHelper.user is null"); //NOI18N
400 } else if (user.getUserId() == null) {
402 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
403 } else if (user.getUserId() < 1) {
405 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N
406 } else if (this.getUserName() == null) {
407 // Not all required fields are set
408 throw new NullPointerException("this.userName is null"); //NOI18N
409 } else if (this.getUserName().isEmpty()) {
410 // Not all required fields are set
411 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
412 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
413 // Clear password fields
414 this.setUserPassword(null);
415 this.setUserPasswordRepeat(null);
417 // Not same password entered
418 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT"); //NOI18N
420 } else if ((!Objects.equals(user.getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
424 // User name already exists
425 this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS"); //NOI18N
427 } else if (this.isSamePasswordEntered()) {
428 // Same password entered, create container
429 if ((Objects.equals(user.getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword())))) {
430 // Clear password fields
431 this.setUserPassword(null);
432 this.setUserPasswordRepeat(null);
434 // Same password entered
435 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD"); //NOI18N
440 encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
443 // Set user name and flag
444 user.setUserName(this.getUserName());
445 user.setUserMustChangePassword(this.getUserMustChangePassword());
447 // Is a password set?
448 if (encryptedPassword != null) {
450 user.setUserEncryptedPassword(encryptedPassword);
453 // Call EJB for updating user data
454 User updatedUser = this.userBean.updateUserData(user);
457 this.updatedUserDataEvent.fire(new AdminUpdatedUserDataEvent(updatedUser));
459 // Return to user list (for now)
460 return "admin_list_user"; //NOI18N
464 public String getUserDeleteReason () {
465 return this.userDeleteReason;
469 public void setUserDeleteReason (final String userDeleteReason) {
470 this.userDeleteReason = userDeleteReason;
474 public String getUserLockReason () {
475 return this.userLockReason;
479 public void setUserLockReason (final String userLockReason) {
480 this.userLockReason = userLockReason;
484 public Boolean getUserMustChangePassword () {
485 return this.userMustChangePassword;
489 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
490 this.userMustChangePassword = userMustChangePassword;
494 public String getUserName () {
495 return this.userName;
499 public void setUserName (final String userName) {
500 this.userName = userName;
504 public String getUserPassword () {
505 return this.userPassword;
509 public void setUserPassword (final String userPassword) {
510 this.userPassword = userPassword;
514 public String getUserPasswordRepeat () {
515 return this.userPasswordRepeat;
519 public void setUserPasswordRepeat (final String userPasswordRepeat) {
520 this.userPasswordRepeat = userPasswordRepeat;
524 * Post-construction method
527 public void init () {
530 // Get initial context
531 Context context = new InitialContext();
534 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/pizzaservice-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
535 this.adminUserBean = (AdminUserSessionBeanRemote) context.lookup("java:global/pizzaservice-ejb/adminUser!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote"); //NOI18N
536 } catch (final NamingException e) {
538 throw new FaceletException(e);
543 public String lockUserAccount (final User user) {
544 // Is the user instance valid and CONFIRMED?
547 throw new NullPointerException("user is null"); //NOI18N
548 } else if (user.getUserId() == null) {
550 throw new NullPointerException("user.userId is null"); //NOI18N
551 } else if (user.getUserId() < 1) {
553 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
554 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
555 // User account is locked
556 throw new FacesException(new UserStatusLockedException(user));
557 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
558 // User account is locked
559 throw new FaceletException(new UserStatusUnconfirmedException(user));
560 } else if (this.getUserLockReason() == null) {
562 throw new NullPointerException("this.userLockReason is null"); //NOI18N
563 } else if (this.getUserLockReason().isEmpty()) {
565 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
568 // Init updated user instance
573 String baseUrl = FacesUtils.generateBaseUrl();
575 // Call EJB to lock account
576 updatedUser = this.adminUserBean.lockUserAccount(user, this.getUserLockReason(), baseUrl);
577 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
579 throw new FaceletException(ex);
583 this.userLockedEvent.fire(new AdminLockedUserEvent(updatedUser));
588 // Should go fine at this point, redirect to user profile
589 return "admin_show_user"; //NOI18N
593 public String unlockUserAccount (final User user) {
594 // Is the user instance valid and CONFIRMED?
597 throw new NullPointerException("user is null"); //NOI18N
598 } else if (user.getUserId() == null) {
600 throw new NullPointerException("user.userId is null"); //NOI18N
601 } else if (user.getUserId() < 1) {
603 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
604 } else if (user.getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
605 // User account is locked
606 throw new FacesException(new UserStatusConfirmedException(user));
607 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
608 // User account is locked
609 throw new FaceletException(new UserStatusUnconfirmedException(user));
612 // Init updated user instance
617 String baseUrl = FacesUtils.generateBaseUrl();
619 // Call EJB to unlock account
620 updatedUser = this.adminUserBean.unlockUserAccount(user, baseUrl);
621 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
623 throw new FaceletException(ex);
627 this.userUnlockedEvent.fire(new AdminUnlockedUserEvent(updatedUser));
632 // Should go fine at this point, redirect to user profile
633 return "admin_show_user"; //NOI18N
639 private void clear () {
642 this.setUserName(null);
643 this.setUserPassword(null);
644 this.setUserPasswordRepeat(null);
645 this.setUserMustChangePassword(null);
649 * Checks if same password is entered and that they are not empty.
651 * @return Whether the same password was entered
653 private boolean isSamePasswordEntered () {
654 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));