2 * Copyright (C) 2016, 2017 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.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.jjobs.beans.BaseJobsController;
36 import org.mxchange.jjobs.beans.contact.JobsAdminContactWebRequestController;
37 import org.mxchange.jjobs.beans.contact.JobsContactWebSessionController;
38 import org.mxchange.jjobs.beans.helper.JobsWebRequestHelperController;
39 import org.mxchange.jjobs.beans.localization.JobsLocalizationSessionController;
40 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
41 import org.mxchange.jusercore.events.user.add.ObservableAdminAddedUserEvent;
42 import org.mxchange.jusercore.events.user.delete.AdminDeletedUserEvent;
43 import org.mxchange.jusercore.events.user.delete.ObservableAdminDeletedUserEvent;
44 import org.mxchange.jusercore.events.user.linked.AdminLinkedUserEvent;
45 import org.mxchange.jusercore.events.user.linked.ObservableAdminLinkedUserEvent;
46 import org.mxchange.jusercore.events.user.locked.AdminLockedUserEvent;
47 import org.mxchange.jusercore.events.user.locked.ObservableAdminLockedUserEvent;
48 import org.mxchange.jusercore.events.user.unlocked.AdminUnlockedUserEvent;
49 import org.mxchange.jusercore.events.user.unlocked.ObservableAdminUnlockedUserEvent;
50 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
51 import org.mxchange.jusercore.events.user.update.ObservableAdminUpdatedUserDataEvent;
52 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
53 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
54 import org.mxchange.jusercore.exceptions.UserNotFoundException;
55 import org.mxchange.jusercore.exceptions.UserStatusConfirmedException;
56 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
57 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
58 import org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote;
59 import org.mxchange.jusercore.model.user.LoginUser;
60 import org.mxchange.jusercore.model.user.User;
61 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
62 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
63 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
64 import org.mxchange.juserlogincore.container.login.UserLoginContainer;
65 import org.mxchange.juserlogincore.events.registration.ObservableUserRegisteredEvent;
66 import org.mxchange.juserlogincore.exceptions.UserPasswordRepeatMismatchException;
67 import org.mxchange.juserlogincore.login.UserLoginUtils;
70 * A user controller (bean)
72 * @author Roland Häder<roland@mxchange.org>
74 @Named ("adminUserController")
76 public class JobsAdminUserWebRequestBean extends BaseJobsController implements JobsAdminUserWebRequestController {
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 JobsAdminContactWebRequestController adminContactController;
97 * Administrative user EJB
99 private AdminUserSessionBeanRemote adminUserBean;
105 private JobsWebRequestHelperController beanHelper;
108 * Regular contact controller
111 private JobsContactWebSessionController contactController;
114 * Event being fired when admin has deleted user
118 private Event<ObservableAdminDeletedUserEvent> deleteUserEvent;
121 * Localization controller
124 private JobsLocalizationSessionController 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 JobsUserWebSessionController 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 JobsAdminUserWebRequestBean () {
200 // Call super constructor
205 public String addUser () {
206 // Get contact from bean helper to "cache" it locally
207 Contact contact = this.beanHelper.getContact();
209 // As the form cannot validate the data (required="true"), check it here
210 if (this.getUserName() == null) {
212 throw new NullPointerException("userName is null"); //NOI18N
213 } else if (this.getUserName().isEmpty()) {
215 throw new IllegalArgumentException("userName is null"); //NOI18N
216 } else if (contact == null) {
217 // No contact instance set, so test required fields: gender, first name and family name
218 if (this.contactController.getPersonalTitle() == null) {
220 throw new NullPointerException("contactController.gender is null"); //NOI18N
221 } else if (this.contactController.getFirstName() == null) {
223 throw new NullPointerException("contactController.firstName is null"); //NOI18N
224 } else if (this.adminContactController.getFirstName().isEmpty()) {
226 throw new IllegalArgumentException("contactController.firstName is empty"); //NOI18N
227 } else if (this.adminContactController.getFamilyName() == null) {
229 throw new NullPointerException("contactController.familyName is null"); //NOI18N
230 } else if (this.adminContactController.getFamilyName().isEmpty()) {
232 throw new IllegalArgumentException("contactController.familyName is empty"); //NOI18N
233 } else if (this.adminContactController.getEmailAddress() == null) {
235 throw new NullPointerException("contactController.emailAddress is null"); //NOI18N
236 } else if (this.adminContactController.getEmailAddress().isEmpty()) {
238 throw new IllegalArgumentException("contactController.emailAddress is empty"); //NOI18N
242 // Create new user instance
243 User user = new LoginUser();
244 // Set user name, CONFIRMED and INVISIBLE
245 user.setUserName(this.getUserName());
246 user.setUserMustChangePassword(this.getUserMustChangePassword());
247 user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
248 user.setUserProfileMode(ProfileMode.INVISIBLE);
251 user.setUserLocale(this.localizationController.getLocale());
256 // Is a contact instance in helper set?
257 if (contact instanceof Contact) {
258 // Then use it for contact linking
259 userContact = contact;
261 // Create contact instance
262 userContact = this.contactController.createContactInstance();
265 // Set contact in user
266 user.setUserContact(userContact);
268 // Init variable for password
269 String password = null;
271 // Is the user name or email address used already?
272 // @TODO Add password length check
273 if (this.userController.isUserNameRegistered(user)) {
274 // User name is already used
275 throw new FaceletException(new UserNameAlreadyRegisteredException(user));
276 } else if ((contact == null) && (this.contactController.isEmailAddressRegistered(user.getUserContact()))) {
277 // Email address is already used
278 this.showFacesMessage("admin_add_user:emailAddress", "ERROR_EMAIL_ADDRESS_ALREADY_USED"); //NOI18N
280 // Always clear password
281 this.setUserPassword(null);
282 this.setUserPasswordRepeat(null);
286 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
287 // Empty password entered, then generate one
288 password = UserLoginUtils.createRandomPassword(JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
289 } else if (!this.isSamePasswordEntered()) {
290 // Both passwords don't match
291 throw new FaceletException(new UserPasswordRepeatMismatchException(user));
293 // Both match, so get it from this bean
294 password = this.getUserPassword();
297 // The password should not be null and at least 5 characters long
298 assert (password != null) : "password is null"; //NOI18N
299 assert (password.length() >= JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
301 // Encrypt password and set it
302 user.setUserEncryptedPassword(UserLoginUtils.encryptPassword(password));
305 // Now, that all is set, call EJB
306 if (contact instanceof Contact) {
307 // Link contact with this user
308 User updatedUser = this.adminUserBean.linkUser(user);
311 this.userLinkedEvent.fire(new AdminLinkedUserEvent(updatedUser));
314 User updatedUser = this.adminUserBean.addUser(user);
317 this.addedUserEvent.fire(new AdminAddedUserEvent(updatedUser));
319 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
321 throw new FaceletException(ex);
325 this.beanHelper.setContact(null);
330 // Return to user list (for now)
331 return "admin_list_user"; //NOI18N
335 * Event observer for new user registrations
337 * @param event User registration event
339 public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
340 // event should not be null
343 throw new NullPointerException("event is null"); //NOI18N
344 } else if (event.getRegisteredUser() == null) {
346 throw new NullPointerException("event.user is null"); //NOI18N
347 } else if (event.getRegisteredUser().getUserId() == null) {
349 throw new NullPointerException("event.user.userId is null"); //NOI18N
350 } else if (event.getRegisteredUser().getUserId() < 1) {
352 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
356 User registeredUser = event.getRegisteredUser();
358 // @TODO Nothing to do with the user here?
364 public String deleteUserData (final User user) {
365 // Is the user instance valid and CONFIRMED?
368 throw new NullPointerException("user is null"); //NOI18N
369 } else if (user.getUserId() == null) {
371 throw new NullPointerException("user.userId is null"); //NOI18N
372 } else if (user.getUserId() < 1) {
374 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
378 // All fine, delete it
379 this.adminUserBean.deleteUser(user, this.getUserDeleteReason());
380 } catch (final UserNotFoundException ex) {
381 // Should not happen, so throw again
382 throw new FaceletException(ex);
386 this.deleteUserEvent.fire(new AdminDeletedUserEvent(user, this.getUserDeleteReason()));
389 return "admin_list_user"; //NOI18N
393 public String editUserData () {
395 User user = this.beanHelper.getUser();
397 // Null password means not setting it
398 String encryptedPassword = null;
400 // Check if user instance is in helper and valid
403 throw new NullPointerException("beanHelper.user is null"); //NOI18N
404 } else if (user.getUserId() == null) {
406 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
407 } else if (user.getUserId() < 1) {
409 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N
410 } else if (this.getUserName() == null) {
411 // Not all required fields are set
412 throw new NullPointerException("this.userName is null"); //NOI18N
413 } else if (this.getUserName().isEmpty()) {
414 // Not all required fields are set
415 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
416 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
417 // Clear password fields
418 this.setUserPassword(null);
419 this.setUserPasswordRepeat(null);
421 // Not same password entered
422 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT"); //NOI18N
424 } else if ((!Objects.equals(user.getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
428 // User name already exists
429 this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS"); //NOI18N
431 } else if (this.isSamePasswordEntered()) {
432 // Same password entered, create container
433 if ((Objects.equals(user.getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserLoginUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword())))) {
434 // Clear password fields
435 this.setUserPassword(null);
436 this.setUserPasswordRepeat(null);
438 // Same password entered
439 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD"); //NOI18N
444 encryptedPassword = UserLoginUtils.encryptPassword(this.getUserPassword());
447 // Set user name and flag
448 user.setUserName(this.getUserName());
449 user.setUserMustChangePassword(this.getUserMustChangePassword());
451 // Is a password set?
452 if (encryptedPassword != null) {
454 user.setUserEncryptedPassword(encryptedPassword);
457 // Call EJB for updating user data
458 User updatedUser = this.userBean.updateUserData(user);
461 this.updatedUserDataEvent.fire(new AdminUpdatedUserDataEvent(updatedUser));
463 // Return to user list (for now)
464 return "admin_list_user"; //NOI18N
468 public String getUserDeleteReason () {
469 return this.userDeleteReason;
473 public void setUserDeleteReason (final String userDeleteReason) {
474 this.userDeleteReason = userDeleteReason;
478 public String getUserLockReason () {
479 return this.userLockReason;
483 public void setUserLockReason (final String userLockReason) {
484 this.userLockReason = userLockReason;
488 public Boolean getUserMustChangePassword () {
489 return this.userMustChangePassword;
493 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
494 this.userMustChangePassword = userMustChangePassword;
498 public String getUserName () {
499 return this.userName;
503 public void setUserName (final String userName) {
504 this.userName = userName;
508 public String getUserPassword () {
509 return this.userPassword;
513 public void setUserPassword (final String userPassword) {
514 this.userPassword = userPassword;
518 public String getUserPasswordRepeat () {
519 return this.userPasswordRepeat;
523 public void setUserPasswordRepeat (final String userPasswordRepeat) {
524 this.userPasswordRepeat = userPasswordRepeat;
528 * Post-construction method
531 public void init () {
534 // Get initial context
535 Context context = new InitialContext();
538 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
539 this.adminUserBean = (AdminUserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/adminUser!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote"); //NOI18N
540 } catch (final NamingException e) {
542 throw new FaceletException(e);
547 public String lockUserAccount (final User user) {
548 // Is the user instance valid and CONFIRMED?
551 throw new NullPointerException("user is null"); //NOI18N
552 } else if (user.getUserId() == null) {
554 throw new NullPointerException("user.userId is null"); //NOI18N
555 } else if (user.getUserId() < 1) {
557 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
558 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
559 // User account is locked
560 throw new FacesException(new UserStatusLockedException(user));
561 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
562 // User account is locked
563 throw new FaceletException(new UserStatusUnconfirmedException(user));
564 } else if (this.getUserLockReason() == null) {
566 throw new NullPointerException("this.userLockReason is null"); //NOI18N
567 } else if (this.getUserLockReason().isEmpty()) {
569 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
572 // Init updated user instance
577 String baseUrl = FacesUtils.generateBaseUrl();
579 // Call EJB to lock account
580 updatedUser = this.adminUserBean.lockUserAccount(user, this.getUserLockReason(), baseUrl);
581 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
583 throw new FaceletException(ex);
587 this.userLockedEvent.fire(new AdminLockedUserEvent(updatedUser));
592 // Should go fine at this point, redirect to user profile
593 return "admin_show_user"; //NOI18N
597 public String unlockUserAccount (final User user) {
598 // Is the user instance valid and CONFIRMED?
601 throw new NullPointerException("user is null"); //NOI18N
602 } else if (user.getUserId() == null) {
604 throw new NullPointerException("user.userId is null"); //NOI18N
605 } else if (user.getUserId() < 1) {
607 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
608 } else if (user.getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
609 // User account is locked
610 throw new FacesException(new UserStatusConfirmedException(user));
611 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
612 // User account is locked
613 throw new FaceletException(new UserStatusUnconfirmedException(user));
616 // Init updated user instance
621 String baseUrl = FacesUtils.generateBaseUrl();
623 // Call EJB to unlock account
624 updatedUser = this.adminUserBean.unlockUserAccount(user, baseUrl);
625 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
627 throw new FaceletException(ex);
631 this.userUnlockedEvent.fire(new AdminUnlockedUserEvent(updatedUser));
636 // Should go fine at this point, redirect to user profile
637 return "admin_show_user"; //NOI18N
643 private void clear () {
646 this.setUserName(null);
647 this.setUserPassword(null);
648 this.setUserPasswordRepeat(null);
649 this.setUserMustChangePassword(null);
653 * Checks if same password is entered and that they are not empty.
655 * @return Whether the same password was entered
657 private boolean isSamePasswordEntered () {
658 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));