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