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.jusercore.container.login.UserLoginContainer;
34 import org.mxchange.jusercore.events.registration.UserRegisteredEvent;
35 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
36 import org.mxchange.jusercore.events.user.add.AdminUserAddedEvent;
37 import org.mxchange.jusercore.events.user.linked.AdminLinkedUserEvent;
38 import org.mxchange.jusercore.events.user.linked.AdminUserLinkedEvent;
39 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
40 import org.mxchange.jusercore.events.user.update.AdminUserDataUpdatedEvent;
41 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
42 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
43 import org.mxchange.jusercore.exceptions.UserNotFoundException;
44 import org.mxchange.jusercore.exceptions.UserPasswordRepeatMismatchException;
45 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
46 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
47 import org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote;
48 import org.mxchange.jusercore.model.user.LoginUser;
49 import org.mxchange.jusercore.model.user.User;
50 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
51 import org.mxchange.jusercore.model.user.UserUtils;
52 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
53 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
54 import org.mxchange.pizzaapplication.beans.BasePizzaController;
55 import org.mxchange.pizzaapplication.beans.contact.PizzaAdminContactWebRequestController;
56 import org.mxchange.pizzaapplication.beans.contact.PizzaContactWebSessionController;
57 import org.mxchange.pizzaapplication.beans.helper.PizzaWebRequestController;
60 * Administrative user bean (controller)
62 * @author Roland Haeder<roland@mxchange.org>
64 @Named ("adminUserController")
66 public class PizzaAdminUserWebRequestBean extends BasePizzaController implements PizzaAdminUserWebRequestController {
71 private static final long serialVersionUID = 542_145_347_916L;
74 * An event fired when the administrator has added a new user
78 private Event<AdminAddedUserEvent> addedUserEvent;
81 * Regular contact controller
84 private PizzaAdminContactWebRequestController adminContactController;
87 * Administrative user EJB
89 private final AdminUserSessionBeanRemote adminUserBean;
92 * Admin helper instance
95 private PizzaWebRequestController beanHelper;
98 * Regular contact controller
101 private PizzaContactWebSessionController contactController;
104 * An event fired when the administrator has updated a new user
108 private Event<AdminUpdatedUserDataEvent> updatedUserDataEvent;
113 private final UserSessionBeanRemote userBean;
116 * Regular user controller
119 private PizzaUserWebSessionController userController;
122 * An event fired when the administrator has linked a user with existing
127 private Event<AdminLinkedUserEvent> userLinkedEvent;
132 private String userLockReason;
135 * Flag whether user must change password after login
137 private Boolean userMustChangePassword;
142 private String userName;
145 * User password (unencrypted from web form)
147 private String userPassword;
150 * User password repeated (unencrypted from web form)
152 private String userPasswordRepeat;
155 * Default constructor
157 public PizzaAdminUserWebRequestBean () {
160 // Get initial context
161 Context context = new InitialContext();
164 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/pizzaservice-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
165 this.adminUserBean = (AdminUserSessionBeanRemote) context.lookup("java:global/pizzaservice-ejb/user!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote"); //NOI18N
166 } catch (final NamingException e) {
168 throw new FaceletException(e);
173 public String addUser () {
174 // Create new user instance
175 User user = new LoginUser();
177 // As the form cannot validate the data (required="true"), check it here
178 if (this.getUserName() == null) {
180 throw new NullPointerException("userName is null"); //NOI18N
181 } else if (this.getUserName().isEmpty()) {
183 throw new IllegalArgumentException("userName is null"); //NOI18N
184 } else if (this.beanHelper.getContact() == null) {
185 // No contact instance set, so test required fields: gender, first name and family name
186 if (this.contactController.getGender() == null) {
188 throw new NullPointerException("contactController.gender is null"); //NOI18N
189 } else if (this.contactController.getFirstName() == null) {
191 throw new NullPointerException("contactController.firstName is null"); //NOI18N //NOI18N
192 } else if (this.contactController.getFirstName().isEmpty()) {
194 throw new IllegalArgumentException("contactController.firstName is empty"); //NOI18N
195 } else if (this.adminContactController.getFamilyName() == null) {
197 throw new NullPointerException("contactController.familyName is null"); //NOI18N
198 } else if (this.contactController.getFamilyName().isEmpty()) {
200 throw new IllegalArgumentException("contactController.familyName is empty"); //NOI18N //NOI18N
201 } else if (this.contactController.getEmailAddress() == null) {
203 throw new NullPointerException("contactController.emailAddress is null"); //NOI18N
204 } else if (this.adminContactController.getEmailAddress().isEmpty()) {
206 throw new IllegalArgumentException("contactController.emailAddress is empty"); //NOI18N //NOI18N
207 } else if (this.contactController.getEmailAddressRepeat() == null) {
209 throw new NullPointerException("contactController.emailAddressRepeat is null");
210 } else if (this.contactController.getEmailAddressRepeat().isEmpty()) {
212 throw new IllegalArgumentException("contactController.emailAddressRepeat is empty"); //NOI18N //NOI18N
213 } else if (!Objects.equals(this.contactController.getEmailAddress(), this.contactController.getEmailAddressRepeat())) {
214 // Is not same email address
215 throw new IllegalArgumentException("Both entered email addresses don't match.");
219 // Set user name, CONFIRMED and INVISIBLE
220 user.setUserName(this.getUserName());
221 user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
222 user.setUserProfileMode(ProfileMode.INVISIBLE);
227 // Is a contact instance in helper set?
228 if (this.beanHelper.getContact() instanceof Contact) {
229 // Then use it for contact linking
230 contact = this.beanHelper.getContact();
232 // Create contact instance
233 contact = this.contactController.createContactInstance();
236 // Set contact in user
237 user.setUserContact(contact);
239 // Init variable for password
240 String password = null;
242 // Is the user name or email address used already?
243 // @TODO Add password length check
244 if (this.userController.isUserNameRegistered(user)) {
245 // User name is already used
246 throw new FaceletException(new UserNameAlreadyRegisteredException(user));
247 } else if ((this.beanHelper.getContact() == null) && (this.contactController.isEmailAddressRegistered(user.getUserContact()))) {
248 // Email address is already used
249 throw new FaceletException(new EmailAddressAlreadyRegisteredException(user));
250 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
251 // Empty password entered, then generate one
252 password = UserUtils.createRandomPassword(PizzaUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
253 } else if (!this.isSamePasswordEntered()) {
254 // Both passwords don't match
255 throw new FaceletException(new UserPasswordRepeatMismatchException(user));
257 // Both match, so get it from this bean
258 password = this.getUserPassword();
261 // The password should not be null and at least 5 characters long
262 assert (password != null) : "password is null"; //NOI18N
263 assert (password.length() >= PizzaUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
265 // Encrypt password and set it
266 user.setUserEncryptedPassword(UserUtils.encryptPassword(password));
269 // Now, that all is set, call EJB
270 if (this.beanHelper.getContact() instanceof Contact) {
271 // Link contact with this user
272 User updatedUser = this.adminUserBean.linkUser(user);
275 this.userLinkedEvent.fire(new AdminUserLinkedEvent(updatedUser));
277 // Remove contact instance
278 this.beanHelper.setContact(null);
281 User updatedUser = this.adminUserBean.addUser(user);
284 this.addedUserEvent.fire(new AdminUserAddedEvent(updatedUser));
286 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
288 throw new FaceletException(ex);
294 // Return to user list (for now)
295 return "admin_list_user"; //NOI18N
299 public void afterRegistrationEvent (@Observes final UserRegisteredEvent event) {
301 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("AdminUserWebBean:afterRegistration: event={0} - CALLED!", event)); //NOI18N
303 // event should not be null
306 throw new NullPointerException("event is null"); //NOI18N
307 } else if (event.getRegisteredUser() == null) {
309 throw new NullPointerException("event.user is null"); //NOI18N
310 } else if (event.getRegisteredUser().getUserId() == null) {
312 throw new NullPointerException("event.user.userId is null"); //NOI18N
313 } else if (event.getRegisteredUser().getUserId() < 1) {
315 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
319 User registeredUser = event.getRegisteredUser();
322 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterRegistration: registeredUser={0}", registeredUser)); //NOI18N
328 //* NOISY-DEBUG: */ System.out.println("AdminUserWebBean:afterRegistration: EXIT!"); //NOI18N
332 public String editUserData () {
334 User user = this.beanHelper.getUser();
336 // Null password means not setting it
337 String encryptedPassword = null;
339 // Check if user instance is in helper and valid
342 throw new NullPointerException("beanHelper.user is null"); //NOI18N
343 } else if (user.getUserId() == null) {
345 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N //NOI18N
346 } else if (user.getUserId() < 1) {
348 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N //NOI18N
349 } else if (this.getUserName() == null) {
350 // Not all required fields are set
351 throw new NullPointerException("this.userName is null"); //NOI18N
352 } else if (this.getUserName().isEmpty()) {
353 // Not all required fields are set
354 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
355 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
356 // Not same password entered
357 this.setUserPassword(null);
358 this.setUserPasswordRepeat(null);
361 throw new FaceletException("Not same password entered"); //NOI18N
362 } else if (this.userBean.ifUserNameExists(this.getUserName())) {
363 // User name already exists
364 throw new FaceletException(new UserNameAlreadyRegisteredException(this.getUserName()));
365 } else if (this.isSamePasswordEntered()) {
366 // Same password entered, create container
367 if (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword()))) {
368 // Same password entered
369 throw new FaceletException("Same password as stored entered."); //NOI18N
373 encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
376 // Set user name and flag
377 user.setUserName(this.getUserName());
378 user.setUserMustChangePassword(this.getUserMustChangePassword());
380 // Is a password set?
381 if (encryptedPassword != null) {
383 user.setUserEncryptedPassword(encryptedPassword);
386 // Call EJB for updating user data
387 User updatedUser = this.userBean.updateUserData(user);
390 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
392 // Return to user list (for now)
393 return "admin_list_user"; //NOI18N
397 public String getUserLockReason () {
398 return this.userLockReason;
402 public void setUserLockReason (final String userLockReason) {
403 this.userLockReason = userLockReason;
407 public Boolean getUserMustChangePassword () {
408 return this.userMustChangePassword;
412 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
413 this.userMustChangePassword = userMustChangePassword;
417 public String getUserName () {
418 return this.userName;
422 public void setUserName (final String userName) {
423 this.userName = userName;
427 public String getUserPassword () {
428 return this.userPassword;
432 public void setUserPassword (final String userPassword) {
433 this.userPassword = userPassword;
437 public String getUserPasswordRepeat () {
438 return this.userPasswordRepeat;
442 public void setUserPasswordRepeat (final String userPasswordRepeat) {
443 this.userPasswordRepeat = userPasswordRepeat;
447 public String lockUserAccount (final User user) {
448 // Is the user instance valid and CONFIRMED?
451 throw new NullPointerException("user is null"); //NOI18N
452 } else if (user.getUserId() == null) {
454 throw new NullPointerException("user.userId is null"); //NOI18N
455 } else if (user.getUserId() < 1) {
457 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
458 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
459 // User account is locked
460 throw new FacesException(new UserStatusLockedException(user));
461 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
462 // User account is locked
463 throw new FaceletException(new UserStatusUnconfirmedException(user));
464 } else if (this.getUserLockReason() == null) {
466 throw new NullPointerException("this.userLockReason is null"); //NOI18N
467 } else if (this.getUserLockReason().isEmpty()) {
469 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
473 // Call EJB to lock account
474 this.adminUserBean.lockUserAccount(user, this.getUserLockReason());
475 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
477 throw new FaceletException(ex);
480 // Should go fine at this point, redirect to user profile
481 return "admin_show_user?faces-redirect=true&includeViewParams=true"; //NOI18N
487 private void clear () {
490 this.setUserName(null);
491 this.setUserPassword(null);
492 this.setUserPasswordRepeat(null);
493 this.setUserMustChangePassword(null);
497 * Checks if same password is entered and that they are not empty.
499 * @return Whether the same password was entered
501 private boolean isSamePasswordEntered () {
502 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));