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