]> git.mxchange.org Git - pizzaservice-war.git/blob - src/java/org/mxchange/pizzaapplication/beans/user/PizzaAdminUserWebRequestBean.java
Please cherry-pick:
[pizzaservice-war.git] / src / java / org / mxchange / pizzaapplication / beans / user / PizzaAdminUserWebRequestBean.java
1 /*
2  * Copyright (C) 2016 Roland Häder
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.pizzaapplication.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.jusercore.container.login.UserLoginContainer;
35 import org.mxchange.jusercore.events.registration.ObservableUserRegisteredEvent;
36 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
37 import org.mxchange.jusercore.events.user.add.ObservableAdminAddedUserEvent;
38 import org.mxchange.jusercore.events.user.linked.AdminLinkedUserEvent;
39 import org.mxchange.jusercore.events.user.linked.ObservableAdminLinkedUserEvent;
40 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
41 import org.mxchange.jusercore.events.user.update.ObservableAdminUpdatedUserDataEvent;
42 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
43 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
44 import org.mxchange.jusercore.exceptions.UserNotFoundException;
45 import org.mxchange.jusercore.exceptions.UserPasswordRepeatMismatchException;
46 import org.mxchange.jusercore.exceptions.UserStatusConfirmedException;
47 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
48 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
49 import org.mxchange.jusercore.model.user.AdminUserSessionBeanRemote;
50 import org.mxchange.jusercore.model.user.LoginUser;
51 import org.mxchange.jusercore.model.user.User;
52 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
53 import org.mxchange.jusercore.model.user.UserUtils;
54 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
55 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
56 import org.mxchange.pizzaapplication.beans.BasePizzaController;
57 import org.mxchange.pizzaapplication.beans.contact.PizzaAdminContactWebRequestController;
58 import org.mxchange.pizzaapplication.beans.contact.PizzaContactWebSessionController;
59 import org.mxchange.pizzaapplication.beans.helper.PizzaWebRequestController;
60
61 /**
62  * Administrative user bean (controller)
63  * <p>
64  * @author Roland Häder<roland@mxchange.org>
65  */
66 @Named ("adminUserController")
67 @RequestScoped
68 public class PizzaAdminUserWebRequestBean extends BasePizzaController implements PizzaAdminUserWebRequestController {
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<ObservableAdminAddedUserEvent> addedUserEvent;
81
82         /**
83          * Regular contact controller
84          */
85         @Inject
86         private PizzaAdminContactWebRequestController adminContactController;
87
88         /**
89          * Administrative user EJB
90          */
91         private final AdminUserSessionBeanRemote adminUserBean;
92
93         /**
94          * Bean helper instance
95          */
96         @Inject
97         private PizzaWebRequestController beanHelper;
98
99         /**
100          * Regular contact controller
101          */
102         @Inject
103         private PizzaContactWebSessionController contactController;
104
105         /**
106          * An event fired when the administrator has updated a new user
107          */
108         @Inject
109         @Any
110         private Event<ObservableAdminUpdatedUserDataEvent> updatedUserDataEvent;
111
112         /**
113          * General user EJB
114          */
115         private final UserSessionBeanRemote userBean;
116
117         /**
118          * Regular user controller
119          */
120         @Inject
121         private PizzaUserWebSessionController 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<ObservableAdminLinkedUserEvent> 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 PizzaAdminUserWebRequestBean () {
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/pizzaservice-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
167                         this.adminUserBean = (AdminUserSessionBeanRemote) context.lookup("java:global/pizzaservice-ejb/adminUser!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                 // Create new user instance
177                 User user = new LoginUser();
178
179                 // As the form cannot validate the data (required="true"), check it here
180                 if (this.getUserName() == null) {
181                         // Throw NPE
182                         throw new NullPointerException("userName is null"); //NOI18N
183                 } else if (this.getUserName().isEmpty()) {
184                         // Is empty
185                         throw new IllegalArgumentException("userName is null"); //NOI18N
186                 } else if (this.beanHelper.getContact() == null) {
187                         // No contact instance set, so test required fields: gender, first name and family name
188                         if (this.contactController.getGender() == null) {
189                                 // Throw NPE again
190                                 throw new NullPointerException("contactController.gender is null"); //NOI18N
191                         } else if (this.contactController.getFirstName() == null) {
192                                 // ... and again
193                                 throw new NullPointerException("contactController.firstName is null"); //NOI18N //NOI18N
194                         } else if (this.contactController.getFirstName().isEmpty()) {
195                                 // ... and again
196                                 throw new IllegalArgumentException("contactController.firstName is empty"); //NOI18N
197                         } else if (this.adminContactController.getFamilyName() == null) {
198                                 // ... and again
199                                 throw new NullPointerException("contactController.familyName is null"); //NOI18N
200                         } else if (this.contactController.getFamilyName().isEmpty()) {
201                                 // ... and again
202                                 throw new IllegalArgumentException("contactController.familyName is empty"); //NOI18N //NOI18N
203                         } else if (this.contactController.getEmailAddress() == null) {
204                                 // ... and again
205                                 throw new NullPointerException("contactController.emailAddress is null"); //NOI18N
206                         } else if (this.adminContactController.getEmailAddress().isEmpty()) {
207                                 // ... and again
208                                 throw new IllegalArgumentException("contactController.emailAddress is empty"); //NOI18N //NOI18N
209                         } else if (this.contactController.getEmailAddressRepeat() == null) {
210                                 // ... and again
211                                 throw new NullPointerException("contactController.emailAddressRepeat is null");
212                         } else if (this.contactController.getEmailAddressRepeat().isEmpty()) {
213                                 // ... and again
214                                 throw new IllegalArgumentException("contactController.emailAddressRepeat is empty"); //NOI18N //NOI18N
215                         } else if (!Objects.equals(this.contactController.getEmailAddress(), this.contactController.getEmailAddressRepeat())) {
216                                 // Is not same email address
217                                 throw new IllegalArgumentException("Both entered email addresses don't match.");
218                         }
219                 }
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(PizzaUserWebSessionController.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() >= PizzaUserWebSessionController.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 AdminLinkedUserEvent(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 AdminAddedUserEvent(updatedUser));
287                         }
288                 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
289                         // Throw again
290                         throw new FaceletException(ex);
291                 }
292
293                 // Clear this bean
294                 this.clear();
295
296                 // Return to user list (for now)
297                 return "admin_list_user"; //NOI18N
298         }
299
300         @Override
301         public void afterRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
302                 // event should not be null
303                 if (null == event) {
304                         // Throw NPE
305                         throw new NullPointerException("event is null"); //NOI18N
306                 } else if (event.getRegisteredUser() == null) {
307                         // Throw NPE again
308                         throw new NullPointerException("event.user is null"); //NOI18N
309                 } else if (event.getRegisteredUser().getUserId() == null) {
310                         // userId is null
311                         throw new NullPointerException("event.user.userId is null"); //NOI18N
312                 } else if (event.getRegisteredUser().getUserId() < 1) {
313                         // Not avalid id
314                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
315                 }
316
317                 // Get user instance
318                 User registeredUser = event.getRegisteredUser();
319
320                 // @TODO Nothing to do with the user here?
321
322                 // Clear all data
323                 this.clear();
324         }
325
326         @Override
327         public String editUserData () {
328                 // Get user instance
329                 User user = this.beanHelper.getUser();
330
331                 // Null password means not setting it
332                 String encryptedPassword = null;
333
334                 // Check if user instance is in helper and valid
335                 if (null == user) {
336                         // Throw NPE
337                         throw new NullPointerException("beanHelper.user is null"); //NOI18N
338                 } else if (user.getUserId() == null) {
339                         // Throw NPE again
340                         throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N //NOI18N
341                 } else if (user.getUserId() < 1) {
342                         // Invalid id
343                         throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N //NOI18N
344                 } else if (this.getUserName() == null) {
345                         // Not all required fields are set
346                         throw new NullPointerException("this.userName is null"); //NOI18N
347                 } else if (this.getUserName().isEmpty()) {
348                         // Not all required fields are set
349                         throw new IllegalArgumentException("this.userName is empty"); //NOI18N
350                 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
351                         // Not same password entered
352                         this.setUserPassword(null);
353                         this.setUserPasswordRepeat(null);
354
355                         // Throw exception
356                         throw new FaceletException("Not same password entered"); //NOI18N
357                 } else if (this.userBean.ifUserNameExists(this.getUserName())) {
358                         // User name already exists
359                         throw new FaceletException(new UserNameAlreadyRegisteredException(this.getUserName()));
360                 } else if (this.isSamePasswordEntered()) {
361                         // Same password entered, create container
362                         if (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword()))) {
363                                 // Same password entered
364                                 throw new FaceletException("Same password as stored entered."); //NOI18N
365                         }
366
367                         // Encrypt password
368                         encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
369                 }
370
371                 // Set user name and flag
372                 user.setUserName(this.getUserName());
373                 user.setUserMustChangePassword(this.getUserMustChangePassword());
374
375                 // Is a password set?
376                 if (encryptedPassword != null) {
377                         // Set it as well
378                         user.setUserEncryptedPassword(encryptedPassword);
379                 }
380
381                 // Call EJB for updating user data
382                 User updatedUser = this.userBean.updateUserData(user);
383
384                 // Fire event
385                 this.updatedUserDataEvent.fire(new AdminUpdatedUserDataEvent(updatedUser));
386
387                 // Return to user list (for now)
388                 return "admin_list_user"; //NOI18N
389         }
390
391         @Override
392         public String getUserLockReason () {
393                 return this.userLockReason;
394         }
395
396         @Override
397         public void setUserLockReason (final String userLockReason) {
398                 this.userLockReason = userLockReason;
399         }
400
401         @Override
402         public Boolean getUserMustChangePassword () {
403                 return this.userMustChangePassword;
404         }
405
406         @Override
407         public void setUserMustChangePassword (final Boolean userMustChangePassword) {
408                 this.userMustChangePassword = userMustChangePassword;
409         }
410
411         @Override
412         public String getUserName () {
413                 return this.userName;
414         }
415
416         @Override
417         public void setUserName (final String userName) {
418                 this.userName = userName;
419         }
420
421         @Override
422         public String getUserPassword () {
423                 return this.userPassword;
424         }
425
426         @Override
427         public void setUserPassword (final String userPassword) {
428                 this.userPassword = userPassword;
429         }
430
431         @Override
432         public String getUserPasswordRepeat () {
433                 return this.userPasswordRepeat;
434         }
435
436         @Override
437         public void setUserPasswordRepeat (final String userPasswordRepeat) {
438                 this.userPasswordRepeat = userPasswordRepeat;
439         }
440
441         @Override
442         public String lockUserAccount (final User user) {
443                 // Is the user instance valid and CONFIRMED?
444                 if (null == user) {
445                         // Throw NPE
446                         throw new NullPointerException("user is null"); //NOI18N
447                 } else if (user.getUserId() == null) {
448                         // Throw again
449                         throw new NullPointerException("user.userId is null"); //NOI18N
450                 } else if (user.getUserId() < 1) {
451                         // Invalid id number
452                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
453                 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
454                         // User account is locked
455                         throw new FacesException(new UserStatusLockedException(user));
456                 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
457                         // User account is locked
458                         throw new FaceletException(new UserStatusUnconfirmedException(user));
459                 } else if (this.getUserLockReason() == null) {
460                         // Throw NPE again
461                         throw new NullPointerException("this.userLockReason is null"); //NOI18N
462                 } else if (this.getUserLockReason().isEmpty()) {
463                         // Empty lock reason
464                         throw new IllegalArgumentException("this.userLockReason is empty"); //NOI18N
465                 }
466
467                 try {
468                         // Get base URL
469                         String baseUrl = FacesUtils.generateBaseUrl();
470
471                         // Call EJB to lock account
472                         this.adminUserBean.lockUserAccount(user, this.getUserLockReason(), baseUrl);
473                 } catch (final UserStatusLockedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
474                         // Throw again
475                         throw new FaceletException(ex);
476                 }
477
478                 // Should go fine at this point, redirect to user profile
479                 return "admin_show_user?faces-redirect=true&includeViewParams=true"; //NOI18N
480         }
481
482         @Override
483         public String unlockUserAccount (final User user) {
484                 // Is the user instance valid and CONFIRMED?
485                 if (null == user) {
486                         // Throw NPE
487                         throw new NullPointerException("user is null"); //NOI18N
488                 } else if (user.getUserId() == null) {
489                         // Throw again
490                         throw new NullPointerException("user.userId is null"); //NOI18N
491                 } else if (user.getUserId() < 1) {
492                         // Invalid id number
493                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
494                 } else if (user.getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
495                         // User account is locked
496                         throw new FacesException(new UserStatusConfirmedException(user));
497                 } else if (user.getUserAccountStatus() == UserAccountStatus.UNCONFIRMED) {
498                         // User account is locked
499                         throw new FaceletException(new UserStatusUnconfirmedException(user));
500                 }
501
502                 try {
503                         // Get base URL
504                         String baseUrl = FacesUtils.generateBaseUrl();
505
506                         // Call EJB to unlock account
507                         this.adminUserBean.unlockUserAccount(user, baseUrl);
508                 } catch (final UserStatusConfirmedException | UserStatusUnconfirmedException | UserNotFoundException ex) {
509                         // Throw again
510                         throw new FaceletException(ex);
511                 }
512
513                 // Should go fine at this point, redirect to user profile
514                 return "admin_show_user?faces-redirect=true&includeViewParams=true"; //NOI18N
515         }
516
517         /**
518          * Clears this bean
519          */
520         private void clear () {
521                 // Clear all data
522                 // - other data
523                 this.setUserName(null);
524                 this.setUserPassword(null);
525                 this.setUserPasswordRepeat(null);
526                 this.setUserMustChangePassword(null);
527         }
528
529         /**
530          * Checks if same password is entered and that they are not empty.
531          * <p>
532          * @return Whether the same password was entered
533          */
534         private boolean isSamePasswordEntered () {
535                 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
536         }
537
538 }