]> git.mxchange.org Git - jfinancials-war.git/blob - src/java/org/mxchange/jfinancials/beans/user/login/FinancialsUserLoginWebSessionBean.java
Don't cherry-pick:
[jfinancials-war.git] / src / java / org / mxchange / jfinancials / beans / user / login / FinancialsUserLoginWebSessionBean.java
1 /*
2  * Copyright (C) 2016 - 2020 Free Software Foundation
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.jfinancials.beans.user.login;
18
19 import java.text.MessageFormat;
20 import java.util.Collections;
21 import java.util.List;
22 import java.util.Objects;
23 import javax.ejb.EJB;
24 import javax.enterprise.context.SessionScoped;
25 import javax.enterprise.event.Event;
26 import javax.enterprise.event.Observes;
27 import javax.enterprise.inject.Any;
28 import javax.faces.application.FacesMessage;
29 import javax.faces.context.FacesContext;
30 import javax.inject.Inject;
31 import javax.inject.Named;
32 import org.mxchange.jfinancials.beans.BaseFinancialsBean;
33 import org.mxchange.jfinancials.beans.user.FinancialsUserWebRequestController;
34 import org.mxchange.jfinancials.beans.user.list.FinancialsUserListWebViewController;
35 import org.mxchange.jusercore.events.user.add.ObservableAdminAddedUserEvent;
36 import org.mxchange.jusercore.events.user.created.ObservableCreatedUserEvent;
37 import org.mxchange.jusercore.events.user.linked.ObservableAdminLinkedUserEvent;
38 import org.mxchange.jusercore.model.user.User;
39 import org.mxchange.jusercore.model.user.password_history.PasswordHistory;
40 import org.mxchange.jusercore.model.user.password_history.UserPasswordHistorySessionBeanRemote;
41 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
42 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
43 import org.mxchange.juserlogincore.container.login.LoginContainer;
44 import org.mxchange.juserlogincore.container.login.UserLoginContainer;
45 import org.mxchange.juserlogincore.events.login.ObservableUserLoggedInEvent;
46 import org.mxchange.juserlogincore.events.login.UserLoggedInEvent;
47 import org.mxchange.juserlogincore.events.logout.ObservableUserLogoutEvent;
48 import org.mxchange.juserlogincore.events.logout.UserLogoutEvent;
49 import org.mxchange.juserlogincore.events.registration.ObservableUserRegisteredEvent;
50 import org.mxchange.juserlogincore.events.user.password_change.ObservableUpdatedUserPasswordEvent;
51 import org.mxchange.juserlogincore.login.UserLoginUtils;
52
53 /**
54  * A web bean for user registration
55  * <p>
56  * @author Roland Häder<roland@mxchange.org>
57  */
58 @Named ("userLoginController")
59 @SessionScoped
60 public class FinancialsUserLoginWebSessionBean extends BaseFinancialsBean implements FinancialsUserLoginWebSessionController {
61
62         /**
63          * Path name for guest base template
64          */
65         private static final String GUEST_BASE_TEMPLATE_NAME = "guest/guest"; //NOI18N
66
67         /**
68          * Path name for logged-in user base template
69          */
70         private static final String USER_BASE_TEMPLATE_NAME = "login/user/user"; //NOI18N
71
72         /**
73          * Serial number
74          */
75         private static final long serialVersionUID = 47_828_986_719_691_592L;
76
77         /**
78          * Template type for pages that might be displayed in guest area and login
79          * area.
80          */
81         private String baseTemplatePathName;
82
83         /**
84          * Logged-in user instance
85          */
86         private User loggedInUser;
87
88         /**
89          * User controller
90          */
91         @Inject
92         private FinancialsUserWebRequestController userController;
93
94         /**
95          * Current password
96          */
97         private String userCurrentPassword;
98
99         /**
100          * User id
101          */
102         private Long userId;
103
104         /**
105          * Administrative user-list controller
106          */
107         @Inject
108         private FinancialsUserListWebViewController userListController;
109
110         /**
111          * Flag whether the user has logged-in, set only from inside
112          */
113         private boolean userLoggedIn;
114
115         /**
116          * Event fired when user has logged in
117          */
118         @Inject
119         @Any
120         private Event<ObservableUserLoggedInEvent> userLoginEvent;
121
122         /**
123          * Event fired when user has logged out
124          */
125         @Inject
126         @Any
127         private Event<ObservableUserLogoutEvent> userLogoutEvent;
128
129         /**
130          * User name
131          */
132         private String userName;
133
134         /**
135          * User password (clear-text from web form)
136          */
137         private String userPassword;
138
139         /**
140          * User's password history
141          */
142         private List<PasswordHistory> userPasswordHistory;
143
144         /**
145          * EJB for user's password history
146          */
147         @EJB (lookup = "java:global/jfinancials-ejb/userPasswordHistory!org.mxchange.jusercore.model.user.password_history.UserPasswordHistorySessionBeanRemote")
148         private UserPasswordHistorySessionBeanRemote userPasswordHistoryBean;
149
150         /**
151          * Whether the user wants a public profile
152          */
153         private ProfileMode userProfileMode;
154
155         /**
156          * Default constructor
157          */
158         public FinancialsUserLoginWebSessionBean () {
159                 // Call super constructor
160                 super();
161
162                 // Defaul template is guest
163                 this.baseTemplatePathName = GUEST_BASE_TEMPLATE_NAME;
164         }
165
166         /**
167          * Event observer for newly added users by administrator
168          * <p>
169          * @param event Event being fired
170          */
171         public void afterAdminAddedUserEvent (@Observes final ObservableAdminAddedUserEvent event) {
172                 // Event and contained entity instance should not be null
173                 if (null == event) {
174                         // Throw NPE
175                         throw new NullPointerException("event is null"); //NOI18N
176                 } else if (event.getAddedUser() == null) {
177                         // Throw NPE again
178                         throw new NullPointerException("event.addedUser is null"); //NOI18N
179                 } else if (event.getAddedUser().getUserId() == null) {
180                         // userId is null
181                         throw new NullPointerException("event.addedUser.userId is null"); //NOI18N
182                 } else if (event.getAddedUser().getUserId() < 1) {
183                         // Not avalid id
184                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getAddedUser(), event.getAddedUser().getUserId())); //NOI18N
185                 }
186
187                 // Set user id again
188                 this.setUserId(event.getAddedUser().getUserId());
189         }
190
191         /**
192          * Event observer for linked users with existing contact data
193          * <p>
194          * @param event Event being fired
195          */
196         public void afterAdminLinkedUserEvent (@Observes final ObservableAdminLinkedUserEvent event) {
197                 // Event and contained entity instance should not be null
198                 if (null == event) {
199                         // Throw NPE
200                         throw new NullPointerException("event is null"); //NOI18N
201                 } else if (event.getLinkedUser() == null) {
202                         // Throw NPE again
203                         throw new NullPointerException("event.linkedUser is null"); //NOI18N
204                 } else if (event.getLinkedUser().getUserId() == null) {
205                         // userId is null
206                         throw new NullPointerException("event.linkedUser.userId is null"); //NOI18N
207                 } else if (event.getLinkedUser().getUserId() < 1) {
208                         // Not avalid id
209                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getLinkedUser(), event.getLinkedUser().getUserId())); //NOI18N
210                 }
211
212                 // Set user id again
213                 this.setUserId(event.getLinkedUser().getUserId());
214         }
215
216         /**
217          * Event observer for when a bean helper has successfully created a user
218          * instance, means the user exists. If the user does not exist, this event
219          * should not fire but instead a proper exception must be thrown.
220          * <p>
221          * @param event User created event
222          */
223         public void afterCreatedUserEvent (@Observes final ObservableCreatedUserEvent event) {
224                 // Is the instance valid?
225                 if (null == event) {
226                         // Throw NPE
227                         throw new NullPointerException("event is null"); //NOI18N
228                 } else if (event.getCreatedUser() == null) {
229                         // Throw NPE again
230                         throw new NullPointerException("event.createdUser is null"); //NOI18N
231                 } else if (event.getCreatedUser().getUserId() == null) {
232                         // Throw NPE again
233                         throw new NullPointerException("event.createdUser.userId is null"); //NOI18N
234                 } else if (event.getCreatedUser().getUserId() < 1) {
235                         // Throw NPE again
236                         throw new NullPointerException(MessageFormat.format("event.createdUser.userId={0} is not valid", event.getCreatedUser().getUserId())); //NOI18N
237                 }
238
239                 // Get user instance
240                 final User user = event.getCreatedUser();
241
242                 // Set all fields here
243                 this.copyUser(user);
244         }
245
246         /**
247          * Event observer for logged-in user
248          * <p>
249          * @param event Event instance
250          */
251         public void afterUserLoginEvent (@Observes final ObservableUserLoggedInEvent event) {
252                 // Event and contained entity instance should not be null
253                 if (null == event) {
254                         // Throw NPE
255                         throw new NullPointerException("event is null"); //NOI18N
256                 } else if (event.getLoggedInUser() == null) {
257                         // Throw NPE again
258                         throw new NullPointerException("event.registeredUser is null"); //NOI18N
259                 } else if (event.getLoggedInUser().getUserId() == null) {
260                         // userId is null
261                         throw new NullPointerException("event.registeredUser.userId is null"); //NOI18N
262                 } else if (event.getLoggedInUser().getUserId() < 1) {
263                         // Not avalid id
264                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getLoggedInUser(), event.getLoggedInUser().getUserId())); //NOI18N
265                 }
266
267                 // "Cache" user instance
268                 final User user = event.getLoggedInUser();
269
270                 // Copy all data to this bean
271                 this.copyUser(user);
272         }
273
274         /**
275          * Event observer for user password changes
276          * <p>
277          * @param event Event being fired
278          */
279         public void afterUserPasswordChangedEvent (@Observes final ObservableUpdatedUserPasswordEvent event) {
280                 // Is it valid?
281                 if (null == event) {
282                         // Throw NPE
283                         throw new NullPointerException("event is null"); //NOI18N
284                 } else if (event.getUserPassword() == null) {
285                         // Throw NPE
286                         throw new NullPointerException("event.userPassword is null"); //NOI18N
287                 } else if (event.getUserPassword().isEmpty()) {
288                         // Throw NPE
289                         throw new IllegalArgumentException("event.userPassword is empty"); //NOI18N
290                 }
291
292                 // Set it here
293                 this.setUserPassword(event.getUserPassword());
294                 this.updatePasswordHistory(event.getPasswordHistory());
295         }
296
297         /**
298          * Event observer for new user registrations
299          * <p>
300          * @param event User registration event
301          */
302         public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
303                 // Event and contained entity instance 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.registeredUser is null"); //NOI18N
310                 } else if (event.getRegisteredUser().getUserId() == null) {
311                         // userId is null
312                         throw new NullPointerException("event.registeredUser.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                 final User registeredUser = event.getRegisteredUser();
320
321                 // Copy all data from registered->user
322                 this.copyUser(registeredUser);
323
324                 // Set user id again
325                 this.setUserId(registeredUser.getUserId());
326         }
327
328         /**
329          * Logout for administrator area. If a logged-in user instance exists, it is
330          * being logged-out, too.
331          * <p>
332          * @return Outcome (should be redirected)
333          */
334         public String doAdminLogout () {
335                 // Is a user logged-in?
336                 if (this.isUserLoggedIn()) {
337                         // Call other logout
338                         return this.doUserLogout();
339                 }
340
341                 // Invalidate session
342                 FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
343
344                 // Set template type to guest
345                 this.setBaseTemplatePathName(GUEST_BASE_TEMPLATE_NAME); //NOI18N
346
347                 // Redirect to index
348                 return "index?faces-redirect=true"; //NOI18N
349         }
350
351         /**
352          * Logins the user, if the account is found, confirmed and unlocked.
353          * <p>
354          * @return Redirect target
355          */
356         public String doUserLogin () {
357                 // Found user instance
358                 User updatedUser = null;
359
360                 // Iterate over all users
361                 for (final User currentUser : this.userListController.getAllUsers()) {
362                         // Is the user name matching?
363                         if (currentUser.getUserName().equals(this.getUserName())) {
364                                 // Yes, same user, then set it and stop iteration
365                                 updatedUser = currentUser;
366                                 break;
367                         }
368                 }
369
370                 if (null == updatedUser) {
371                         // Show JSF message
372                         this.showFacesMessage("form_user_login:userName", "ERROR_USER_NOT_FOUND", FacesMessage.SEVERITY_ERROR); //NOI18N
373                         return ""; //NOI18N
374                 } else if (updatedUser.getUserAccountStatus().equals(UserAccountStatus.LOCKED)) {
375                         this.showFacesMessage("form_user_login:userName", "ERROR_USER_STATUS_LOCKED", FacesMessage.SEVERITY_WARN); //NOI18N
376                         return ""; //NOI18N
377                 } else if (updatedUser.getUserAccountStatus().equals(UserAccountStatus.UNCONFIRMED)) {
378                         this.showFacesMessage("form_user_login:userName", "ERROR_USER_STATUS_UNCONFIRMED", FacesMessage.SEVERITY_INFO); //NOI18N
379                         return ""; //NOI18N
380                 } else if (!UserLoginUtils.ifPasswordMatches(this.getUserPassword(), updatedUser)) {
381                         // Show JSF message
382                         this.showFacesMessage("form_user_login:userPassword", "ERROR_USER_PASSWORD_MISMATCH", FacesMessage.SEVERITY_WARN); //NOI18N
383                         return ""; //NOI18N
384                 }
385
386                 // All fine here so set it here
387                 this.setLoggedInUser(updatedUser);
388
389                 // Retrieve user's password list
390                 this.userPasswordHistory = this.userPasswordHistoryBean.fetchPasswordHistoryByUser(updatedUser);
391
392                 // Set template to "login"
393                 this.setBaseTemplatePathName(USER_BASE_TEMPLATE_NAME);
394
395                 // Fire event away. Keep this last before return statement.
396                 this.userLoginEvent.fire(new UserLoggedInEvent(updatedUser));
397
398                 // Clear this bean
399                 this.clear();
400
401                 // All fine
402                 return "login_user"; //NOI18N
403         }
404
405         /**
406          * Logout for current user by invalidating the current session.
407          * <p>
408          * @return Outcome (should be redirected)
409          */
410         public String doUserLogout () {
411                 // Is loggedInUser set?
412                 if (this.getLoggedInUser() == null) {
413                         // Throw NPE
414                         throw new NullPointerException("this.loggedInUser is null"); //NOI18N
415                 } else if (this.getLoggedInUser().getUserId() == null) {
416                         // Throw again
417                         throw new NullPointerException("this.loggedInUser.userId is null"); //NOI18N
418                 } else if (this.getLoggedInUser().getUserId() < 1) {
419                         // Invalid user id
420                         throw new IllegalStateException(MessageFormat.format("this.loggedInUser.userId={0} is not valid.", this.getLoggedInUser().getUserId())); //NOI18N
421                 }
422
423                 // Fire event
424                 this.userLogoutEvent.fire(new UserLogoutEvent(this.getLoggedInUser()));
425
426                 // Invalidate session
427                 FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
428
429                 // Unset any user instances
430                 this.setLoggedInUser(null);
431                 this.setBaseTemplatePathName(GUEST_BASE_TEMPLATE_NAME); //NOI18N
432
433                 // Redirect to index
434                 return "index"; //NOI18N
435         }
436
437         @Override
438         public String getBaseTemplatePathName () {
439                 return this.baseTemplatePathName;
440         }
441
442         @Override
443         public void setBaseTemplatePathName (final String baseTemplatePathName) {
444                 this.baseTemplatePathName = baseTemplatePathName;
445         }
446
447         @Override
448         public User getLoggedInUser () {
449                 return this.loggedInUser;
450         }
451
452         @Override
453         public void setLoggedInUser (final User loggedInUser) {
454                 this.loggedInUser = loggedInUser;
455         }
456
457         /**
458          * Getter for current password (clear text)
459          * <p>
460          * @return Current password
461          */
462         public String getUserCurrentPassword () {
463                 return this.userCurrentPassword;
464         }
465
466         /**
467          * Setter for current password (clear text)
468          * <p>
469          * @param userCurrentPassword Current password
470          */
471         public void setUserCurrentPassword (final String userCurrentPassword) {
472                 this.userCurrentPassword = userCurrentPassword;
473         }
474
475         /**
476          * Getter for user id
477          * <p>
478          * @return User id
479          */
480         public Long getUserId () {
481                 return this.userId;
482         }
483
484         /**
485          * Setter for user id
486          * <p>
487          * @param userId User id
488          */
489         public void setUserId (final Long userId) {
490                 this.userId = userId;
491         }
492
493         /**
494          * Getter for user name
495          * <p>
496          * @return User name
497          */
498         public String getUserName () {
499                 return this.userName;
500         }
501
502         /**
503          * Setter for user name
504          * <p>
505          * @param userName User name
506          */
507         public void setUserName (final String userName) {
508                 this.userName = userName;
509         }
510
511         /**
512          * Getter for clear-text user password
513          * <p>
514          * @return Clear-text user password
515          */
516         public String getUserPassword () {
517                 return this.userPassword;
518         }
519
520         /**
521          * Setter for clear-text user password
522          * <p>
523          * @param userPassword Clear-text user password
524          */
525         public void setUserPassword (final String userPassword) {
526                 this.userPassword = userPassword;
527         }
528
529         @Override
530         public List<PasswordHistory> getUserPasswordHistory () {
531                 return Collections.unmodifiableList(this.userPasswordHistory);
532         }
533
534         /**
535          * Getter for user profile mode
536          * <p>
537          * @return User profile mode
538          */
539         public ProfileMode getUserProfileMode () {
540                 return this.userProfileMode;
541         }
542
543         /**
544          * Setter for user profile mode
545          * <p>
546          * @param userProfileMode User profile mode
547          */
548         public void setUserProfileMode (final ProfileMode userProfileMode) {
549                 this.userProfileMode = userProfileMode;
550         }
551
552         @Override
553         public boolean ifCurrentPasswordMatches () {
554                 // The current password must be set and not empty
555                 if (this.getUserCurrentPassword() == null) {
556                         // Is not set
557                         throw new NullPointerException("this.userCurrentPassword is null"); //NOI18N
558                 } else if (this.getUserCurrentPassword().isEmpty()) {
559                         // Is set empty
560                         throw new IllegalStateException("this.userCurrentPassword is empty."); //NOI18N
561                 }
562
563                 // Create "container"
564                 final LoginContainer container = new UserLoginContainer(this.getLoggedInUser(), this.getUserCurrentPassword());
565
566                 // Now check if it matches
567                 return UserLoginUtils.ifPasswordMatches(container, this.getLoggedInUser());
568         }
569
570         @Override
571         public boolean ifUserMustChangePassword () {
572                 return ((this.isUserLoggedIn()) && (Objects.equals(this.getLoggedInUser().getUserMustChangePassword(), Boolean.TRUE)));
573         }
574
575         @Override
576         public boolean isInvisible () {
577                 // Check on login
578                 if (!this.isUserLoggedIn()) {
579                         // Not logged in!
580                         throw new IllegalStateException("isInvisible() has been invoked for a guest."); //NOI18N
581                 }
582
583                 // Check logged-in first, then invisibility
584                 return Objects.equals(this.getLoggedInUser().getUserProfileMode(), ProfileMode.INVISIBLE);
585         }
586
587         @Override
588         public boolean isPasswordInHistory (final String userPassword) {
589                 // Default is not found
590                 boolean isPasswordInHistory = false;
591
592                 // Init variables
593                 int count = 1;
594                 final int maxEntries = this.getIntegerContextParameter("max_user_password_history"); //NOI18N
595
596                 // Check all passwords
597                 for (final PasswordHistory entry : this.getUserPasswordHistory()) {
598                         // Is password the same?
599                         if (UserLoginUtils.ifPasswordMatches(userPassword, entry.getUserPasswordHistoryUser())) {
600                                 // Yes, found it
601                                 isPasswordInHistory = true;
602                                 break;
603                         } else if (count == maxEntries) {
604                                 // Maximum reached
605                                 break;
606                         }
607
608                         // Count up
609                         count++;
610                 }
611
612                 // Return status
613                 return isPasswordInHistory;
614         }
615
616         /**
617          * Checks if the user id is empty
618          * <p>
619          * @return Whether the user id is empty
620          */
621         public boolean isUserIdEmpty () {
622                 return ((this.getUserId() == null) || (this.getUserId() == 0));
623         }
624
625         @Override
626         public boolean isUserLoggedIn () {
627                 // Compare instance
628                 this.userLoggedIn = ((this.getLoggedInUser() instanceof User) && (Objects.equals(this.getLoggedInUser().getUserAccountStatus(), UserAccountStatus.CONFIRMED)));
629
630                 // Return it
631                 return this.userLoggedIn;
632         }
633
634         /**
635          * Clears this bean
636          */
637         private void clear () {
638                 // Clear all fields
639                 this.setLoggedInUser(null);
640                 this.setUserName(null);
641                 this.setUserPassword(null);
642                 this.setUserCurrentPassword(null);
643                 this.setUserProfileMode(null);
644         }
645
646         /**
647          * Copies given user into the controller
648          * <p>
649          * @param user User instance
650          */
651         private void copyUser (final User user) {
652                 // Copy all fields:
653                 // - base data
654                 this.setUserId(user.getUserId());
655                 this.setUserName(user.getUserName());
656                 this.setUserProfileMode(user.getUserProfileMode());
657         }
658
659         /**
660          * Updates password history by adding given entry to it as long as it is not
661          * there.
662          * <p>
663          * @param passwordHistory Password history entry
664          */
665         private void updatePasswordHistory (final PasswordHistory passwordHistory) {
666                 if (null == passwordHistory) {
667                         // Throw NPE
668                         throw new NullPointerException("passwordHistory is null"); //NOI18N
669                 } else if (passwordHistory.getUserPasswordHistoryId() == null) {
670                         // Throw NPE again
671                         throw new NullPointerException("passwordHistory.userPasswordHistoryId is null"); //NOI18N
672                 } else if (passwordHistory.getUserPasswordHistoryId() < 1) {
673                         // Invalid id
674                         throw new IllegalArgumentException(MessageFormat.format("passwordHistory.userPasswordHistoryId={0} is not valid.", passwordHistory.getUserPasswordHistoryId())); //NOI18N
675                 }
676
677                 // Is it there?
678                 if (this.userPasswordHistory.contains(passwordHistory)) {
679                         // Excact copy found
680                         return;
681                 }
682
683                 // Check all entries
684                 for (final PasswordHistory entry : this.userPasswordHistory) {
685                         // Is same id number?
686                         if (Objects.equals(entry.getUserPasswordHistoryId(), passwordHistory.getUserPasswordHistoryId())) {
687                                 // Found it
688                                 return;
689                         }
690                 }
691
692                 // Not found, so add it
693                 this.userPasswordHistory.add(passwordHistory);
694         }
695
696 }