2 * Copyright (C) 2016 Roland Haeder
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.enterprise.context.RequestScoped;
22 import javax.enterprise.event.Event;
23 import javax.enterprise.event.Observes;
24 import javax.enterprise.inject.Any;
25 import javax.faces.FacesException;
26 import javax.faces.view.facelets.FaceletException;
27 import javax.inject.Inject;
28 import javax.inject.Named;
29 import javax.naming.Context;
30 import javax.naming.InitialContext;
31 import javax.naming.NamingException;
32 import org.mxchange.jcontacts.contact.Contact;
33 import org.mxchange.jcoreee.utils.FacesUtils;
34 import org.mxchange.jusercore.container.login.UserLoginContainer;
35 import org.mxchange.jusercore.events.registration.UserRegisteredEvent;
36 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
37 import org.mxchange.jusercore.events.user.add.AdminUserAddedEvent;
38 import org.mxchange.jusercore.events.user.linked.AdminLinkedUserEvent;
39 import org.mxchange.jusercore.events.user.linked.AdminUserLinkedEvent;
40 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
41 import org.mxchange.jusercore.events.user.update.AdminUserDataUpdatedEvent;
42 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
43 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
44 import org.mxchange.jusercore.exceptions.UserNotFoundException;
45 import org.mxchange.jusercore.exceptions.UserPasswordRepeatMismatchException;
46 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
47 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
48 import org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote;
49 import org.mxchange.jusercore.model.user.LoginUser;
50 import org.mxchange.jusercore.model.user.User;
51 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
52 import org.mxchange.jusercore.model.user.UserUtils;
53 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
54 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
55 import org.mxchange.pizzaapplication.beans.BasePizzaController;
56 import org.mxchange.pizzaapplication.beans.contact.PizzaAdminContactWebRequestController;
57 import org.mxchange.pizzaapplication.beans.contact.PizzaContactWebSessionController;
58 import org.mxchange.pizzaapplication.beans.helper.PizzaWebRequestController;
61 * Administrative user bean (controller)
63 * @author Roland Haeder<roland@mxchange.org>
65 @Named ("adminUserController")
67 public class PizzaAdminUserWebRequestBean extends BasePizzaController implements PizzaAdminUserWebRequestController {
72 private static final long serialVersionUID = 542_145_347_916L;
75 * An event fired when the administrator has added a new user
79 private Event<AdminAddedUserEvent> addedUserEvent;
82 * Regular contact controller
85 private PizzaAdminContactWebRequestController adminContactController;
88 * Administrative user EJB
90 private final AdminUserSessionBeanRemote adminUserBean;
93 * Admin helper instance
96 private PizzaWebRequestController beanHelper;
99 * Regular contact controller
102 private PizzaContactWebSessionController contactController;
105 * An event fired when the administrator has updated a new user
109 private Event<AdminUpdatedUserDataEvent> updatedUserDataEvent;
114 private final UserSessionBeanRemote userBean;
117 * Regular user controller
120 private PizzaUserWebSessionController userController;
123 * An event fired when the administrator has linked a user with existing
128 private Event<AdminLinkedUserEvent> userLinkedEvent;
133 private String userLockReason;
136 * Flag whether user must change password after login
138 private Boolean userMustChangePassword;
143 private String userName;
146 * User password (unencrypted from web form)
148 private String userPassword;
151 * User password repeated (unencrypted from web form)
153 private String userPasswordRepeat;
156 * Default constructor
158 public PizzaAdminUserWebRequestBean () {
161 // Get initial context
162 Context context = new InitialContext();
165 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/pizzaservice-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
166 this.adminUserBean = (AdminUserSessionBeanRemote) context.lookup("java:global/pizzaservice-ejb/user!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote"); //NOI18N
167 } catch (final NamingException e) {
169 throw new FaceletException(e);
174 public String addUser () {
175 // Create new user instance
176 User user = new LoginUser();
178 // As the form cannot validate the data (required="true"), check it here
179 if (this.getUserName() == null) {
181 throw new NullPointerException("userName is null"); //NOI18N
182 } else if (this.getUserName().isEmpty()) {
184 throw new IllegalArgumentException("userName is null"); //NOI18N
185 } else if (this.beanHelper.getContact() == null) {
186 // No contact instance set, so test required fields: gender, first name and family name
187 if (this.contactController.getGender() == null) {
189 throw new NullPointerException("contactController.gender is null"); //NOI18N
190 } else if (this.contactController.getFirstName() == null) {
192 throw new NullPointerException("contactController.firstName is null"); //NOI18N //NOI18N
193 } else if (this.contactController.getFirstName().isEmpty()) {
195 throw new IllegalArgumentException("contactController.firstName is empty"); //NOI18N
196 } else if (this.adminContactController.getFamilyName() == null) {
198 throw new NullPointerException("contactController.familyName is null"); //NOI18N
199 } else if (this.contactController.getFamilyName().isEmpty()) {
201 throw new IllegalArgumentException("contactController.familyName is empty"); //NOI18N //NOI18N
202 } else if (this.contactController.getEmailAddress() == null) {
204 throw new NullPointerException("contactController.emailAddress is null"); //NOI18N
205 } else if (this.adminContactController.getEmailAddress().isEmpty()) {
207 throw new IllegalArgumentException("contactController.emailAddress is empty"); //NOI18N //NOI18N
208 } else if (this.contactController.getEmailAddressRepeat() == null) {
210 throw new NullPointerException("contactController.emailAddressRepeat is null");
211 } else if (this.contactController.getEmailAddressRepeat().isEmpty()) {
213 throw new IllegalArgumentException("contactController.emailAddressRepeat is empty"); //NOI18N //NOI18N
214 } else if (!Objects.equals(this.contactController.getEmailAddress(), this.contactController.getEmailAddressRepeat())) {
215 // Is not same email address
216 throw new IllegalArgumentException("Both entered email addresses don't match.");
220 // Set user name, CONFIRMED and INVISIBLE
221 user.setUserName(this.getUserName());
222 user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
223 user.setUserProfileMode(ProfileMode.INVISIBLE);
228 // Is a contact instance in helper set?
229 if (this.beanHelper.getContact() instanceof Contact) {
230 // Then use it for contact linking
231 contact = this.beanHelper.getContact();
233 // Create contact instance
234 contact = this.contactController.createContactInstance();
237 // Set contact in user
238 user.setUserContact(contact);
240 // Init variable for password
241 String password = null;
243 // Is the user name or email address used already?
244 // @TODO Add password length check
245 if (this.userController.isUserNameRegistered(user)) {
246 // User name is already used
247 throw new FaceletException(new UserNameAlreadyRegisteredException(user));
248 } else if ((this.beanHelper.getContact() == null) && (this.contactController.isEmailAddressRegistered(user.getUserContact()))) {
249 // Email address is already used
250 throw new FaceletException(new EmailAddressAlreadyRegisteredException(user));
251 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
252 // Empty password entered, then generate one
253 password = UserUtils.createRandomPassword(PizzaUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
254 } else if (!this.isSamePasswordEntered()) {
255 // Both passwords don't match
256 throw new FaceletException(new UserPasswordRepeatMismatchException(user));
258 // Both match, so get it from this bean
259 password = this.getUserPassword();
262 // The password should not be null and at least 5 characters long
263 assert (password != null) : "password is null"; //NOI18N
264 assert (password.length() >= PizzaUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
266 // Encrypt password and set it
267 user.setUserEncryptedPassword(UserUtils.encryptPassword(password));
270 // Now, that all is set, call EJB
271 if (this.beanHelper.getContact() instanceof Contact) {
272 // Link contact with this user
273 User updatedUser = this.adminUserBean.linkUser(user);
276 this.userLinkedEvent.fire(new AdminUserLinkedEvent(updatedUser));
278 // Remove contact instance
279 this.beanHelper.setContact(null);
282 User updatedUser = this.adminUserBean.addUser(user);
285 this.addedUserEvent.fire(new AdminUserAddedEvent(updatedUser));
287 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
289 throw new FaceletException(ex);
295 // Return to user list (for now)
296 return "admin_list_user"; //NOI18N
300 public void afterRegistrationEvent (@Observes final UserRegisteredEvent event) {
302 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("AdminUserWebBean:afterRegistration: event={0} - CALLED!", event)); //NOI18N
304 // event should not be null
307 throw new NullPointerException("event is null"); //NOI18N
308 } else if (event.getRegisteredUser() == null) {
310 throw new NullPointerException("event.user is null"); //NOI18N
311 } else if (event.getRegisteredUser().getUserId() == null) {
313 throw new NullPointerException("event.user.userId is null"); //NOI18N
314 } else if (event.getRegisteredUser().getUserId() < 1) {
316 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
320 User registeredUser = event.getRegisteredUser();
323 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterRegistration: registeredUser={0}", registeredUser)); //NOI18N
329 //* NOISY-DEBUG: */ System.out.println("AdminUserWebBean:afterRegistration: EXIT!"); //NOI18N
333 public String editUserData () {
335 User user = this.beanHelper.getUser();
337 // Null password means not setting it
338 String encryptedPassword = null;
340 // Check if user instance is in helper and valid
343 throw new NullPointerException("beanHelper.user is null"); //NOI18N
344 } else if (user.getUserId() == null) {
346 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N //NOI18N
347 } else if (user.getUserId() < 1) {
349 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N //NOI18N
350 } else if (this.getUserName() == null) {
351 // Not all required fields are set
352 throw new NullPointerException("this.userName is null"); //NOI18N
353 } else if (this.getUserName().isEmpty()) {
354 // Not all required fields are set
355 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
356 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
357 // Not same password entered
358 this.setUserPassword(null);
359 this.setUserPasswordRepeat(null);
362 throw new FaceletException("Not same password entered"); //NOI18N
363 } else if (this.userBean.ifUserNameExists(this.getUserName())) {
364 // User name already exists
365 throw new FaceletException(new UserNameAlreadyRegisteredException(this.getUserName()));
366 } else if (this.isSamePasswordEntered()) {
367 // Same password entered, create container
368 if (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword()))) {
369 // Same password entered
370 throw new FaceletException("Same password as stored entered."); //NOI18N
374 encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
377 // Set user name and flag
378 user.setUserName(this.getUserName());
379 user.setUserMustChangePassword(this.getUserMustChangePassword());
381 // Is a password set?
382 if (encryptedPassword != null) {
384 user.setUserEncryptedPassword(encryptedPassword);
387 // Call EJB for updating user data
388 User updatedUser = this.userBean.updateUserData(user);
391 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
393 // Return to user list (for now)
394 return "admin_list_user"; //NOI18N
398 public String getUserLockReason () {
399 return this.userLockReason;
403 public void setUserLockReason (final String userLockReason) {
404 this.userLockReason = userLockReason;
408 public Boolean getUserMustChangePassword () {
409 return this.userMustChangePassword;
413 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
414 this.userMustChangePassword = userMustChangePassword;
418 public String getUserName () {
419 return this.userName;
423 public void setUserName (final String userName) {
424 this.userName = userName;
428 public String getUserPassword () {
429 return this.userPassword;
433 public void setUserPassword (final String userPassword) {
434 this.userPassword = userPassword;
438 public String getUserPasswordRepeat () {
439 return this.userPasswordRepeat;
443 public void setUserPasswordRepeat (final String userPasswordRepeat) {
444 this.userPasswordRepeat = userPasswordRepeat;
448 public String lockUserAccount (final User user) {
449 // Is the user instance valid and CONFIRMED?
452 throw new NullPointerException("user is null"); //NOI18N
453 } else if (user.getUserId() == null) {
455 throw new NullPointerException("user.userId is null"); //NOI18N
456 } else if (user.getUserId() < 1) {
458 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
459 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
460 // User account is locked
461 throw new FacesException(new UserStatusLockedException(user));
462 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
463 // User account is locked
464 throw new FaceletException(new UserStatusUnconfirmedException(user));
465 } else if (this.getUserLockReason() == null) {
467 throw new NullPointerException("this.userLockReason is null"); //NOI18N
468 } else if (this.getUserLockReason().isEmpty()) {
470 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
475 String baseUrl = FacesUtils.generateBaseUrl();
477 // Call EJB to lock account
478 this.adminUserBean.lockUserAccount(user, this.getUserLockReason(), baseUrl);
479 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
481 throw new FaceletException(ex);
484 // Should go fine at this point, redirect to user profile
485 return "admin_show_user?faces-redirect=true&includeViewParams=true"; //NOI18N
491 private void clear () {
494 this.setUserName(null);
495 this.setUserPassword(null);
496 this.setUserPasswordRepeat(null);
497 this.setUserMustChangePassword(null);
501 * Checks if same password is entered and that they are not empty.
503 * @return Whether the same password was entered
505 private boolean isSamePasswordEntered () {
506 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));