]> git.mxchange.org Git - jjobs-war.git/blob - src/java/org/mxchange/jjobs/beans/user/JobsAdminUserWebRequestBean.java
Continued a bit: (please cherry-pick)
[jjobs-war.git] / src / java / org / mxchange / jjobs / beans / user / JobsAdminUserWebRequestBean.java
1 /*
2  * Copyright (C) 2016 Roland Haeder
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU Affero General Public License as
6  * published by the Free Software Foundation, either version 3 of the
7  * License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU Affero General Public License for more details.
13  *
14  * You should have received a copy of the GNU Affero General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17 package org.mxchange.jjobs.beans.user;
18
19 import java.text.MessageFormat;
20 import java.util.Objects;
21 import javax.annotation.PostConstruct;
22 import javax.enterprise.context.RequestScoped;
23 import javax.enterprise.event.Event;
24 import javax.enterprise.event.Observes;
25 import javax.enterprise.inject.Any;
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.jjobs.beans.BaseJobsController;
34 import org.mxchange.jjobs.beans.contact.JobsContactWebSessionController;
35 import org.mxchange.jjobs.beans.login.JobsUserLoginWebSessionController;
36 import org.mxchange.jusercore.container.login.UserLoginContainer;
37 import org.mxchange.jusercore.events.registration.UserRegisteredEvent;
38 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
39 import org.mxchange.jusercore.events.user.add.AdminUserAddedEvent;
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.UserPasswordRepeatMismatchException;
45 import org.mxchange.jusercore.model.user.LoginUser;
46 import org.mxchange.jusercore.model.user.User;
47 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
48 import org.mxchange.jusercore.model.user.UserUtils;
49 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
50 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
51 import org.mxchange.jjobs.beans.helper.JobsWebRequestController;
52
53 /**
54  * A user bean (controller)
55  * <p>
56  * @author Roland Haeder<roland@mxchange.org>
57  */
58 @Named ("adminUserController")
59 @RequestScoped
60 public class JobsAdminUserWebRequestBean extends BaseJobsController implements JobsAdminUserWebRequestController {
61
62         /**
63          * Serial number
64          */
65         private static final long serialVersionUID = 542_145_347_916L;
66
67         /**
68          * An event fired when the administrator has added a new user
69          */
70         @Inject
71         @Any
72         private Event<AdminAddedUserEvent> addedUserEvent;
73
74         /**
75          * Bean helper instance
76          */
77         @Inject
78         private JobsWebRequestController beanHelper;
79
80         /**
81          * Regular contact controller
82          */
83         @Inject
84         private JobsContactWebSessionController contactController;
85
86         /**
87          * An event fired when the administrator has updated a new user
88          */
89         @Inject
90         @Any
91         private Event<AdminUpdatedUserDataEvent> updatedUserDataEvent;
92
93         /**
94          * Remote user bean
95          */
96         private final UserSessionBeanRemote userBean;
97
98         /**
99          * Regular user controller
100          */
101         @Inject
102         private JobsUserWebSessionController userController;
103
104         /**
105          * Flag whether user must change password after login
106          */
107         private Boolean userMustChangePassword;
108
109         /**
110          * User name
111          */
112         private String userName;
113
114         /**
115          * User password (unencrypted from web form)
116          */
117         private String userPassword;
118
119         /**
120          * User password repeated (unencrypted from web form)
121          */
122         private String userPasswordRepeat;
123
124         /**
125          * Default constructor
126          */
127         public JobsAdminUserWebRequestBean () {
128                 // Try it
129                 try {
130                         // Get initial context
131                         Context context = new InitialContext();
132
133                         // Try to lookup
134                         this.userBean = (UserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
135                 } catch (final NamingException e) {
136                         // Throw again
137                         throw new FaceletException(e);
138                 }
139         }
140
141         @Override
142         public String addUser () {
143                 // As the form cannot validate the data (required="true"), check it here
144                 if (this.getUserName() == null) {
145                         // Throw NPE
146                         throw new NullPointerException("userName is null"); //NOI18N
147                 } else if (this.getUserName().isEmpty()) {
148                         // Is empty
149                         throw new IllegalArgumentException("userName is null"); //NOI18N
150                 } else if (this.beanHelper.getContact() == null) {
151                         // No contact instance set, so test required fields: gender, first name and family name
152                         if (this.contactController.getGender() == null) {
153                                 // Throw NPE again
154                                 throw new NullPointerException("contactController.gender is null"); //NOI18N
155                         } else if (this.contactController.getFirstName() == null) {
156                                 // ... and again
157                                 throw new NullPointerException("contactController.firstName is null"); //NOI18N //NOI18N
158                         } else if (this.contactController.getFirstName().isEmpty()) {
159                                 // ... and again
160                                 throw new IllegalArgumentException("contactController.firstName is empty");
161                         } else if (this.contactController.getFamilyName() == null) {
162                                 // ... and again
163                                 throw new NullPointerException("contactController.familyName is null"); //NOI18N
164                         } else if (this.contactController.getFamilyName().isEmpty()) {
165                                 // ... and again
166                                 throw new IllegalArgumentException("contactController.familyName is empty"); //NOI18N //NOI18N
167                         } else if (this.contactController.getEmailAddress() == null) {
168                                 // ... and again
169                                 throw new NullPointerException("contactController.emailAddress is null");
170                         } else if (this.contactController.getEmailAddress().isEmpty()) {
171                                 // ... and again
172                                 throw new IllegalArgumentException("contactController.emailAddress is empty"); //NOI18N //NOI18N
173                         } else if (this.contactController.getEmailAddressRepeat() == null) {
174                                 // ... and again
175                                 throw new NullPointerException("contactController.emailAddressRepeat is null");
176                         } else if (this.contactController.getEmailAddressRepeat().isEmpty()) {
177                                 // ... and again
178                                 throw new IllegalArgumentException("contactController.emailAddressRepeat is empty"); //NOI18N //NOI18N
179                         } else if (!Objects.equals(this.contactController.getEmailAddress(), this.contactController.getEmailAddressRepeat())) {
180                                 // Is not same email address
181                                 throw new IllegalArgumentException("Both entered email addresses don't match.");
182                         }
183                 }
184
185                 // Create new user instance
186                 User user = new LoginUser();
187
188                 // Set user name, CONFIRMED and INVISIBLE
189                 user.setUserName(this.getUserName());
190                 user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
191                 user.setUserProfileMode(ProfileMode.INVISIBLE);
192
193                 // Init instance
194                 Contact contact;
195
196                 // Is a contact instance in helper set?
197                 if (this.beanHelper.getContact() instanceof Contact) {
198                         // Then use it for contact linking
199                         contact = this.beanHelper.getContact();
200                 } else {
201                         // Create contact instance
202                         contact = this.contactController.createContactInstance();
203                 }
204
205                 // Set contact in user
206                 user.setUserContact(contact);
207
208                 // Init variable for password
209                 String password = null;
210
211                 // Is the user name or email address used already?
212                 // @TODO Add password length check
213                 if (this.userController.isUserNameRegistered(user)) {
214                         // User name is already used
215                         throw new FaceletException(new UserNameAlreadyRegisteredException(user));
216                 } else if ((this.beanHelper.getContact() == null) && (this.contactController.isEmailAddressRegistered(user.getUserContact()))) {
217                         // Email address is already used
218                         throw new FaceletException(new EmailAddressAlreadyRegisteredException(user));
219                 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
220                         // Empty password entered, then generate one
221                         password = UserUtils.createRandomPassword(JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
222                 } else if (!this.isSamePasswordEntered()) {
223                         // Both passwords don't match
224                         throw new FaceletException(new UserPasswordRepeatMismatchException(user));
225                 } else {
226                         // Both match, so get it from this bean
227                         password = this.getUserPassword();
228                 }
229
230                 // The password should not be null and at least 5 characters long
231                 assert (password != null) : "password is null"; //NOI18N
232                 assert (password.length() >= JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
233
234                 // Encrypt password and set it
235                 user.setUserEncryptedPassword(UserUtils.encryptPassword(password));
236
237                 // Init updated user instance
238                 User updatedUser = null;
239
240                 try {
241                         // Now, that all is set, call EJB
242                         if (this.beanHelper.getContact() instanceof Contact) {
243                                 // Link contact with this user
244                                 updatedUser = this.userBean.linkUser(user);
245
246                                 // Remove contact instance
247                                 this.beanHelper.setContact(null);
248                         } else {
249                                 // Add new contact
250                                 updatedUser = this.userBean.addUser(user);
251                         }
252                 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
253                         // Throw again
254                         throw new FaceletException(ex);
255                 }
256
257                 // Clear helper
258                 this.beanHelper.setContact(null);
259
260                 // Fire event
261                 this.addedUserEvent.fire(new AdminUserAddedEvent(updatedUser));
262
263                 // Return to user list (for now)
264                 return "admin_list_user"; //NOI18N
265         }
266
267         @Override
268         public void afterRegistrationEvent (@Observes final UserRegisteredEvent event) {
269                 // Trace message
270                 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterRegistration: event={0} - CALLED!", event)); //NOI18N
271
272                 // event should not be null
273                 if (null == event) {
274                         // Throw NPE
275                         throw new NullPointerException("event is null"); //NOI18N
276                 } else if (event.getRegisteredUser() == null) {
277                         // Throw NPE again
278                         throw new NullPointerException("event.user is null"); //NOI18N
279                 } else if (event.getRegisteredUser().getUserId() == null) {
280                         // userId is null
281                         throw new NullPointerException("event.user.userId is null"); //NOI18N
282                 } else if (event.getRegisteredUser().getUserId() < 1) {
283                         // Not avalid id
284                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
285                 }
286
287                 // Get user instance
288                 User registeredUser = event.getRegisteredUser();
289
290                 // Debug message
291                 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterRegistration: registeredUser={0}", registeredUser)); //NOI18N
292
293                 // Clear all data
294                 this.clear();
295
296                 // Trace message
297                 //* NOISY-DEBUG: */ System.out.println("UserWebBean:afterRegistration: EXIT!"); //NOI18N
298         }
299
300         @Override
301         public String editUserData () {
302                 // Get user instance
303                 User user = this.beanHelper.getUser();
304
305                 // Null password means not setting it
306                 String encryptedPassword = null;
307
308                 // Check if user instance is in helper and valid
309                 if (null == user) {
310                         // Throw NPE
311                         throw new NullPointerException("beanHelper.user is null"); //NOI18N
312                 } else if (user.getUserId() == null) {
313                         // Throw NPE again
314                         throw new NullPointerException("beanHelper.user.userId is null"); //NOI18N //NOI18N
315                 } else if (user.getUserId() < 1) {
316                         // Invalid id
317                         throw new IllegalStateException(MessageFormat.format("beanHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N
318                 } else if (this.getUserName() == null) {
319                         // Not all required fields are set
320                         throw new NullPointerException("this.userName is null"); //NOI18N
321                 } else if (this.getUserName().isEmpty()) {
322                         // Not all required fields are set
323                         throw new IllegalArgumentException("this.userName is empty"); //NOI18N
324                 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
325                         // Not same password entered
326                         this.setUserPassword(null);
327                         this.setUserPasswordRepeat(null);
328
329                         // Throw exception
330                         throw new FaceletException("Not same password entered"); //NOI18N
331                 } else if (this.userBean.ifUserNameExists(this.getUserName())) {
332                         // User name already exists
333                         throw new FaceletException(new UserNameAlreadyRegisteredException(this.getUserName()));
334                 } else if (this.isSamePasswordEntered()) {
335                         // Same password entered, create container
336                         if (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword()))) {
337                                 // Same password entered
338                                 throw new FaceletException("Same password as stored entered."); //NOI18N
339                         }
340
341                         // Encrypt password
342                         encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
343                 }
344
345                 // Set user name and flag
346                 user.setUserName(this.getUserName());
347                 user.setUserMustChangePassword(this.getUserMustChangePassword());
348
349                 // Is a password set?
350                 if (encryptedPassword != null) {
351                         // Set it as well
352                         user.setUserEncryptedPassword(encryptedPassword);
353                 }
354
355                 // Call EJB for updating user data
356                 User updatedUser = this.userBean.updateUserData(user);
357
358                 // Fire event
359                 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
360
361                 // Return to user list (for now)
362                 return "admin_list_user"; //NOI18N
363         }
364
365         @Override
366         public Boolean getUserMustChangePassword () {
367                 return this.userMustChangePassword;
368         }
369
370         @Override
371         public void setUserMustChangePassword (final Boolean userMustChangePassword) {
372                 this.userMustChangePassword = userMustChangePassword;
373         }
374
375         @Override
376         public String getUserName () {
377                 return this.userName;
378         }
379
380         @Override
381         public void setUserName (final String userName) {
382                 this.userName = userName;
383         }
384
385         @Override
386         public String getUserPassword () {
387                 return this.userPassword;
388         }
389
390         @Override
391         public void setUserPassword (final String userPassword) {
392                 this.userPassword = userPassword;
393         }
394
395         @Override
396         public String getUserPasswordRepeat () {
397                 return this.userPasswordRepeat;
398         }
399
400         @Override
401         public void setUserPasswordRepeat (final String userPasswordRepeat) {
402                 this.userPasswordRepeat = userPasswordRepeat;
403         }
404
405         /**
406          * Post-initialization of this class
407          */
408         @PostConstruct
409         public void init () {
410         }
411
412         /**
413          * Clears this bean
414          */
415         private void clear () {
416                 // Clear all data
417                 // - other data
418                 this.setUserName(null);
419                 this.setUserPassword(null);
420                 this.setUserPasswordRepeat(null);
421                 this.setUserMustChangePassword(null);
422         }
423
424         /**
425          * Checks if same password is entered and that they are not empty.
426          * <p>
427          * @return Whether the same password was entered
428          */
429         private boolean isSamePasswordEntered () {
430                 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
431         }
432
433 }