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.JobsWebRequestController;
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.AdminUserLinkedEvent;
43 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
44 import org.mxchange.jusercore.events.user.update.AdminUserDataUpdatedEvent;
45 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
46 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
47 import org.mxchange.jusercore.exceptions.UserNotFoundException;
48 import org.mxchange.jusercore.exceptions.UserPasswordRepeatMismatchException;
49 import org.mxchange.jusercore.exceptions.UserStatusConfirmedException;
50 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
51 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
52 import org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote;
53 import org.mxchange.jusercore.model.user.LoginUser;
54 import org.mxchange.jusercore.model.user.User;
55 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
56 import org.mxchange.jusercore.model.user.UserUtils;
57 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
58 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
61 * A user bean (controller)
63 * @author Roland Haeder<roland@mxchange.org>
65 @Named ("adminUserController")
67 public class JobsAdminUserWebRequestBean extends BaseJobsController implements JobsAdminUserWebRequestController {
72 private static final long serialVersionUID = 542_145_347_916L;
75 * An event fired when the administrator has added a new user
79 private Event<AdminAddedUserEvent> addedUserEvent;
82 * Regular contact controller
85 private JobsAdminContactWebRequestController adminContactController;
88 * Administrative user EJB
90 private final AdminUserSessionBeanRemote adminUserBean;
93 * Admin helper instance
96 private JobsWebRequestController beanHelper;
99 * Regular contact controller
102 private JobsContactWebSessionController contactController;
105 * An event fired when the administrator has updated a new user
109 private Event<AdminUpdatedUserDataEvent> updatedUserDataEvent;
114 private final UserSessionBeanRemote userBean;
117 * Regular user controller
120 private JobsUserWebSessionController userController;
125 private String userLockReason;
128 * Flag whether user must change password after login
130 private Boolean userMustChangePassword;
135 private String userName;
138 * User password (unencrypted from web form)
140 private String userPassword;
143 * User password repeated (unencrypted from web form)
145 private String userPasswordRepeat;
148 * Default constructor
150 public JobsAdminUserWebRequestBean () {
153 // Get initial context
154 Context context = new InitialContext();
157 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
158 this.adminUserBean = (AdminUserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote"); //NOI18N
159 } catch (final NamingException e) {
161 throw new FaceletException(e);
166 public String addUser () {
167 // As the form cannot validate the data (required="true"), check it here
168 if (this.getUserName() == null) {
170 throw new NullPointerException("userName is null"); //NOI18N
171 } else if (this.getUserName().isEmpty()) {
173 throw new IllegalArgumentException("userName is null"); //NOI18N
174 } else if (this.beanHelper.getContact() == null) {
175 // No contact instance set, so test required fields: gender, first name and family name
176 if (this.contactController.getGender() == null) {
178 throw new NullPointerException("contactController.gender is null"); //NOI18N
179 } else if (this.contactController.getFirstName() == null) {
181 throw new NullPointerException("contactController.firstName is null"); //NOI18N //NOI18N
182 } else if (this.contactController.getFirstName().isEmpty()) {
184 throw new IllegalArgumentException("contactController.firstName is empty"); //NOI18N
185 } else if (this.adminContactController.getFamilyName() == null) {
187 throw new NullPointerException("contactController.familyName is null"); //NOI18N
188 } else if (this.contactController.getFamilyName().isEmpty()) {
190 throw new IllegalArgumentException("contactController.familyName is empty"); //NOI18N //NOI18N
191 } else if (this.contactController.getEmailAddress() == null) {
193 throw new NullPointerException("contactController.emailAddress is null"); //NOI18N
194 } else if (this.adminContactController.getEmailAddress().isEmpty()) {
196 throw new IllegalArgumentException("contactController.emailAddress is empty"); //NOI18N //NOI18N
197 } else if (this.contactController.getEmailAddressRepeat() == null) {
199 throw new NullPointerException("contactController.emailAddressRepeat is null");
200 } else if (this.contactController.getEmailAddressRepeat().isEmpty()) {
202 throw new IllegalArgumentException("contactController.emailAddressRepeat is empty"); //NOI18N //NOI18N
203 } else if (!Objects.equals(this.contactController.getEmailAddress(), this.contactController.getEmailAddressRepeat())) {
204 // Is not same email address
205 throw new IllegalArgumentException("Both entered email addresses don't match.");
209 // Create new user instance
210 User user = new LoginUser();
212 // Set user name, CONFIRMED and INVISIBLE
213 user.setUserName(this.getUserName());
214 user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
215 user.setUserProfileMode(ProfileMode.INVISIBLE);
220 // Is a contact instance in helper set?
221 if (this.beanHelper.getContact() instanceof Contact) {
222 // Then use it for contact linking
223 contact = this.beanHelper.getContact();
225 // Create contact instance
226 contact = this.contactController.createContactInstance();
229 // Set contact in user
230 user.setUserContact(contact);
232 // Init variable for password
233 String password = null;
235 // Is the user name or email address used already?
236 // @TODO Add password length check
237 if (this.userController.isUserNameRegistered(user)) {
238 // User name is already used
239 throw new FaceletException(new UserNameAlreadyRegisteredException(user));
240 } else if ((this.beanHelper.getContact() == null) && (this.contactController.isEmailAddressRegistered(user.getUserContact()))) {
241 // Email address is already used
242 throw new FaceletException(new EmailAddressAlreadyRegisteredException(user));
243 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
244 // Empty password entered, then generate one
245 password = UserUtils.createRandomPassword(JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
246 } else if (!this.isSamePasswordEntered()) {
247 // Both passwords don't match
248 throw new FaceletException(new UserPasswordRepeatMismatchException(user));
250 // Both match, so get it from this bean
251 password = this.getUserPassword();
254 // The password should not be null and at least 5 characters long
255 assert (password != null) : "password is null"; //NOI18N
256 assert (password.length() >= JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
258 // Encrypt password and set it
259 user.setUserEncryptedPassword(UserUtils.encryptPassword(password));
262 // Now, that all is set, call EJB
263 if (this.beanHelper.getContact() instanceof Contact) {
264 // Link contact with this user
265 User updatedUser = this.adminUserBean.linkUser(user);
268 this.userLinkedEvent.fire(new AdminUserLinkedEvent(updatedUser));
270 // Remove contact instance
271 this.beanHelper.setContact(null);
274 User updatedUser = this.adminUserBean.addUser(user);
277 this.addedUserEvent.fire(new AdminUserAddedEvent(updatedUser));
279 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
281 throw new FaceletException(ex);
285 this.beanHelper.setContact(null);
287 // Return to user list (for now)
288 return "admin_list_user"; //NOI18N
292 public void afterRegistrationEvent (@Observes final UserRegisteredEvent event) {
294 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterRegistration: event={0} - CALLED!", event)); //NOI18N
296 // event should not be null
299 throw new NullPointerException("event is null"); //NOI18N
300 } else if (event.getRegisteredUser() == null) {
302 throw new NullPointerException("event.user is null"); //NOI18N
303 } else if (event.getRegisteredUser().getUserId() == null) {
305 throw new NullPointerException("event.user.userId is null"); //NOI18N
306 } else if (event.getRegisteredUser().getUserId() < 1) {
308 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
312 User registeredUser = event.getRegisteredUser();
315 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterRegistration: registeredUser={0}", registeredUser)); //NOI18N
321 //* NOISY-DEBUG: */ System.out.println("UserWebBean:afterRegistration: EXIT!"); //NOI18N
325 public String editUserData () {
327 User user = this.beanHelper.getUser();
329 // Null password means not setting it
330 String encryptedPassword = null;
332 // Check if user instance is in helper and valid
335 throw new NullPointerException("beanHelper.user is null"); //NOI18N
336 } else if (user.getUserId() == null) {
338 throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N //NOI18N
339 } else if (user.getUserId() < 1) {
341 throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N
342 } else if (this.getUserName() == null) {
343 // Not all required fields are set
344 throw new NullPointerException("this.userName is null"); //NOI18N
345 } else if (this.getUserName().isEmpty()) {
346 // Not all required fields are set
347 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
348 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
349 // Not same password entered
350 this.setUserPassword(null);
351 this.setUserPasswordRepeat(null);
354 throw new FaceletException("Not same password entered"); //NOI18N
355 } else if (this.userBean.ifUserNameExists(this.getUserName())) {
356 // User name already exists
357 throw new FaceletException(new UserNameAlreadyRegisteredException(this.getUserName()));
358 } else if (this.isSamePasswordEntered()) {
359 // Same password entered, create container
360 if (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword()))) {
361 // Same password entered
362 throw new FaceletException("Same password as stored entered."); //NOI18N
366 encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
369 // Set user name and flag
370 user.setUserName(this.getUserName());
371 user.setUserMustChangePassword(this.getUserMustChangePassword());
373 // Is a password set?
374 if (encryptedPassword != null) {
376 user.setUserEncryptedPassword(encryptedPassword);
379 // Call EJB for updating user data
380 User updatedUser = this.userBean.updateUserData(user);
383 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
385 // Return to user list (for now)
386 return "admin_list_user"; //NOI18N
390 public String getUserLockReason () {
391 return this.userLockReason;
395 public void setUserLockReason (final String userLockReason) {
396 this.userLockReason = userLockReason;
400 public Boolean getUserMustChangePassword () {
401 return this.userMustChangePassword;
405 public void setUserMustChangePassword (final Boolean userMustChangePassword) {
406 this.userMustChangePassword = userMustChangePassword;
410 public String getUserName () {
411 return this.userName;
415 public void setUserName (final String userName) {
416 this.userName = userName;
420 public String getUserPassword () {
421 return this.userPassword;
425 public void setUserPassword (final String userPassword) {
426 this.userPassword = userPassword;
430 public String getUserPasswordRepeat () {
431 return this.userPasswordRepeat;
435 public void setUserPasswordRepeat (final String userPasswordRepeat) {
436 this.userPasswordRepeat = userPasswordRepeat;
440 public String lockUserAccount (final User user) {
441 // Is the user instance valid and CONFIRMED?
444 throw new NullPointerException("user is null"); //NOI18N
445 } else if (user.getUserId() == null) {
447 throw new NullPointerException("user.userId is null"); //NOI18N
448 } else if (user.getUserId() < 1) {
450 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
451 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
452 // User account is locked
453 throw new FacesException(new UserStatusLockedException(user));
454 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
455 // User account is locked
456 throw new FaceletException(new UserStatusUnconfirmedException(user));
457 } else if (this.getUserLockReason() == null) {
459 throw new NullPointerException("this.userLockReason is null"); //NOI18N
460 } else if (this.getUserLockReason().isEmpty()) {
462 throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
467 String baseUrl = FacesUtils.generateBaseUrl();
469 // Call EJB to lock account
470 this.adminUserBean.lockUserAccount(user, this.getUserLockReason(), baseUrl);
471 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
473 throw new FaceletException(ex);
476 // Should go fine at this point, redirect to user profile
477 return "admin_show_user?faces-redirect=true&includeViewParams=true"; //NOI18N
481 public String unlockUserAccount (final User user) {
482 // Is the user instance valid and CONFIRMED?
485 throw new NullPointerException("user is null"); //NOI18N
486 } else if (user.getUserId() == null) {
488 throw new NullPointerException("user.userId is null"); //NOI18N
489 } else if (user.getUserId() < 1) {
491 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
492 } else if (user.getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
493 // User account is locked
494 throw new FacesException(new UserStatusConfirmedException(user));
495 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
496 // User account is locked
497 throw new FaceletException(new UserStatusUnconfirmedException(user));
502 String baseUrl = FacesUtils.generateBaseUrl();
504 // Call EJB to unlock account
505 this.adminUserBean.unlockUserAccount(user, baseUrl);
506 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
508 throw new FaceletException(ex);
511 // Should go fine at this point, redirect to user profile
512 return "admin_show_user?faces-redirect=true&includeViewParams=true"; //NOI18N
518 private void clear () {
521 this.setUserName(null);
522 this.setUserPassword(null);
523 this.setUserPasswordRepeat(null);
524 this.setUserMustChangePassword(null);
528 * Checks if same password is entered and that they are not empty.
530 * @return Whether the same password was entered
532 private boolean isSamePasswordEntered () {
533 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));