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