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