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