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