]> git.mxchange.org Git - jjobs-war.git/blob - src/java/org/mxchange/jjobs/beans/user/JobsAdminUserWebRequestBean.java
removed double //NOI18N (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.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
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 afterRegistrationEvent (@Observes final UserRegisteredEvent event) {
314                 // Trace message
315                 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterRegistration: event={0} - CALLED!", event)); //NOI18N
316
317                 // event should not be null
318                 if (null == event) {
319                         // Throw NPE
320                         throw new NullPointerException("event is null"); //NOI18N
321                 } else if (event.getRegisteredUser() == null) {
322                         // Throw NPE again
323                         throw new NullPointerException("event.user is null"); //NOI18N
324                 } else if (event.getRegisteredUser().getUserId() == null) {
325                         // userId is null
326                         throw new NullPointerException("event.user.userId is null"); //NOI18N
327                 } else if (event.getRegisteredUser().getUserId() < 1) {
328                         // Not avalid id
329                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
330                 }
331
332                 // Get user instance
333                 User registeredUser = event.getRegisteredUser();
334
335                 // Debug message
336                 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterRegistration: registeredUser={0}", registeredUser)); //NOI18N
337                 // Clear all data
338                 this.clear();
339
340                 // Trace message
341                 //* NOISY-DEBUG: */ System.out.println("UserWebBean:afterRegistration: EXIT!"); //NOI18N
342         }
343
344         @Override
345         public String editUserData () {
346                 // Get user instance
347                 User user = this.beanHelper.getUser();
348
349                 // Null password means not setting it
350                 String encryptedPassword = null;
351
352                 // Check if user instance is in helper and valid
353                 if (null == user) {
354                         // Throw NPE
355                         throw new NullPointerException("beanHelper.user is null"); //NOI18N
356                 } else if (user.getUserId() == null) {
357                         // Throw NPE again
358                         throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N
359                 } else if (user.getUserId() < 1) {
360                         // Invalid id
361                         throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N
362                 } else if (this.getUserName() == null) {
363                         // Not all required fields are set
364                         throw new NullPointerException("this.userName is null"); //NOI18N
365                 } else if (this.getUserName().isEmpty()) {
366                         // Not all required fields are set
367                         throw new IllegalArgumentException("this.userName is empty"); //NOI18N
368                 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
369                         // Not same password entered
370                         this.setUserPassword(null);
371                         this.setUserPasswordRepeat(null);
372
373                         // Throw exception
374                         throw new FaceletException("Not same password entered"); //NOI18N
375                 } else if (this.userBean.ifUserNameExists(this.getUserName())) {
376                         // User name already exists
377                         throw new FaceletException(new UserNameAlreadyRegisteredException(this.getUserName()));
378                 } else if (this.isSamePasswordEntered()) {
379                         // Same password entered, create container
380                         if (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword()))) {
381                                 // Same password entered
382                                 throw new FaceletException("Same password as stored entered."); //NOI18N
383                         }
384
385                         // Encrypt password
386                         encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
387                 }
388
389                 // Set user name and flag
390                 user.setUserName(this.getUserName());
391                 user.setUserMustChangePassword(this.getUserMustChangePassword());
392
393                 // Is a password set?
394                 if (encryptedPassword != null) {
395                         // Set it as well
396                         user.setUserEncryptedPassword(encryptedPassword);
397                 }
398
399                 // Call EJB for updating user data
400                 User updatedUser = this.userBean.updateUserData(user);
401
402                 // Fire event
403                 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
404
405                 // Return to user list (for now)
406                 return "admin_list_user"; //NOI18N
407         }
408
409         @Override
410         public String getUserLockReason () {
411                 return this.userLockReason;
412         }
413
414         @Override
415         public void setUserLockReason (final String userLockReason) {
416                 this.userLockReason = userLockReason;
417         }
418
419         @Override
420         public Boolean getUserMustChangePassword () {
421                 return this.userMustChangePassword;
422         }
423
424         @Override
425         public void setUserMustChangePassword (final Boolean userMustChangePassword) {
426                 this.userMustChangePassword = userMustChangePassword;
427         }
428
429         @Override
430         public String getUserName () {
431                 return this.userName;
432         }
433
434         @Override
435         public void setUserName (final String userName) {
436                 this.userName = userName;
437         }
438
439         @Override
440         public String getUserPassword () {
441                 return this.userPassword;
442         }
443
444         @Override
445         public void setUserPassword (final String userPassword) {
446                 this.userPassword = userPassword;
447         }
448
449         @Override
450         public String getUserPasswordRepeat () {
451                 return this.userPasswordRepeat;
452         }
453
454         @Override
455         public void setUserPasswordRepeat (final String userPasswordRepeat) {
456                 this.userPasswordRepeat = userPasswordRepeat;
457         }
458
459         @Override
460         public String lockUserAccount (final User user) {
461                 // Is the user instance valid and CONFIRMED?
462                 if (null == user) {
463                         // Throw NPE
464                         throw new NullPointerException("user is null"); //NOI18N
465                 } else if (user.getUserId() == null) {
466                         // Throw again
467                         throw new NullPointerException("user.userId is null"); //NOI18N
468                 } else if (user.getUserId() < 1) {
469                         // Invalid id number
470                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
471                 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
472                         // User account is locked
473                         throw new FacesException(new UserStatusLockedException(user));
474                 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
475                         // User account is locked
476                         throw new FaceletException(new UserStatusUnconfirmedException(user));
477                 } else if (this.getUserLockReason() == null) {
478                         // Throw NPE again
479                         throw new NullPointerException("this.userLockReason is null"); //NOI18N
480                 } else if (this.getUserLockReason().isEmpty()) {
481                         // Empty lock reason
482                         throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
483                 }
484
485                 // Init updated user instance
486                 User updatedUser;
487
488                 try {
489                         // Get base URL
490                         String baseUrl = FacesUtils.generateBaseUrl();
491
492                         // Call EJB to lock account
493                         updatedUser = this.adminUserBean.lockUserAccount(user, this.getUserLockReason(), baseUrl);
494                 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
495                         // Throw again
496                         throw new FaceletException(ex);
497                 }
498
499                 // Fire event
500                 this.userLockedEvent.fire(new AdminUserLockedEvent(updatedUser));
501
502                 // Clear bean
503                 this.clear();
504
505                 // Should go fine at this point, redirect to user profile
506                 return "admin_show_user?faces-redirect=true&includeViewParams=true"; //NOI18N
507         }
508
509         @Override
510         public String unlockUserAccount (final User user) {
511                 // Is the user instance valid and CONFIRMED?
512                 if (null == user) {
513                         // Throw NPE
514                         throw new NullPointerException("user is null"); //NOI18N
515                 } else if (user.getUserId() == null) {
516                         // Throw again
517                         throw new NullPointerException("user.userId is null"); //NOI18N
518                 } else if (user.getUserId() < 1) {
519                         // Invalid id number
520                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
521                 } else if (user.getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
522                         // User account is locked
523                         throw new FacesException(new UserStatusConfirmedException(user));
524                 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
525                         // User account is locked
526                         throw new FaceletException(new UserStatusUnconfirmedException(user));
527                 }
528
529                 // Init updated user instance
530                 User updatedUser;
531
532                 try {
533                         // Get base URL
534                         String baseUrl = FacesUtils.generateBaseUrl();
535
536                         // Call EJB to unlock account
537                         updatedUser = this.adminUserBean.unlockUserAccount(user, baseUrl);
538                 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
539                         // Throw again
540                         throw new FaceletException(ex);
541                 }
542
543                 // Fire event
544                 this.userUnlockedEvent.fire(new AdminUserUnlockedEvent(updatedUser));
545
546                 // Clear bean
547                 this.clear();
548
549                 // Should go fine at this point, redirect to user profile
550                 return "admin_show_user?faces-redirect=true&includeViewParams=true"; //NOI18N
551         }
552
553         /**
554          * Clears this bean
555          */
556         private void clear () {
557                 // Clear all data
558                 // - other data
559                 this.setUserName(null);
560                 this.setUserPassword(null);
561                 this.setUserPasswordRepeat(null);
562                 this.setUserMustChangePassword(null);
563         }
564
565         /**
566          * Checks if same password is entered and that they are not empty.
567          * <p>
568          * @return Whether the same password was entered
569          */
570         private boolean isSamePasswordEntered () {
571                 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
572         }
573
574 }