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