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.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.JobsWebViewHelperController;
38 import org.mxchange.jusercore.container.login.UserLoginContainer;
39 import org.mxchange.jusercore.events.registration.UserRegisteredEvent;
40 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
41 import org.mxchange.jusercore.events.user.add.AdminUserAddedEvent;
42 import org.mxchange.jusercore.events.user.linked.AdminLinkedUserEvent;
43 import org.mxchange.jusercore.events.user.linked.AdminUserLinkedEvent;
44 import org.mxchange.jusercore.events.user.locked.AdminLockedUserEvent;
45 import org.mxchange.jusercore.events.user.locked.AdminUserLockedEvent;
46 import org.mxchange.jusercore.events.user.unlocked.AdminUnlockedUserEvent;
47 import org.mxchange.jusercore.events.user.unlocked.AdminUserUnlockedEvent;
48 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
49 import org.mxchange.jusercore.events.user.update.AdminUserDataUpdatedEvent;
50 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
51 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
52 import org.mxchange.jusercore.exceptions.UserNotFoundException;
53 import org.mxchange.jusercore.exceptions.UserPasswordRepeatMismatchException;
54 import org.mxchange.jusercore.exceptions.UserStatusConfirmedException;
55 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
56 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
57 import org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote;
58 import org.mxchange.jusercore.model.user.LoginUser;
59 import org.mxchange.jusercore.model.user.User;
60 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
61 import org.mxchange.jusercore.model.user.UserUtils;
62 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
63 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
66 * A user controller (bean)
68 * @author Roland Haeder<roland@mxchange.org>
70 @Named ("adminUserController")
72 public class JobsAdminUserWebRequestBean extends BaseJobsController implements JobsAdminUserWebRequestController {
77 private static final long serialVersionUID = 542_145_347_916L;
80 * An event fired when the administrator has added a new user
84 private Event<AdminAddedUserEvent> addedUserEvent;
87 * Regular contact controller
90 private JobsAdminContactWebRequestController adminContactController;
93 * Administrative user EJB
95 private final AdminUserSessionBeanRemote adminUserBean;
101 private JobsWebViewHelperController beanHelper;
104 * Regular contact controller
107 private JobsContactWebSessionController contactController;
110 * An event fired when the administrator has updated a new user
114 private Event<AdminUpdatedUserDataEvent> updatedUserDataEvent;
119 private final UserSessionBeanRemote userBean;
122 * Regular user controller
125 private JobsUserWebSessionController userController;
128 * An event fired when the administrator has linked a user with existing
133 private Event<AdminLinkedUserEvent> userLinkedEvent;
138 private String userLockReason;
141 * Event being fired when an administrator has locked a user
145 private Event<AdminLockedUserEvent> userLockedEvent;
148 * Flag whether user must change password after login
150 private Boolean userMustChangePassword;
155 private String userName;
158 * User password (unencrypted from web form)
160 private String userPassword;
163 * User password repeated (unencrypted from web form)
165 private String userPasswordRepeat;
168 * Event being fired when admin unlocks an account
172 private Event<AdminUnlockedUserEvent> userUnlockedEvent;
175 * Default constructor
177 public JobsAdminUserWebRequestBean () {
180 // Get initial context
181 Context context = new InitialContext();
184 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
185 this.adminUserBean = (AdminUserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote"); //NOI18N
186 } catch (final NamingException e) {
188 throw new FaceletException(e);
193 public String addUser () {
194 // As the form cannot validate the data (required="true"), check it here
195 if (this.getUserName() == null) {
197 throw new NullPointerException("userName is null"); //NOI18N
198 } else if (this.getUserName().isEmpty()) {
200 throw new IllegalArgumentException("userName is null"); //NOI18N
201 } else if (this.beanHelper.getContact() == null) {
202 // No contact instance set, so test required fields: gender, first name and family name
203 if (this.contactController.getGender() == null) {
205 throw new NullPointerException("contactController.gender is null"); //NOI18N
206 } else if (this.contactController.getFirstName() == null) {
208 throw new NullPointerException("contactController.firstName is null"); //NOI18N
209 } else if (this.adminContactController.getFirstName().isEmpty()) {
211 throw new IllegalArgumentException("contactController.firstName is empty"); //NOI18N
212 } else if (this.adminContactController.getFamilyName() == null) {
214 throw new NullPointerException("contactController.familyName is null"); //NOI18N
215 } else if (this.contactController.getFamilyName().isEmpty()) {
217 throw new IllegalArgumentException("contactController.familyName is empty"); //NOI18N
218 } else if (this.adminContactController.getEmailAddress() == null) {
220 throw new NullPointerException("contactController.emailAddress is null"); //NOI18N
221 } else if (this.adminContactController.getEmailAddress().isEmpty()) {
223 throw new IllegalArgumentException("contactController.emailAddress is empty"); //NOI18N
227 // Create new user instance
228 User user = new LoginUser();
230 // Set user name, CONFIRMED and INVISIBLE
231 user.setUserName(this.getUserName());
232 user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
233 user.setUserProfileMode(ProfileMode.INVISIBLE);
238 // Is a contact instance in helper set?
239 if (this.beanHelper.getContact() instanceof Contact) {
240 // Then use it for contact linking
241 contact = this.beanHelper.getContact();
243 // Create contact instance
244 contact = this.contactController.createContactInstance();
247 // Set contact in user
248 user.setUserContact(contact);
250 // Init variable for password
251 String password = null;
253 // Is the user name or email address used already?
254 // @TODO Add password length check
255 if (this.userController.isUserNameRegistered(user)) {
256 // User name is already used
257 throw new FaceletException(new UserNameAlreadyRegisteredException(user));
258 } else if ((this.beanHelper.getContact() == null) && (this.contactController.isEmailAddressRegistered(user.getUserContact()))) {
259 // Email address is already used
260 throw new FaceletException(new EmailAddressAlreadyRegisteredException(user));
261 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
262 // Empty password entered, then generate one
263 password = UserUtils.createRandomPassword(JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
264 } else if (!this.isSamePasswordEntered()) {
265 // Both passwords don't match
266 throw new FaceletException(new UserPasswordRepeatMismatchException(user));
268 // Both match, so get it from this bean
269 password = this.getUserPassword();
272 // The password should not be null and at least 5 characters long
273 assert (password != null) : "password is null"; //NOI18N
274 assert (password.length() >= JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
276 // Encrypt password and set it
277 user.setUserEncryptedPassword(UserUtils.encryptPassword(password));
280 // Now, that all is set, call EJB
281 if (this.beanHelper.getContact() instanceof Contact) {
282 // Link contact with this user
283 User updatedUser = this.adminUserBean.linkUser(user);
286 this.userLinkedEvent.fire(new AdminUserLinkedEvent(updatedUser));
288 // Remove contact instance
289 this.beanHelper.setContact(null);
292 User updatedUser = this.adminUserBean.addUser(user);
295 this.addedUserEvent.fire(new AdminUserAddedEvent(updatedUser));
297 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
299 throw new FaceletException(ex);
303 this.beanHelper.setContact(null);
308 // Return to user list (for now)
309 return "admin_list_user"; //NOI18N
313 public void afterUserRegistrationEvent (@Observes final UserRegisteredEvent event) {
314 // event should not be null
317 throw new NullPointerException("event is null"); //NOI18N
318 } else if (event.getRegisteredUser() == null) {
320 throw new NullPointerException("event.user is null"); //NOI18N
321 } else if (event.getRegisteredUser().getUserId() == null) {
323 throw new NullPointerException("event.user.userId is null"); //NOI18N
324 } else if (event.getRegisteredUser().getUserId() < 1) {
326 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
330 User registeredUser = event.getRegisteredUser();
333 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterRegistration: registeredUser={0}", registeredUser)); //NOI18N
338 //* NOISY-DEBUG: */ System.out.println("UserWebBean:afterRegistration: EXIT!"); //NOI18N
342 public String editUserData () {
344 User user = this.beanHelper.getUser();
346 // Null password means not setting it
347 String encryptedPassword = null;
349 // Check if user instance is in helper and valid
352 throw new NullPointerException("beanHelper.user is null"); //NOI18N
353 } else if (user.getUserId() == null) {
355 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
356 } else if (user.getUserId() < 1) {
358 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N
359 } else if (this.getUserName() == null) {
360 // Not all required fields are set
361 throw new NullPointerException("this.userName is null"); //NOI18N
362 } else if (this.getUserName().isEmpty()) {
363 // Not all required fields are set
364 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
365 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
366 // Not same password entered
367 this.setUserPassword(null);
368 this.setUserPasswordRepeat(null);
371 throw new FaceletException("Not same password entered"); //NOI18N
372 } else if (this.userBean.ifUserNameExists(this.getUserName())) {
373 // User name already exists
374 throw new FaceletException(new UserNameAlreadyRegisteredException(this.getUserName()));
375 } else if (this.isSamePasswordEntered()) {
376 // Same password entered, create container
377 if (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword()))) {
378 // Same password entered
379 throw new FaceletException("Same password as stored entered."); //NOI18N
383 encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
386 // Set user name and flag
387 user.setUserName(this.getUserName());
388 user.setUserMustChangePassword(this.getUserMustChangePassword());
390 // Is a password set?
391 if (encryptedPassword != null) {
393 user.setUserEncryptedPassword(encryptedPassword);
396 // Call EJB for updating user data
397 User updatedUser = this.userBean.updateUserData(user);
400 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
402 // Return to user list (for now)
403 return "admin_list_user"; //NOI18N
407 public String getUserLockReason () {
408 return this.userLockReason;
412 public void setUserLockReason (final String userLockReason) {
413 this.userLockReason = userLockReason;
417 public Boolean getUserMustChangePassword () {
418 return this.userMustChangePassword;
422 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
423 this.userMustChangePassword = userMustChangePassword;
427 public String getUserName () {
428 return this.userName;
432 public void setUserName (final String userName) {
433 this.userName = userName;
437 public String getUserPassword () {
438 return this.userPassword;
442 public void setUserPassword (final String userPassword) {
443 this.userPassword = userPassword;
447 public String getUserPasswordRepeat () {
448 return this.userPasswordRepeat;
452 public void setUserPasswordRepeat (final String userPasswordRepeat) {
453 this.userPasswordRepeat = userPasswordRepeat;
457 public String lockUserAccount (final User user) {
458 // Is the user instance valid and CONFIRMED?
461 throw new NullPointerException("user is null"); //NOI18N
462 } else if (user.getUserId() == null) {
464 throw new NullPointerException("user.userId is null"); //NOI18N
465 } else if (user.getUserId() < 1) {
467 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
468 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
469 // User account is locked
470 throw new FacesException(new UserStatusLockedException(user));
471 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
472 // User account is locked
473 throw new FaceletException(new UserStatusUnconfirmedException(user));
474 } else if (this.getUserLockReason() == null) {
476 throw new NullPointerException("this.userLockReason is null"); //NOI18N
477 } else if (this.getUserLockReason().isEmpty()) {
479 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
482 // Init updated user instance
487 String baseUrl = FacesUtils.generateBaseUrl();
489 // Call EJB to lock account
490 updatedUser = this.adminUserBean.lockUserAccount(user, this.getUserLockReason(), baseUrl);
491 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
493 throw new FaceletException(ex);
497 this.userLockedEvent.fire(new AdminUserLockedEvent(updatedUser));
502 // Should go fine at this point, redirect to user profile
503 return "admin_show_user"; //NOI18N
507 public String unlockUserAccount (final User user) {
508 // Is the user instance valid and CONFIRMED?
511 throw new NullPointerException("user is null"); //NOI18N
512 } else if (user.getUserId() == null) {
514 throw new NullPointerException("user.userId is null"); //NOI18N
515 } else if (user.getUserId() < 1) {
517 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
518 } else if (user.getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
519 // User account is locked
520 throw new FacesException(new UserStatusConfirmedException(user));
521 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
522 // User account is locked
523 throw new FaceletException(new UserStatusUnconfirmedException(user));
526 // Init updated user instance
531 String baseUrl = FacesUtils.generateBaseUrl();
533 // Call EJB to unlock account
534 updatedUser = this.adminUserBean.unlockUserAccount(user, baseUrl);
535 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
537 throw new FaceletException(ex);
541 this.userUnlockedEvent.fire(new AdminUserUnlockedEvent(updatedUser));
546 // Should go fine at this point, redirect to user profile
547 return "admin_show_user"; //NOI18N
553 private void clear () {
556 this.setUserName(null);
557 this.setUserPassword(null);
558 this.setUserPasswordRepeat(null);
559 this.setUserMustChangePassword(null);
563 * Checks if same password is entered and that they are not empty.
565 * @return Whether the same password was entered
567 private boolean isSamePasswordEntered () {
568 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));