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.UserStatusConfirmedException;
47 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
48 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
49 import org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote;
50 import org.mxchange.jusercore.model.user.LoginUser;
51 import org.mxchange.jusercore.model.user.User;
52 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
53 import org.mxchange.jusercore.model.user.UserUtils;
54 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
55 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
56 import org.mxchange.pizzaapplication.beans.BasePizzaController;
57 import org.mxchange.pizzaapplication.beans.contact.PizzaAdminContactWebRequestController;
58 import org.mxchange.pizzaapplication.beans.contact.PizzaContactWebSessionController;
59 import org.mxchange.pizzaapplication.beans.helper.PizzaWebRequestController;
62 * Administrative user bean (controller)
64 * @author Roland Haeder<roland@mxchange.org>
66 @Named ("adminUserController")
68 public class PizzaAdminUserWebRequestBean extends BasePizzaController implements PizzaAdminUserWebRequestController {
73 private static final long serialVersionUID = 542_145_347_916L;
76 * An event fired when the administrator has added a new user
80 private Event<AdminAddedUserEvent> addedUserEvent;
83 * Regular contact controller
86 private PizzaAdminContactWebRequestController adminContactController;
89 * Administrative user EJB
91 private final AdminUserSessionBeanRemote adminUserBean;
94 * Admin helper instance
97 private PizzaWebRequestController beanHelper;
100 * Regular contact controller
103 private PizzaContactWebSessionController contactController;
106 * An event fired when the administrator has updated a new user
110 private Event<AdminUpdatedUserDataEvent> updatedUserDataEvent;
115 private final UserSessionBeanRemote userBean;
118 * Regular user controller
121 private PizzaUserWebSessionController userController;
124 * An event fired when the administrator has linked a user with existing
129 private Event<AdminLinkedUserEvent> userLinkedEvent;
134 private String userLockReason;
137 * Flag whether user must change password after login
139 private Boolean userMustChangePassword;
144 private String userName;
147 * User password (unencrypted from web form)
149 private String userPassword;
152 * User password repeated (unencrypted from web form)
154 private String userPasswordRepeat;
157 * Default constructor
159 public PizzaAdminUserWebRequestBean () {
162 // Get initial context
163 Context context = new InitialContext();
166 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/pizzaservice-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
167 this.adminUserBean = (AdminUserSessionBeanRemote) context.lookup("java:global/pizzaservice-ejb/user!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote"); //NOI18N
168 } catch (final NamingException e) {
170 throw new FaceletException(e);
175 public String addUser () {
176 // Create new user instance
177 User user = new LoginUser();
179 // As the form cannot validate the data (required="true"), check it here
180 if (this.getUserName() == null) {
182 throw new NullPointerException("userName is null"); //NOI18N
183 } else if (this.getUserName().isEmpty()) {
185 throw new IllegalArgumentException("userName is null"); //NOI18N
186 } else if (this.beanHelper.getContact() == null) {
187 // No contact instance set, so test required fields: gender, first name and family name
188 if (this.contactController.getGender() == null) {
190 throw new NullPointerException("contactController.gender is null"); //NOI18N
191 } else if (this.contactController.getFirstName() == null) {
193 throw new NullPointerException("contactController.firstName is null"); //NOI18N //NOI18N
194 } else if (this.contactController.getFirstName().isEmpty()) {
196 throw new IllegalArgumentException("contactController.firstName is empty"); //NOI18N
197 } else if (this.adminContactController.getFamilyName() == null) {
199 throw new NullPointerException("contactController.familyName is null"); //NOI18N
200 } else if (this.contactController.getFamilyName().isEmpty()) {
202 throw new IllegalArgumentException("contactController.familyName is empty"); //NOI18N //NOI18N
203 } else if (this.contactController.getEmailAddress() == null) {
205 throw new NullPointerException("contactController.emailAddress is null"); //NOI18N
206 } else if (this.adminContactController.getEmailAddress().isEmpty()) {
208 throw new IllegalArgumentException("contactController.emailAddress is empty"); //NOI18N //NOI18N
209 } else if (this.contactController.getEmailAddressRepeat() == null) {
211 throw new NullPointerException("contactController.emailAddressRepeat is null");
212 } else if (this.contactController.getEmailAddressRepeat().isEmpty()) {
214 throw new IllegalArgumentException("contactController.emailAddressRepeat is empty"); //NOI18N //NOI18N
215 } else if (!Objects.equals(this.contactController.getEmailAddress(), this.contactController.getEmailAddressRepeat())) {
216 // Is not same email address
217 throw new IllegalArgumentException("Both entered email addresses don't match.");
221 // Set user name, CONFIRMED and INVISIBLE
222 user.setUserName(this.getUserName());
223 user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
224 user.setUserProfileMode(ProfileMode.INVISIBLE);
229 // Is a contact instance in helper set?
230 if (this.beanHelper.getContact() instanceof Contact) {
231 // Then use it for contact linking
232 contact = this.beanHelper.getContact();
234 // Create contact instance
235 contact = this.contactController.createContactInstance();
238 // Set contact in user
239 user.setUserContact(contact);
241 // Init variable for password
242 String password = null;
244 // Is the user name or email address used already?
245 // @TODO Add password length check
246 if (this.userController.isUserNameRegistered(user)) {
247 // User name is already used
248 throw new FaceletException(new UserNameAlreadyRegisteredException(user));
249 } else if ((this.beanHelper.getContact() == null) && (this.contactController.isEmailAddressRegistered(user.getUserContact()))) {
250 // Email address is already used
251 throw new FaceletException(new EmailAddressAlreadyRegisteredException(user));
252 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
253 // Empty password entered, then generate one
254 password = UserUtils.createRandomPassword(PizzaUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
255 } else if (!this.isSamePasswordEntered()) {
256 // Both passwords don't match
257 throw new FaceletException(new UserPasswordRepeatMismatchException(user));
259 // Both match, so get it from this bean
260 password = this.getUserPassword();
263 // The password should not be null and at least 5 characters long
264 assert (password != null) : "password is null"; //NOI18N
265 assert (password.length() >= PizzaUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
267 // Encrypt password and set it
268 user.setUserEncryptedPassword(UserUtils.encryptPassword(password));
271 // Now, that all is set, call EJB
272 if (this.beanHelper.getContact() instanceof Contact) {
273 // Link contact with this user
274 User updatedUser = this.adminUserBean.linkUser(user);
277 this.userLinkedEvent.fire(new AdminUserLinkedEvent(updatedUser));
279 // Remove contact instance
280 this.beanHelper.setContact(null);
283 User updatedUser = this.adminUserBean.addUser(user);
286 this.addedUserEvent.fire(new AdminUserAddedEvent(updatedUser));
288 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
290 throw new FaceletException(ex);
296 // Return to user list (for now)
297 return "admin_list_user"; //NOI18N
301 public void afterRegistrationEvent (@Observes final UserRegisteredEvent event) {
303 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("AdminUserWebBean:afterRegistration: event={0} - CALLED!", event)); //NOI18N
305 // event should not be null
308 throw new NullPointerException("event is null"); //NOI18N
309 } else if (event.getRegisteredUser() == null) {
311 throw new NullPointerException("event.user is null"); //NOI18N
312 } else if (event.getRegisteredUser().getUserId() == null) {
314 throw new NullPointerException("event.user.userId is null"); //NOI18N
315 } else if (event.getRegisteredUser().getUserId() < 1) {
317 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
321 User registeredUser = event.getRegisteredUser();
324 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterRegistration: registeredUser={0}", registeredUser)); //NOI18N
330 //* NOISY-DEBUG: */ System.out.println("AdminUserWebBean:afterRegistration: EXIT!"); //NOI18N
334 public String editUserData () {
336 User user = this.beanHelper.getUser();
338 // Null password means not setting it
339 String encryptedPassword = null;
341 // Check if user instance is in helper and valid
344 throw new NullPointerException("beanHelper.user is null"); //NOI18N
345 } else if (user.getUserId() == null) {
347 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N //NOI18N
348 } else if (user.getUserId() < 1) {
350 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N //NOI18N
351 } else if (this.getUserName() == null) {
352 // Not all required fields are set
353 throw new NullPointerException("this.userName is null"); //NOI18N
354 } else if (this.getUserName().isEmpty()) {
355 // Not all required fields are set
356 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
357 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
358 // Not same password entered
359 this.setUserPassword(null);
360 this.setUserPasswordRepeat(null);
363 throw new FaceletException("Not same password entered"); //NOI18N
364 } else if (this.userBean.ifUserNameExists(this.getUserName())) {
365 // User name already exists
366 throw new FaceletException(new UserNameAlreadyRegisteredException(this.getUserName()));
367 } else if (this.isSamePasswordEntered()) {
368 // Same password entered, create container
369 if (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword()))) {
370 // Same password entered
371 throw new FaceletException("Same password as stored entered."); //NOI18N
375 encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
378 // Set user name and flag
379 user.setUserName(this.getUserName());
380 user.setUserMustChangePassword(this.getUserMustChangePassword());
382 // Is a password set?
383 if (encryptedPassword != null) {
385 user.setUserEncryptedPassword(encryptedPassword);
388 // Call EJB for updating user data
389 User updatedUser = this.userBean.updateUserData(user);
392 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
394 // Return to user list (for now)
395 return "admin_list_user"; //NOI18N
399 public String getUserLockReason () {
400 return this.userLockReason;
404 public void setUserLockReason (final String userLockReason) {
405 this.userLockReason = userLockReason;
409 public Boolean getUserMustChangePassword () {
410 return this.userMustChangePassword;
414 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
415 this.userMustChangePassword = userMustChangePassword;
419 public String getUserName () {
420 return this.userName;
424 public void setUserName (final String userName) {
425 this.userName = userName;
429 public String getUserPassword () {
430 return this.userPassword;
434 public void setUserPassword (final String userPassword) {
435 this.userPassword = userPassword;
439 public String getUserPasswordRepeat () {
440 return this.userPasswordRepeat;
444 public void setUserPasswordRepeat (final String userPasswordRepeat) {
445 this.userPasswordRepeat = userPasswordRepeat;
449 public String lockUserAccount (final User user) {
450 // Is the user instance valid and CONFIRMED?
453 throw new NullPointerException("user is null"); //NOI18N
454 } else if (user.getUserId() == null) {
456 throw new NullPointerException("user.userId is null"); //NOI18N
457 } else if (user.getUserId() < 1) {
459 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
460 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
461 // User account is locked
462 throw new FacesException(new UserStatusLockedException(user));
463 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
464 // User account is locked
465 throw new FaceletException(new UserStatusUnconfirmedException(user));
466 } else if (this.getUserLockReason() == null) {
468 throw new NullPointerException("this.userLockReason is null"); //NOI18N
469 } else if (this.getUserLockReason().isEmpty()) {
471 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
476 String baseUrl = FacesUtils.generateBaseUrl();
478 // Call EJB to lock account
479 this.adminUserBean.lockUserAccount(user, this.getUserLockReason(), baseUrl);
480 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
482 throw new FaceletException(ex);
485 // Should go fine at this point, redirect to user profile
486 return "admin_show_user?faces-redirect=true&includeViewParams=true"; //NOI18N
490 public String unlockUserAccount (final User user) {
491 // Is the user instance valid and CONFIRMED?
494 throw new NullPointerException("user is null"); //NOI18N
495 } else if (user.getUserId() == null) {
497 throw new NullPointerException("user.userId is null"); //NOI18N
498 } else if (user.getUserId() < 1) {
500 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
501 } else if (user.getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
502 // User account is locked
503 throw new FacesException(new UserStatusConfirmedException(user));
504 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
505 // User account is locked
506 throw new FaceletException(new UserStatusUnconfirmedException(user));
511 String baseUrl = FacesUtils.generateBaseUrl();
513 // Call EJB to unlock account
514 this.adminUserBean.unlockUserAccount(user, baseUrl);
515 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
517 throw new FaceletException(ex);
520 // Should go fine at this point, redirect to user profile
521 return "admin_show_user?faces-redirect=true&includeViewParams=true"; //NOI18N
527 private void clear () {
530 this.setUserName(null);
531 this.setUserPassword(null);
532 this.setUserPasswordRepeat(null);
533 this.setUserMustChangePassword(null);
537 * Checks if same password is entered and that they are not empty.
539 * @return Whether the same password was entered
541 private boolean isSamePasswordEntered () {
542 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));