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.jjobs.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.jjobs.beans.BaseJobsController;
35 import org.mxchange.jjobs.beans.contact.JobsAdminContactWebRequestController;
36 import org.mxchange.jjobs.beans.contact.JobsContactWebSessionController;
37 import org.mxchange.jjobs.beans.helper.JobsWebRequestHelperController;
38 import org.mxchange.jjobs.beans.localization.JobsLocalizationSessionController;
39 import org.mxchange.jusercore.container.login.UserLoginContainer;
40 import org.mxchange.jusercore.events.registration.ObservableUserRegisteredEvent;
41 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
42 import org.mxchange.jusercore.events.user.add.ObservableAdminAddedUserEvent;
43 import org.mxchange.jusercore.events.user.delete.AdminDeletedUserEvent;
44 import org.mxchange.jusercore.events.user.delete.ObservableAdminDeletedUserEvent;
45 import org.mxchange.jusercore.events.user.linked.AdminLinkedUserEvent;
46 import org.mxchange.jusercore.events.user.linked.ObservableAdminLinkedUserEvent;
47 import org.mxchange.jusercore.events.user.locked.AdminLockedUserEvent;
48 import org.mxchange.jusercore.events.user.locked.ObservableAdminLockedUserEvent;
49 import org.mxchange.jusercore.events.user.unlocked.AdminUnlockedUserEvent;
50 import org.mxchange.jusercore.events.user.unlocked.ObservableAdminUnlockedUserEvent;
51 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
52 import org.mxchange.jusercore.events.user.update.ObservableAdminUpdatedUserDataEvent;
53 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
54 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
55 import org.mxchange.jusercore.exceptions.UserNotFoundException;
56 import org.mxchange.jusercore.exceptions.UserPasswordRepeatMismatchException;
57 import org.mxchange.jusercore.exceptions.UserStatusConfirmedException;
58 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
59 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
60 import org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote;
61 import org.mxchange.jusercore.model.user.LoginUser;
62 import org.mxchange.jusercore.model.user.User;
63 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
64 import org.mxchange.jusercore.model.user.UserUtils;
65 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
66 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
69 * A user controller (bean)
71 * @author Roland Häder<roland@mxchange.org>
73 @Named ("adminUserController")
75 public class JobsAdminUserWebRequestBean extends BaseJobsController implements JobsAdminUserWebRequestController {
80 private static final long serialVersionUID = 542_145_347_916L;
83 * An event fired when the administrator has added a new user
87 private Event<ObservableAdminAddedUserEvent> addedUserEvent;
90 * Regular contact controller
93 private JobsAdminContactWebRequestController adminContactController;
96 * Administrative user EJB
98 private final AdminUserSessionBeanRemote adminUserBean;
104 private JobsWebRequestHelperController beanHelper;
107 * Regular contact controller
110 private JobsContactWebSessionController contactController;
113 * Event being fired when admin has deleted user
117 private Event<ObservableAdminDeletedUserEvent> deleteUserEvent;
120 * Localization controller
123 private JobsLocalizationSessionController localizationController;
126 * An event fired when the administrator has updated a new user
130 private Event<ObservableAdminUpdatedUserDataEvent> updatedUserDataEvent;
135 private final UserSessionBeanRemote userBean;
138 * Regular user controller
141 private JobsUserWebSessionController userController;
146 private String userDeleteReason;
149 * An event fired when the administrator has linked a user with existing
154 private Event<ObservableAdminLinkedUserEvent> userLinkedEvent;
159 private String userLockReason;
162 * Event being fired when an administrator has locked a user
166 private Event<ObservableAdminLockedUserEvent> userLockedEvent;
169 * Flag whether user must change password after login
171 private Boolean userMustChangePassword;
176 private String userName;
179 * User password (unencrypted from web form)
181 private String userPassword;
184 * User password repeated (unencrypted from web form)
186 private String userPasswordRepeat;
189 * Event being fired when admin unlocks an account
193 private Event<ObservableAdminUnlockedUserEvent> userUnlockedEvent;
196 * Default constructor
198 public JobsAdminUserWebRequestBean () {
201 // Get initial context
202 Context context = new InitialContext();
205 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
206 this.adminUserBean = (AdminUserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/adminUser!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote"); //NOI18N
207 } catch (final NamingException e) {
209 throw new FaceletException(e);
214 public String addUser () {
215 // As the form cannot validate the data (required="true"), check it here
216 if (this.getUserName() == null) {
218 throw new NullPointerException("userName is null"); //NOI18N
219 } else if (this.getUserName().isEmpty()) {
221 throw new IllegalArgumentException("userName is null"); //NOI18N
222 } else if (this.beanHelper.getContact() == null) {
223 // No contact instance set, so test required fields: gender, first name and family name
224 if (this.contactController.getGender() == null) {
226 throw new NullPointerException("contactController.gender is null"); //NOI18N
227 } else if (this.contactController.getFirstName() == null) {
229 throw new NullPointerException("contactController.firstName is null"); //NOI18N
230 } else if (this.adminContactController.getFirstName().isEmpty()) {
232 throw new IllegalArgumentException("contactController.firstName is empty"); //NOI18N
233 } else if (this.adminContactController.getFamilyName() == null) {
235 throw new NullPointerException("contactController.familyName is null"); //NOI18N
236 } else if (this.contactController.getFamilyName().isEmpty()) {
238 throw new IllegalArgumentException("contactController.familyName is empty"); //NOI18N
239 } else if (this.adminContactController.getEmailAddress() == null) {
241 throw new NullPointerException("contactController.emailAddress is null"); //NOI18N
242 } else if (this.adminContactController.getEmailAddress().isEmpty()) {
244 throw new IllegalArgumentException("contactController.emailAddress is empty"); //NOI18N
248 // Create new user instance
249 User user = new LoginUser();
251 // Set user name, CONFIRMED and INVISIBLE
252 user.setUserName(this.getUserName());
253 user.setUserMustChangePassword(this.getUserMustChangePassword());
254 user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
255 user.setUserProfileMode(ProfileMode.INVISIBLE);
260 // Is a contact instance in helper set?
261 if (this.beanHelper.getContact() instanceof Contact) {
262 // Then use it for contact linking
263 contact = this.beanHelper.getContact();
265 // Create contact instance
266 contact = this.contactController.createContactInstance();
269 // Set contact in user
270 user.setUserContact(contact);
272 // Init variable for password
273 String password = null;
275 // Is the user name or email address used already?
276 // @TODO Add password length check
277 if (this.userController.isUserNameRegistered(user)) {
278 // User name is already used
279 throw new FaceletException(new UserNameAlreadyRegisteredException(user));
280 } else if ((this.beanHelper.getContact() == null) && (this.contactController.isEmailAddressRegistered(user.getUserContact()))) {
281 // Email address is already used
282 this.showFacesMessage("admin_add_user:emailAddress", "ERROR_EMAIL_ADDRESS_ALREADY_USED"); //NOI18N
284 // Always clear password
285 this.setUserPassword(null);
286 this.setUserPasswordRepeat(null);
290 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
291 // Empty password entered, then generate one
292 password = UserUtils.createRandomPassword(JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
293 } else if (!this.isSamePasswordEntered()) {
294 // Both passwords don't match
295 throw new FaceletException(new UserPasswordRepeatMismatchException(user));
297 // Both match, so get it from this bean
298 password = this.getUserPassword();
301 // The password should not be null and at least 5 characters long
302 assert (password != null) : "password is null"; //NOI18N
303 assert (password.length() >= JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
305 // Encrypt password and set it
306 user.setUserEncryptedPassword(UserUtils.encryptPassword(password));
309 // Now, that all is set, call EJB
310 if (this.beanHelper.getContact() instanceof Contact) {
311 // Link contact with this user
312 User updatedUser = this.adminUserBean.linkUser(user);
315 this.userLinkedEvent.fire(new AdminLinkedUserEvent(updatedUser));
317 // Remove contact instance
318 this.beanHelper.setContact(null);
321 User updatedUser = this.adminUserBean.addUser(user);
324 this.addedUserEvent.fire(new AdminAddedUserEvent(updatedUser));
326 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
328 throw new FaceletException(ex);
332 this.beanHelper.setContact(null);
337 // Return to user list (for now)
338 return "admin_list_user"; //NOI18N
342 public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
343 // event should not be null
346 throw new NullPointerException("event is null"); //NOI18N
347 } else if (event.getRegisteredUser() == null) {
349 throw new NullPointerException("event.user is null"); //NOI18N
350 } else if (event.getRegisteredUser().getUserId() == null) {
352 throw new NullPointerException("event.user.userId is null"); //NOI18N
353 } else if (event.getRegisteredUser().getUserId() < 1) {
355 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
359 User registeredUser = event.getRegisteredUser();
361 // @TODO Nothing to do with the user here?
368 public String deleteUserData (final User user) {
369 // Is the user instance valid and CONFIRMED?
372 throw new NullPointerException("user is null"); //NOI18N
373 } else if (user.getUserId() == null) {
375 throw new NullPointerException("user.userId is null"); //NOI18N
376 } else if (user.getUserId() < 1) {
378 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
382 // All fine, delete it
383 this.adminUserBean.deleteUser(user, this.getUserDeleteReason());
384 } catch (final UserNotFoundException ex) {
385 // Should not happen, so throw again
386 throw new FaceletException(ex);
390 this.deleteUserEvent.fire(new AdminDeletedUserEvent(user, this.getUserDeleteReason()));
393 return "admin_list_user"; //NOI18N
397 public String editUserData () {
399 User user = this.beanHelper.getUser();
401 // Null password means not setting it
402 String encryptedPassword = null;
404 // Check if user instance is in helper and valid
407 throw new NullPointerException("beanHelper.user is null"); //NOI18N
408 } else if (user.getUserId() == null) {
410 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
411 } else if (user.getUserId() < 1) {
413 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N
414 } else if (this.getUserName() == null) {
415 // Not all required fields are set
416 throw new NullPointerException("this.userName is null"); //NOI18N
417 } else if (this.getUserName().isEmpty()) {
418 // Not all required fields are set
419 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
420 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
421 // Clear password fields
422 this.setUserPassword(null);
423 this.setUserPasswordRepeat(null);
425 // Not same password entered
426 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT"); //NOI18N
428 } else if ((!Objects.equals(user.getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
432 // User name already exists
433 this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS"); //NOI18N
435 } else if (this.isSamePasswordEntered()) {
436 // Same password entered, create container
437 if ((Objects.equals(user.getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword())))) {
438 // Clear password fields
439 this.setUserPassword(null);
440 this.setUserPasswordRepeat(null);
442 // Same password entered
443 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD"); //NOI18N
448 encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
451 // Set user name and flag
452 user.setUserName(this.getUserName());
453 user.setUserMustChangePassword(this.getUserMustChangePassword());
455 // Is a password set?
456 if (encryptedPassword != null) {
458 user.setUserEncryptedPassword(encryptedPassword);
461 // Call EJB for updating user data
462 User updatedUser = this.userBean.updateUserData(user);
465 this.updatedUserDataEvent.fire(new AdminUpdatedUserDataEvent(updatedUser));
467 // Return to user list (for now)
468 return "admin_list_user"; //NOI18N
472 public String getUserDeleteReason () {
473 return this.userDeleteReason;
477 public void setUserDeleteReason (final String userDeleteReason) {
478 this.userDeleteReason = userDeleteReason;
482 public String getUserLockReason () {
483 return this.userLockReason;
487 public void setUserLockReason (final String userLockReason) {
488 this.userLockReason = userLockReason;
492 public Boolean getUserMustChangePassword () {
493 return this.userMustChangePassword;
497 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
498 this.userMustChangePassword = userMustChangePassword;
502 public String getUserName () {
503 return this.userName;
507 public void setUserName (final String userName) {
508 this.userName = userName;
512 public String getUserPassword () {
513 return this.userPassword;
517 public void setUserPassword (final String userPassword) {
518 this.userPassword = userPassword;
522 public String getUserPasswordRepeat () {
523 return this.userPasswordRepeat;
527 public void setUserPasswordRepeat (final String userPasswordRepeat) {
528 this.userPasswordRepeat = userPasswordRepeat;
532 public String lockUserAccount (final User user) {
533 // Is the user instance valid and CONFIRMED?
536 throw new NullPointerException("user is null"); //NOI18N
537 } else if (user.getUserId() == null) {
539 throw new NullPointerException("user.userId is null"); //NOI18N
540 } else if (user.getUserId() < 1) {
542 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
543 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
544 // User account is locked
545 throw new FacesException(new UserStatusLockedException(user));
546 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
547 // User account is locked
548 throw new FaceletException(new UserStatusUnconfirmedException(user));
549 } else if (this.getUserLockReason() == null) {
551 throw new NullPointerException("this.userLockReason is null"); //NOI18N
552 } else if (this.getUserLockReason().isEmpty()) {
554 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
557 // Init updated user instance
562 String baseUrl = FacesUtils.generateBaseUrl();
564 // Call EJB to lock account
565 updatedUser = this.adminUserBean.lockUserAccount(user, this.getUserLockReason(), baseUrl);
566 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
568 throw new FaceletException(ex);
572 this.userLockedEvent.fire(new AdminLockedUserEvent(updatedUser));
577 // Should go fine at this point, redirect to user profile
578 return "admin_show_user"; //NOI18N
582 public String unlockUserAccount (final User user) {
583 // Is the user instance valid and CONFIRMED?
586 throw new NullPointerException("user is null"); //NOI18N
587 } else if (user.getUserId() == null) {
589 throw new NullPointerException("user.userId is null"); //NOI18N
590 } else if (user.getUserId() < 1) {
592 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
593 } else if (user.getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
594 // User account is locked
595 throw new FacesException(new UserStatusConfirmedException(user));
596 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
597 // User account is locked
598 throw new FaceletException(new UserStatusUnconfirmedException(user));
601 // Init updated user instance
606 String baseUrl = FacesUtils.generateBaseUrl();
608 // Call EJB to unlock account
609 updatedUser = this.adminUserBean.unlockUserAccount(user, baseUrl);
610 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
612 throw new FaceletException(ex);
616 this.userUnlockedEvent.fire(new AdminUnlockedUserEvent(updatedUser));
621 // Should go fine at this point, redirect to user profile
622 return "admin_show_user"; //NOI18N
628 private void clear () {
631 this.setUserName(null);
632 this.setUserPassword(null);
633 this.setUserPasswordRepeat(null);
634 this.setUserMustChangePassword(null);
638 * Checks if same password is entered and that they are not empty.
640 * @return Whether the same password was entered
642 private boolean isSamePasswordEntered () {
643 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));