]> git.mxchange.org Git - jjobs-war.git/blob - src/java/org/mxchange/jjobs/beans/user/JobsAdminUserWebRequestBean.java
d78d7062b0f8e9e495f4c44074e6a1cb4cf3814e
[jjobs-war.git] / src / java / org / mxchange / jjobs / beans / user / JobsAdminUserWebRequestBean.java
1 /*
2  * Copyright (C) 2016 Roland Haeder
3  *
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.
8  *
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.
13  *
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/>.
16  */
17 package org.mxchange.jjobs.beans.user;
18
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.jjobs.beans.localization.JobsLocalizationSessionController;
39 import org.mxchange.jusercore.container.login.UserLoginContainer;
40 import org.mxchange.jusercore.events.registration.UserRegisteredEvent;
41 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
42 import org.mxchange.jusercore.events.user.add.AdminUserAddedEvent;
43 import org.mxchange.jusercore.events.user.delete.AdminDeletedUserEvent;
44 import org.mxchange.jusercore.events.user.delete.AdminUserDeletedEvent;
45 import org.mxchange.jusercore.events.user.linked.AdminLinkedUserEvent;
46 import org.mxchange.jusercore.events.user.linked.AdminUserLinkedEvent;
47 import org.mxchange.jusercore.events.user.locked.AdminLockedUserEvent;
48 import org.mxchange.jusercore.events.user.locked.AdminUserLockedEvent;
49 import org.mxchange.jusercore.events.user.unlocked.AdminUnlockedUserEvent;
50 import org.mxchange.jusercore.events.user.unlocked.AdminUserUnlockedEvent;
51 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
52 import org.mxchange.jusercore.events.user.update.AdminUserDataUpdatedEvent;
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;
67
68 /**
69  * A user controller (bean)
70  * <p>
71  * @author Roland Haeder<roland@mxchange.org>
72  */
73 @Named ("adminUserController")
74 @RequestScoped
75 public class JobsAdminUserWebRequestBean extends BaseJobsController implements JobsAdminUserWebRequestController {
76
77         /**
78          * Serial number
79          */
80         private static final long serialVersionUID = 542_145_347_916L;
81
82         /**
83          * An event fired when the administrator has added a new user
84          */
85         @Inject
86         @Any
87         private Event<AdminAddedUserEvent> addedUserEvent;
88
89         /**
90          * Regular contact controller
91          */
92         @Inject
93         private JobsAdminContactWebRequestController adminContactController;
94
95         /**
96          * Administrative user EJB
97          */
98         private final AdminUserSessionBeanRemote adminUserBean;
99
100         /**
101          * Bean helper
102          */
103         @Inject
104         private JobsWebViewHelperController beanHelper;
105
106         /**
107          * Regular contact controller
108          */
109         @Inject
110         private JobsContactWebSessionController contactController;
111
112         /**
113          * Event being fired when admin has deleted user
114          */
115         @Inject
116         @Any
117         private Event<AdminDeletedUserEvent> deleteUserEvent;
118
119         /**
120          * Localization controller
121          */
122         @Inject
123         private JobsLocalizationSessionController localizationController;
124
125         /**
126          * An event fired when the administrator has updated a new user
127          */
128         @Inject
129         @Any
130         private Event<AdminUpdatedUserDataEvent> updatedUserDataEvent;
131
132         /**
133          * General user EJB
134          */
135         private final UserSessionBeanRemote userBean;
136
137         /**
138          * Regular user controller
139          */
140         @Inject
141         private JobsUserWebSessionController userController;
142
143         /**
144          * Delete reason
145          */
146         private String userDeleteReason;
147
148         /**
149          * An event fired when the administrator has linked a user with existing
150          * contact data.
151          */
152         @Inject
153         @Any
154         private Event<AdminLinkedUserEvent> userLinkedEvent;
155
156         /**
157          * User lock reason
158          */
159         private String userLockReason;
160
161         /**
162          * Event being fired when an administrator has locked a user
163          */
164         @Inject
165         @Any
166         private Event<AdminLockedUserEvent> userLockedEvent;
167
168         /**
169          * Flag whether user must change password after login
170          */
171         private Boolean userMustChangePassword;
172
173         /**
174          * User name
175          */
176         private String userName;
177
178         /**
179          * User password (unencrypted from web form)
180          */
181         private String userPassword;
182
183         /**
184          * User password repeated (unencrypted from web form)
185          */
186         private String userPasswordRepeat;
187
188         /**
189          * Event being fired when admin unlocks an account
190          */
191         @Inject
192         @Any
193         private Event<AdminUnlockedUserEvent> userUnlockedEvent;
194
195         /**
196          * Default constructor
197          */
198         public JobsAdminUserWebRequestBean () {
199                 // Try it
200                 try {
201                         // Get initial context
202                         Context context = new InitialContext();
203
204                         // Try to lookup
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/user!org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote"); //NOI18N
207                 } catch (final NamingException e) {
208                         // Throw again
209                         throw new FaceletException(e);
210                 }
211         }
212
213         @Override
214         public String addUser () {
215                 // As the form cannot validate the data (required="true"), check it here
216                 if (this.getUserName() == null) {
217                         // Throw NPE
218                         throw new NullPointerException("userName is null"); //NOI18N
219                 } else if (this.getUserName().isEmpty()) {
220                         // Is empty
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) {
225                                 // Throw NPE again
226                                 throw new NullPointerException("contactController.gender is null"); //NOI18N
227                         } else if (this.contactController.getFirstName() == null) {
228                                 // ... and again
229                                 throw new NullPointerException("contactController.firstName is null"); //NOI18N
230                         } else if (this.adminContactController.getFirstName().isEmpty()) {
231                                 // ... and again
232                                 throw new IllegalArgumentException("contactController.firstName is empty"); //NOI18N
233                         } else if (this.adminContactController.getFamilyName() == null) {
234                                 // ... and again
235                                 throw new NullPointerException("contactController.familyName is null"); //NOI18N
236                         } else if (this.contactController.getFamilyName().isEmpty()) {
237                                 // ... and again
238                                 throw new IllegalArgumentException("contactController.familyName is empty"); //NOI18N
239                         } else if (this.adminContactController.getEmailAddress() == null) {
240                                 // ... and again
241                                 throw new NullPointerException("contactController.emailAddress is null"); //NOI18N
242                         } else if (this.adminContactController.getEmailAddress().isEmpty()) {
243                                 // ... and again
244                                 throw new IllegalArgumentException("contactController.emailAddress is empty"); //NOI18N
245                         }
246                 }
247
248                 // Create new user instance
249                 User user = new LoginUser();
250
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);
256
257                 // Init instance
258                 Contact contact;
259
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();
264                 } else {
265                         // Create contact instance
266                         contact = this.contactController.createContactInstance();
267                 }
268
269                 // Set contact in user
270                 user.setUserContact(contact);
271
272                 // Init variable for password
273                 String password = null;
274
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                         throw new FaceletException(new EmailAddressAlreadyRegisteredException(user));
283                 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
284                         // Empty password entered, then generate one
285                         password = UserUtils.createRandomPassword(JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
286                 } else if (!this.isSamePasswordEntered()) {
287                         // Both passwords don't match
288                         throw new FaceletException(new UserPasswordRepeatMismatchException(user));
289                 } else {
290                         // Both match, so get it from this bean
291                         password = this.getUserPassword();
292                 }
293
294                 // The password should not be null and at least 5 characters long
295                 assert (password != null) : "password is null"; //NOI18N
296                 assert (password.length() >= JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
297
298                 // Encrypt password and set it
299                 user.setUserEncryptedPassword(UserUtils.encryptPassword(password));
300
301                 try {
302                         // Now, that all is set, call EJB
303                         if (this.beanHelper.getContact() instanceof Contact) {
304                                 // Link contact with this user
305                                 User updatedUser = this.adminUserBean.linkUser(user);
306
307                                 // Fire event
308                                 this.userLinkedEvent.fire(new AdminUserLinkedEvent(updatedUser));
309
310                                 // Remove contact instance
311                                 this.beanHelper.setContact(null);
312                         } else {
313                                 // Add new contact
314                                 User updatedUser = this.adminUserBean.addUser(user);
315
316                                 // Fire event
317                                 this.addedUserEvent.fire(new AdminUserAddedEvent(updatedUser));
318                         }
319                 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
320                         // Throw again
321                         throw new FaceletException(ex);
322                 }
323
324                 // Clear helper
325                 this.beanHelper.setContact(null);
326
327                 // Clear this bean
328                 this.clear();
329
330                 // Return to user list (for now)
331                 return "admin_list_user"; //NOI18N
332         }
333
334         @Override
335         public void afterUserRegistrationEvent (@Observes final UserRegisteredEvent event) {
336                 // event should not be null
337                 if (null == event) {
338                         // Throw NPE
339                         throw new NullPointerException("event is null"); //NOI18N
340                 } else if (event.getRegisteredUser() == null) {
341                         // Throw NPE again
342                         throw new NullPointerException("event.user is null"); //NOI18N
343                 } else if (event.getRegisteredUser().getUserId() == null) {
344                         // userId is null
345                         throw new NullPointerException("event.user.userId is null"); //NOI18N
346                 } else if (event.getRegisteredUser().getUserId() < 1) {
347                         // Not avalid id
348                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
349                 }
350
351                 // Get user instance
352                 User registeredUser = event.getRegisteredUser();
353
354                 // Debug message
355                 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterRegistration: registeredUser={0}", registeredUser)); //NOI18N
356                 // Clear all data
357                 this.clear();
358
359                 // Trace message
360                 //* NOISY-DEBUG: */ System.out.println("UserWebBean:afterRegistration: EXIT!"); //NOI18N
361         }
362
363         @Override
364         public String deleteUserData (final User user) {
365                 // Is the user instance valid and CONFIRMED?
366                 if (null == user) {
367                         // Throw NPE
368                         throw new NullPointerException("user is null"); //NOI18N
369                 } else if (user.getUserId() == null) {
370                         // Throw again
371                         throw new NullPointerException("user.userId is null"); //NOI18N
372                 } else if (user.getUserId() < 1) {
373                         // Invalid id number
374                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
375                 }
376
377                 try {
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);
383                 }
384
385                 // Fire event
386                 this.deleteUserEvent.fire(new AdminUserDeletedEvent(user, this.getUserDeleteReason()));
387
388                 // Redirect
389                 return "admin_list_user"; //NOI18N
390         }
391
392         @Override
393         public String editUserData () {
394                 // Get user instance
395                 User user = this.beanHelper.getUser();
396
397                 // Null password means not setting it
398                 String encryptedPassword = null;
399
400                 // Check if user instance is in helper and valid
401                 if (null == user) {
402                         // Throw NPE
403                         throw new NullPointerException("beanHelper.user is null"); //NOI18N
404                 } else if (user.getUserId() == null) {
405                         // Throw NPE again
406                         throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
407                 } else if (user.getUserId() < 1) {
408                         // Invalid id
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);
420
421                         // Not same password entered
422                         this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_PASSWORD_REPEAT_DIFFERENT"); //NOI18N
423                         return ""; //NOI18N
424                 } else if ((!Objects.equals(user.getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
425                         // Clear all fields
426                         this.clear();
427
428                         // User name already exists
429                         this.showFacesMessage("form_edit_user:userName", "ADMIN_USER_NAME_ALREADY_EXISTS"); //NOI18N
430                         return ""; //NOI18N
431                 } else if (this.isSamePasswordEntered()) {
432                         // Same password entered, create container
433                         if ((Objects.equals(user.getUserMustChangePassword(), this.getUserMustChangePassword())) && (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword())))) {
434                                 // Clear password fields
435                                 this.setUserPassword(null);
436                                 this.setUserPasswordRepeat(null);
437
438                                 // Same password entered
439                                 this.showFacesMessage("form_edit_user:userPassword", "ADMIN_USER_ENTERED_SAME_AS_OLD_PASSWORD"); //NOI18N
440                                 return ""; //NOI18N
441                         }
442
443                         // Encrypt password
444                         encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
445                 }
446
447                 // Set user name and flag
448                 user.setUserName(this.getUserName());
449                 user.setUserMustChangePassword(this.getUserMustChangePassword());
450
451                 // Is a password set?
452                 if (encryptedPassword != null) {
453                         // Set it as well
454                         user.setUserEncryptedPassword(encryptedPassword);
455                 }
456
457                 // Call EJB for updating user data
458                 User updatedUser = this.userBean.updateUserData(user);
459
460                 // Fire event
461                 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
462
463                 // Return to user list (for now)
464                 return "admin_list_user"; //NOI18N
465         }
466
467         @Override
468         public String getUserDeleteReason () {
469                 return this.userDeleteReason;
470         }
471
472         @Override
473         public void setUserDeleteReason (final String userDeleteReason) {
474                 this.userDeleteReason = userDeleteReason;
475         }
476
477         @Override
478         public String getUserLockReason () {
479                 return this.userLockReason;
480         }
481
482         @Override
483         public void setUserLockReason (final String userLockReason) {
484                 this.userLockReason = userLockReason;
485         }
486
487         @Override
488         public Boolean getUserMustChangePassword () {
489                 return this.userMustChangePassword;
490         }
491
492         @Override
493         public void setUserMustChangePassword (final Boolean userMustChangePassword) {
494                 this.userMustChangePassword = userMustChangePassword;
495         }
496
497         @Override
498         public String getUserName () {
499                 return this.userName;
500         }
501
502         @Override
503         public void setUserName (final String userName) {
504                 this.userName = userName;
505         }
506
507         @Override
508         public String getUserPassword () {
509                 return this.userPassword;
510         }
511
512         @Override
513         public void setUserPassword (final String userPassword) {
514                 this.userPassword = userPassword;
515         }
516
517         @Override
518         public String getUserPasswordRepeat () {
519                 return this.userPasswordRepeat;
520         }
521
522         @Override
523         public void setUserPasswordRepeat (final String userPasswordRepeat) {
524                 this.userPasswordRepeat = userPasswordRepeat;
525         }
526
527         @Override
528         public String lockUserAccount (final User user) {
529                 // Is the user instance valid and CONFIRMED?
530                 if (null == user) {
531                         // Throw NPE
532                         throw new NullPointerException("user is null"); //NOI18N
533                 } else if (user.getUserId() == null) {
534                         // Throw again
535                         throw new NullPointerException("user.userId is null"); //NOI18N
536                 } else if (user.getUserId() < 1) {
537                         // Invalid id number
538                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
539                 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
540                         // User account is locked
541                         throw new FacesException(new UserStatusLockedException(user));
542                 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
543                         // User account is locked
544                         throw new FaceletException(new UserStatusUnconfirmedException(user));
545                 } else if (this.getUserLockReason() == null) {
546                         // Throw NPE again
547                         throw new NullPointerException("this.userLockReason is null"); //NOI18N
548                 } else if (this.getUserLockReason().isEmpty()) {
549                         // Empty lock reason
550                         throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
551                 }
552
553                 // Init updated user instance
554                 User updatedUser;
555
556                 try {
557                         // Get base URL
558                         String baseUrl = FacesUtils.generateBaseUrl();
559
560                         // Call EJB to lock account
561                         updatedUser = this.adminUserBean.lockUserAccount(user, this.getUserLockReason(), baseUrl);
562                 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
563                         // Throw again
564                         throw new FaceletException(ex);
565                 }
566
567                 // Fire event
568                 this.userLockedEvent.fire(new AdminUserLockedEvent(updatedUser));
569
570                 // Clear bean
571                 this.clear();
572
573                 // Should go fine at this point, redirect to user profile
574                 return "admin_show_user"; //NOI18N
575         }
576
577         @Override
578         public String unlockUserAccount (final User user) {
579                 // Is the user instance valid and CONFIRMED?
580                 if (null == user) {
581                         // Throw NPE
582                         throw new NullPointerException("user is null"); //NOI18N
583                 } else if (user.getUserId() == null) {
584                         // Throw again
585                         throw new NullPointerException("user.userId is null"); //NOI18N
586                 } else if (user.getUserId() < 1) {
587                         // Invalid id number
588                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
589                 } else if (user.getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
590                         // User account is locked
591                         throw new FacesException(new UserStatusConfirmedException(user));
592                 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
593                         // User account is locked
594                         throw new FaceletException(new UserStatusUnconfirmedException(user));
595                 }
596
597                 // Init updated user instance
598                 User updatedUser;
599
600                 try {
601                         // Get base URL
602                         String baseUrl = FacesUtils.generateBaseUrl();
603
604                         // Call EJB to unlock account
605                         updatedUser = this.adminUserBean.unlockUserAccount(user, baseUrl);
606                 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
607                         // Throw again
608                         throw new FaceletException(ex);
609                 }
610
611                 // Fire event
612                 this.userUnlockedEvent.fire(new AdminUserUnlockedEvent(updatedUser));
613
614                 // Clear bean
615                 this.clear();
616
617                 // Should go fine at this point, redirect to user profile
618                 return "admin_show_user"; //NOI18N
619         }
620
621         /**
622          * Clears this bean
623          */
624         private void clear () {
625                 // Clear all data
626                 // - other data
627                 this.setUserName(null);
628                 this.setUserPassword(null);
629                 this.setUserPasswordRepeat(null);
630                 this.setUserMustChangePassword(null);
631         }
632
633         /**
634          * Checks if same password is entered and that they are not empty.
635          * <p>
636          * @return Whether the same password was entered
637          */
638         private boolean isSamePasswordEntered () {
639                 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
640         }
641
642 }