]> git.mxchange.org Git - jjobs-war.git/blob - src/java/org/mxchange/jjobs/beans/user/JobsAdminUserWebRequestBean.java
1776e0e50a5d28add8bdad1de36bbd61d080ff3e
[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.setUserAccountStatus(UserAccountStatus.CONFIRMED);
254                 user.setUserProfileMode(ProfileMode.INVISIBLE);
255
256                 // Init instance
257                 Contact contact;
258
259                 // Is a contact instance in helper set?
260                 if (this.beanHelper.getContact() instanceof Contact) {
261                         // Then use it for contact linking
262                         contact = this.beanHelper.getContact();
263                 } else {
264                         // Create contact instance
265                         contact = this.contactController.createContactInstance();
266                 }
267
268                 // Set contact in user
269                 user.setUserContact(contact);
270
271                 // Init variable for password
272                 String password = null;
273
274                 // Is the user name or email address used already?
275                 // @TODO Add password length check
276                 if (this.userController.isUserNameRegistered(user)) {
277                         // User name is already used
278                         throw new FaceletException(new UserNameAlreadyRegisteredException(user));
279                 } else if ((this.beanHelper.getContact() == null) && (this.contactController.isEmailAddressRegistered(user.getUserContact()))) {
280                         // Email address is already used
281                         throw new FaceletException(new EmailAddressAlreadyRegisteredException(user));
282                 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
283                         // Empty password entered, then generate one
284                         password = UserUtils.createRandomPassword(JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
285                 } else if (!this.isSamePasswordEntered()) {
286                         // Both passwords don't match
287                         throw new FaceletException(new UserPasswordRepeatMismatchException(user));
288                 } else {
289                         // Both match, so get it from this bean
290                         password = this.getUserPassword();
291                 }
292
293                 // The password should not be null and at least 5 characters long
294                 assert (password != null) : "password is null"; //NOI18N
295                 assert (password.length() >= JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
296
297                 // Encrypt password and set it
298                 user.setUserEncryptedPassword(UserUtils.encryptPassword(password));
299
300                 try {
301                         // Now, that all is set, call EJB
302                         if (this.beanHelper.getContact() instanceof Contact) {
303                                 // Link contact with this user
304                                 User updatedUser = this.adminUserBean.linkUser(user);
305
306                                 // Fire event
307                                 this.userLinkedEvent.fire(new AdminUserLinkedEvent(updatedUser));
308
309                                 // Remove contact instance
310                                 this.beanHelper.setContact(null);
311                         } else {
312                                 // Add new contact
313                                 User updatedUser = this.adminUserBean.addUser(user);
314
315                                 // Fire event
316                                 this.addedUserEvent.fire(new AdminUserAddedEvent(updatedUser));
317                         }
318                 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
319                         // Throw again
320                         throw new FaceletException(ex);
321                 }
322
323                 // Clear helper
324                 this.beanHelper.setContact(null);
325
326                 // Clear this bean
327                 this.clear();
328
329                 // Return to user list (for now)
330                 return "admin_list_user"; //NOI18N
331         }
332
333         @Override
334         public void afterUserRegistrationEvent (@Observes final UserRegisteredEvent event) {
335                 // event should not be null
336                 if (null == event) {
337                         // Throw NPE
338                         throw new NullPointerException("event is null"); //NOI18N
339                 } else if (event.getRegisteredUser() == null) {
340                         // Throw NPE again
341                         throw new NullPointerException("event.user is null"); //NOI18N
342                 } else if (event.getRegisteredUser().getUserId() == null) {
343                         // userId is null
344                         throw new NullPointerException("event.user.userId is null"); //NOI18N
345                 } else if (event.getRegisteredUser().getUserId() < 1) {
346                         // Not avalid id
347                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
348                 }
349
350                 // Get user instance
351                 User registeredUser = event.getRegisteredUser();
352
353                 // Debug message
354                 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterRegistration: registeredUser={0}", registeredUser)); //NOI18N
355                 // Clear all data
356                 this.clear();
357
358                 // Trace message
359                 //* NOISY-DEBUG: */ System.out.println("UserWebBean:afterRegistration: EXIT!"); //NOI18N
360         }
361
362         @Override
363         public String deleteUserData (final User user) {
364                 // Is the user instance valid and CONFIRMED?
365                 if (null == user) {
366                         // Throw NPE
367                         throw new NullPointerException("user is null"); //NOI18N
368                 } else if (user.getUserId() == null) {
369                         // Throw again
370                         throw new NullPointerException("user.userId is null"); //NOI18N
371                 } else if (user.getUserId() < 1) {
372                         // Invalid id number
373                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
374                 }
375
376                 try {
377                         // All fine, delete it
378                         this.adminUserBean.deleteUser(user, this.getUserDeleteReason());
379                 } catch (final UserNotFoundException ex) {
380                         // Should not happen, so throw again
381                         throw new FaceletException(ex);
382                 }
383
384                 // Fire event
385                 this.deleteUserEvent.fire(new AdminUserDeletedEvent(user, this.getUserDeleteReason()));
386
387                 // Redirect
388                 return "admin_list_user"; //NOI18N
389         }
390
391         @Override
392         public String editUserData () {
393                 // Get user instance
394                 User user = this.beanHelper.getUser();
395
396                 // Null password means not setting it
397                 String encryptedPassword = null;
398
399                 // Check if user instance is in helper and valid
400                 if (null == user) {
401                         // Throw NPE
402                         throw new NullPointerException("beanHelper.user is null"); //NOI18N
403                 } else if (user.getUserId() == null) {
404                         // Throw NPE again
405                         throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
406                 } else if (user.getUserId() < 1) {
407                         // Invalid id
408                         throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N
409                 } else if (this.getUserName() == null) {
410                         // Not all required fields are set
411                         throw new NullPointerException("this.userName is null"); //NOI18N
412                 } else if (this.getUserName().isEmpty()) {
413                         // Not all required fields are set
414                         throw new IllegalArgumentException("this.userName is empty"); //NOI18N
415                 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
416                         // Not same password entered
417                         this.setUserPassword(null);
418                         this.setUserPasswordRepeat(null);
419
420                         // Throw exception
421                         throw new FaceletException("Not same password entered"); //NOI18N
422                 } else if ((!Objects.equals(user.getUserName(), this.getUserName())) && (this.userBean.ifUserNameExists(this.getUserName()))) {
423                         // User name already exists
424                         throw new FaceletException(new UserNameAlreadyRegisteredException(this.getUserName()));
425                 } else if (this.isSamePasswordEntered()) {
426                         // Same password entered, create container
427                         if (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword()))) {
428                                 // Same password entered
429                                 throw new FaceletException("Same password as stored entered."); //NOI18N
430                         }
431
432                         // Encrypt password
433                         encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
434                 }
435
436                 // Set user name and flag
437                 user.setUserName(this.getUserName());
438                 user.setUserMustChangePassword(this.getUserMustChangePassword());
439
440                 // Is a password set?
441                 if (encryptedPassword != null) {
442                         // Set it as well
443                         user.setUserEncryptedPassword(encryptedPassword);
444                 }
445
446                 // Call EJB for updating user data
447                 User updatedUser = this.userBean.updateUserData(user);
448
449                 // Fire event
450                 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
451
452                 // Return to user list (for now)
453                 return "admin_list_user"; //NOI18N
454         }
455
456         @Override
457         public String getUserDeleteReason () {
458                 return this.userDeleteReason;
459         }
460
461         @Override
462         public void setUserDeleteReason (final String userDeleteReason) {
463                 this.userDeleteReason = userDeleteReason;
464         }
465
466         @Override
467         public String getUserLockReason () {
468                 return this.userLockReason;
469         }
470
471         @Override
472         public void setUserLockReason (final String userLockReason) {
473                 this.userLockReason = userLockReason;
474         }
475
476         @Override
477         public Boolean getUserMustChangePassword () {
478                 return this.userMustChangePassword;
479         }
480
481         @Override
482         public void setUserMustChangePassword (final Boolean userMustChangePassword) {
483                 this.userMustChangePassword = userMustChangePassword;
484         }
485
486         @Override
487         public String getUserName () {
488                 return this.userName;
489         }
490
491         @Override
492         public void setUserName (final String userName) {
493                 this.userName = userName;
494         }
495
496         @Override
497         public String getUserPassword () {
498                 return this.userPassword;
499         }
500
501         @Override
502         public void setUserPassword (final String userPassword) {
503                 this.userPassword = userPassword;
504         }
505
506         @Override
507         public String getUserPasswordRepeat () {
508                 return this.userPasswordRepeat;
509         }
510
511         @Override
512         public void setUserPasswordRepeat (final String userPasswordRepeat) {
513                 this.userPasswordRepeat = userPasswordRepeat;
514         }
515
516         @Override
517         public String lockUserAccount (final User user) {
518                 // Is the user instance valid and CONFIRMED?
519                 if (null == user) {
520                         // Throw NPE
521                         throw new NullPointerException("user is null"); //NOI18N
522                 } else if (user.getUserId() == null) {
523                         // Throw again
524                         throw new NullPointerException("user.userId is null"); //NOI18N
525                 } else if (user.getUserId() < 1) {
526                         // Invalid id number
527                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
528                 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
529                         // User account is locked
530                         throw new FacesException(new UserStatusLockedException(user));
531                 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
532                         // User account is locked
533                         throw new FaceletException(new UserStatusUnconfirmedException(user));
534                 } else if (this.getUserLockReason() == null) {
535                         // Throw NPE again
536                         throw new NullPointerException("this.userLockReason is null"); //NOI18N
537                 } else if (this.getUserLockReason().isEmpty()) {
538                         // Empty lock reason
539                         throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
540                 }
541
542                 // Init updated user instance
543                 User updatedUser;
544
545                 try {
546                         // Get base URL
547                         String baseUrl = FacesUtils.generateBaseUrl();
548
549                         // Call EJB to lock account
550                         updatedUser = this.adminUserBean.lockUserAccount(user, this.getUserLockReason(), baseUrl);
551                 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
552                         // Throw again
553                         throw new FaceletException(ex);
554                 }
555
556                 // Fire event
557                 this.userLockedEvent.fire(new AdminUserLockedEvent(updatedUser));
558
559                 // Clear bean
560                 this.clear();
561
562                 // Should go fine at this point, redirect to user profile
563                 return "admin_show_user"; //NOI18N
564         }
565
566         @Override
567         public String unlockUserAccount (final User user) {
568                 // Is the user instance valid and CONFIRMED?
569                 if (null == user) {
570                         // Throw NPE
571                         throw new NullPointerException("user is null"); //NOI18N
572                 } else if (user.getUserId() == null) {
573                         // Throw again
574                         throw new NullPointerException("user.userId is null"); //NOI18N
575                 } else if (user.getUserId() < 1) {
576                         // Invalid id number
577                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
578                 } else if (user.getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
579                         // User account is locked
580                         throw new FacesException(new UserStatusConfirmedException(user));
581                 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
582                         // User account is locked
583                         throw new FaceletException(new UserStatusUnconfirmedException(user));
584                 }
585
586                 // Init updated user instance
587                 User updatedUser;
588
589                 try {
590                         // Get base URL
591                         String baseUrl = FacesUtils.generateBaseUrl();
592
593                         // Call EJB to unlock account
594                         updatedUser = this.adminUserBean.unlockUserAccount(user, baseUrl);
595                 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
596                         // Throw again
597                         throw new FaceletException(ex);
598                 }
599
600                 // Fire event
601                 this.userUnlockedEvent.fire(new AdminUserUnlockedEvent(updatedUser));
602
603                 // Clear bean
604                 this.clear();
605
606                 // Should go fine at this point, redirect to user profile
607                 return "admin_show_user"; //NOI18N
608         }
609
610         /**
611          * Clears this bean
612          */
613         private void clear () {
614                 // Clear all data
615                 // - other data
616                 this.setUserName(null);
617                 this.setUserPassword(null);
618                 this.setUserPasswordRepeat(null);
619                 this.setUserMustChangePassword(null);
620         }
621
622         /**
623          * Checks if same password is entered and that they are not empty.
624          * <p>
625          * @return Whether the same password was entered
626          */
627         private boolean isSamePasswordEntered () {
628                 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
629         }
630
631 }