]> git.mxchange.org Git - pizzaservice-war.git/blob - src/java/org/mxchange/pizzaapplication/beans/user/PizzaAdminUserWebRequestBean.java
Continued a bit:
[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.annotation.PostConstruct;
22 import javax.enterprise.context.RequestScoped;
23 import javax.enterprise.event.Event;
24 import javax.enterprise.inject.Any;
25 import javax.faces.view.facelets.FaceletException;
26 import javax.inject.Inject;
27 import javax.inject.Named;
28 import javax.naming.Context;
29 import javax.naming.InitialContext;
30 import javax.naming.NamingException;
31 import org.mxchange.jcontacts.contact.Contact;
32 import org.mxchange.jusercore.container.login.UserLoginContainer;
33 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
34 import org.mxchange.jusercore.events.user.add.AdminUserAddedEvent;
35 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
36 import org.mxchange.jusercore.events.user.update.AdminUserDataUpdatedEvent;
37 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
38 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
39 import org.mxchange.jusercore.exceptions.UserPasswordRepeatMismatchException;
40 import org.mxchange.jusercore.model.user.LoginUser;
41 import org.mxchange.jusercore.model.user.User;
42 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
43 import org.mxchange.jusercore.model.user.UserUtils;
44 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
45 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
46 import org.mxchange.pizzaapplication.beans.contact.PizzaContactWebSessionController;
47 import org.mxchange.pizzaapplication.beans.helper.PizzaAdminWebRequestController;
48
49 /**
50  * Administrative user bean (controller)
51  * <p>
52  * @author Roland Haeder<roland@mxchange.org>
53  */
54 @Named ("adminUserController")
55 @RequestScoped
56 public class PizzaAdminUserWebRequestBean implements PizzaAdminUserWebRequestController {
57
58         /**
59          * Serial number
60          */
61         private static final long serialVersionUID = 542_145_347_916L;
62
63         /**
64          * An event fired when the administrator has added a new user
65          */
66         @Inject
67         @Any
68         private Event<AdminAddedUserEvent> addedUserEvent;
69
70         /**
71          * Admin helper instance
72          */
73         @Inject
74         private PizzaAdminWebRequestController adminHelper;
75
76         /**
77          * Regular contact controller
78          */
79         @Inject
80         private PizzaContactWebSessionController contactController;
81
82         /**
83          * An event fired when the administrator has updated a new user
84          */
85         @Inject
86         @Any
87         private Event<AdminUpdatedUserDataEvent> updatedUserDataEvent;
88
89         /**
90          * Remote user bean
91          */
92         private final UserSessionBeanRemote userBean;
93
94         /**
95          * Regular user controller
96          */
97         @Inject
98         private PizzaUserWebSessionController userController;
99
100         /**
101          * User name
102          */
103         private String userName;
104
105         /**
106          * User password (unencrypted from web form)
107          */
108         private String userPassword;
109
110         /**
111          * User password repeated (unencrypted from web form)
112          */
113         private String userPasswordRepeat;
114
115         /**
116          * Default constructor
117          */
118         public PizzaAdminUserWebRequestBean () {
119                 // Try it
120                 try {
121                         // Get initial context
122                         Context context = new InitialContext();
123
124                         // Try to lookup
125                         this.userBean = (UserSessionBeanRemote) context.lookup("java:global/PizzaService-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
126                 } catch (final NamingException e) {
127                         // Throw again
128                         throw new FaceletException(e);
129                 }
130         }
131
132         @Override
133         public String addUser () {
134                 // Create new user instance
135                 User user = new LoginUser();
136
137                 // As the form cannot validate the data (required="true"), check it here
138                 if (this.getUserName() == null) {
139                         // Throw NPE
140                         throw new NullPointerException("userName is null"); //NOI18N
141                 } else if (this.getUserName().isEmpty()) {
142                         // Is empty
143                         throw new IllegalArgumentException("userName is null"); //NOI18N
144                 } else if (this.adminHelper.getContact() == null) {
145                         // No contact instance set, so test required fields: gender, first name and family name
146                         if (this.contactController.getGender() == null) {
147                                 // Throw NPE again
148                                 throw new NullPointerException("contactController.gender is null"); //NOI18N
149                         } else if (this.contactController.getFirstName() == null) {
150                                 // ... and again
151                                 throw new NullPointerException("contactController.firstName is null"); //NOI18N //NOI18N
152                         } else if (this.contactController.getFirstName().isEmpty()) {
153                                 // ... and again
154                                 throw new IllegalArgumentException("contactController.firstName is empty");
155                         } else if (this.contactController.getFamilyName() == null) {
156                                 // ... and again
157                                 throw new NullPointerException("contactController.familyName is null"); //NOI18N
158                         } else if (this.contactController.getFamilyName().isEmpty()) {
159                                 // ... and again
160                                 throw new IllegalArgumentException("contactController.familyName is empty"); //NOI18N //NOI18N
161                         } else if (this.contactController.getEmailAddress() == null) {
162                                 // ... and again
163                                 throw new NullPointerException("contactController.emailAddress is null");
164                         } else if (this.contactController.getEmailAddress().isEmpty()) {
165                                 // ... and again
166                                 throw new IllegalArgumentException("contactController.emailAddress is empty"); //NOI18N //NOI18N
167                         } else if (this.contactController.getEmailAddressRepeat() == null) {
168                                 // ... and again
169                                 throw new NullPointerException("contactController.emailAddressRepeat is null");
170                         } else if (this.contactController.getEmailAddressRepeat().isEmpty()) {
171                                 // ... and again
172                                 throw new IllegalArgumentException("contactController.emailAddressRepeat is empty"); //NOI18N //NOI18N
173                         } else if (!Objects.equals(this.contactController.getEmailAddress(), this.contactController.getEmailAddressRepeat())) {
174                                 // Is not same email address
175                                 throw new IllegalArgumentException("Both entered email addresses don't match.");
176                         }
177                 }
178
179                 // Set user name, CONFIRMED and INVISIBLE
180                 user.setUserName(this.getUserName());
181                 user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
182                 user.setUserProfileMode(ProfileMode.INVISIBLE);
183
184                 // Init instance
185                 Contact contact;
186
187                 // Is a contact instance in helper set?
188                 if (this.adminHelper.getContact() instanceof Contact) {
189                         // Then use it for contact linking
190                         contact = this.adminHelper.getContact();
191                 } else {
192                         // Create contact instance
193                         contact = this.contactController.createContactInstance();
194                 }
195
196                 // Set contact in user
197                 user.setUserContact(contact);
198
199                 // Init variable for password
200                 String password = null;
201
202                 // Is the user name or email address used already?
203                 // @TODO Add password length check
204                 if (this.userController.isUserNameRegistered(user)) {
205                         // User name is already used
206                         throw new FaceletException(new UserNameAlreadyRegisteredException(user));
207                 } else if ((this.adminHelper.getContact() == null) && (this.contactController.isEmailAddressRegistered(user.getUserContact()))) {
208                         // Email address is already used
209                         throw new FaceletException(new EmailAddressAlreadyRegisteredException(user));
210                 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
211                         // Empty password entered, then generate one
212                         password = UserUtils.createRandomPassword(PizzaUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
213                 } else if (!this.isSamePasswordEntered()) {
214                         // Both passwords don't match
215                         throw new FaceletException(new UserPasswordRepeatMismatchException(user));
216                 } else {
217                         // Both match, so get it from this bean
218                         password = this.getUserPassword();
219                 }
220
221                 // The password should not be null and at least 5 characters long
222                 assert (password != null) : "password is null"; //NOI18N
223                 assert (password.length() >= PizzaUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
224
225                 // Encrypt password and set it
226                 user.setUserEncryptedPassword(UserUtils.encryptPassword(password));
227
228                 // Init updated user instance
229                 User updatedUser = null;
230
231                 try {
232                         // Now, that all is set, call EJB
233                         if (this.adminHelper.getContact() instanceof Contact) {
234                                 // Link contact with this user
235                                 updatedUser = this.userBean.linkUser(user);
236
237                                 // Remove contact instance
238                                 this.adminHelper.setContact(null);
239                         } else {
240                                 // Add new contact
241                                 updatedUser = this.userBean.addUser(user);
242                         }
243                 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
244                         // Throw again
245                         throw new FaceletException(ex);
246                 }
247
248                 // Fire event
249                 this.addedUserEvent.fire(new AdminUserAddedEvent(updatedUser));
250
251                 // Clear this bean
252                 this.clear();
253
254                 // Return to user list (for now)
255                 return "admin_list_user"; //NOI18N
256         }
257
258         @Override
259         public String editUserData () {
260                 // Get user instance
261                 User user = this.adminHelper.getUser();
262
263                 // Null password means not setting it
264                 String encryptedPassword = null;
265
266                 // Check if user instance is in helper and valid
267                 if (null == user) {
268                         // Throw NPE
269                         throw new NullPointerException("adminHelper.user is null"); //NOI18N
270                 } else if (user.getUserId() == null) {
271                         // Throw NPE again
272                         throw new NullPointerException("adminHelper.user.userId is null"); //NOI18N //NOI18N
273                 } else if (user.getUserId() < 1) {
274                         // Invalid id
275                         throw new IllegalStateException(MessageFormat.format("adminHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N //NOI18N
276                 } else if (this.getUserName() == null) {
277                         // Not all required fields are set
278                         throw new NullPointerException("this.userName is null"); //NOI18N
279                 } else if (this.getUserName().isEmpty()) {
280                         // Not all required fields are set
281                         throw new IllegalArgumentException("this.userName is empty"); //NOI18N
282                 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
283                         // Not same password entered
284                         this.setUserPassword(null);
285                         this.setUserPasswordRepeat(null);
286
287                         // Throw exception
288                         throw new FaceletException("Not same password entered"); //NOI18N
289                 } else if (this.userBean.ifUserNameExists(this.getUserName())) {
290                         // User name already exists
291                         throw new FaceletException(new UserNameAlreadyRegisteredException(this.getUserName()));
292                 } else if (this.isSamePasswordEntered()) {
293                         // Same password entered, create container
294                         if (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword()))) {
295                                 // Same password entered
296                                 throw new FaceletException("Same password as stored entered."); //NOI18N
297                         }
298
299                         // Encrypt password
300                         encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
301                 }
302
303                 // Set user name
304                 user.setUserName(this.getUserName());
305
306                 // Is a password set?
307                 if (encryptedPassword != null) {
308                         // Set it as well
309                         user.setUserEncryptedPassword(encryptedPassword);
310                 }
311
312                 // Call EJB for updating user data
313                 User updatedUser = this.userBean.updateUserData(user);
314
315                 // Update list
316                 this.userController.updateList(updatedUser);
317
318                 // Fire event
319                 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
320
321                 // Return to user list (for now)
322                 return "admin_list_user"; //NOI18N
323         }
324
325         @Override
326         public String getUserName () {
327                 return this.userName;
328         }
329
330         @Override
331         public void setUserName (final String userName) {
332                 this.userName = userName;
333         }
334
335         @Override
336         public String getUserPassword () {
337                 return this.userPassword;
338         }
339
340         @Override
341         public void setUserPassword (final String userPassword) {
342                 this.userPassword = userPassword;
343         }
344
345         @Override
346         public String getUserPasswordRepeat () {
347                 return this.userPasswordRepeat;
348         }
349
350         @Override
351         public void setUserPasswordRepeat (final String userPasswordRepeat) {
352                 this.userPasswordRepeat = userPasswordRepeat;
353         }
354
355         /**
356          * Post-initialization of this class
357          */
358         @PostConstruct
359         public void init () {
360         }
361
362         /**
363          * Clears this bean
364          */
365         private void clear () {
366                 // Clear all fields
367                 this.setUserName(null);
368                 this.setUserPassword(null);
369                 this.setUserPasswordRepeat(null);
370         }
371
372         /**
373          * Checks if same password is entered and that they are not empty.
374          * <p>
375          * @return Whether the same password was entered
376          */
377         private boolean isSamePasswordEntered () {
378                 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
379         }
380
381 }