]> git.mxchange.org Git - jjobs-war.git/blob - src/java/org/mxchange/jjobs/beans/user/login/JobsUserLoginWebSessionBean.java
Please rename/cherry-pick:
[jjobs-war.git] / src / java / org / mxchange / jjobs / beans / user / login / JobsUserLoginWebSessionBean.java
1 /*
2  * Copyright (C) 2016, 2017 Roland Häder
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.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.context.FacesContext;
29 import javax.inject.Inject;
30 import javax.inject.Named;
31 import org.mxchange.jjobs.beans.BaseJobsController;
32 import org.mxchange.jjobs.beans.user.JobsUserWebRequestController;
33 import org.mxchange.jusercore.exceptions.UserNotFoundException;
34 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
35 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
36 import org.mxchange.jusercore.model.user.User;
37 import org.mxchange.jusercore.model.user.password_history.PasswordHistory;
38 import org.mxchange.jusercore.model.user.password_history.UserPasswordHistorySessionBeanRemote;
39 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
40 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
41 import org.mxchange.juserlogincore.container.login.LoginContainer;
42 import org.mxchange.juserlogincore.container.login.UserLoginContainer;
43 import org.mxchange.juserlogincore.events.login.ObservableUserLoggedInEvent;
44 import org.mxchange.juserlogincore.events.login.UserLoggedInEvent;
45 import org.mxchange.juserlogincore.events.logout.ObservableUserLogoutEvent;
46 import org.mxchange.juserlogincore.events.logout.UserLogoutEvent;
47 import org.mxchange.juserlogincore.events.user.password_change.ObservableUpdatedUserPasswordEvent;
48 import org.mxchange.juserlogincore.exceptions.UserPasswordMismatchException;
49 import org.mxchange.juserlogincore.login.UserLoginUtils;
50 import org.mxchange.juserlogincore.model.user.login.UserLoginSessionBeanRemote;
51
52 /**
53  * A web bean for user registration
54  * <p>
55  * @author Roland Häder<roland@mxchange.org>
56  */
57 @Named ("userLoginController")
58 @SessionScoped
59 public class JobsUserLoginWebSessionBean extends BaseJobsController implements JobsUserLoginWebSessionController {
60
61         /**
62          * Path name for guest base template
63          */
64         private static final String GUEST_BASE_TEMPLATE_NAME = "guest/guest"; //NOI18N
65
66         /**
67          * Path name for logged-in user base template
68          */
69         private static final String USER_BASE_TEMPLATE_NAME = "login/user/user"; //NOI18N
70
71         /**
72          * Serial number
73          */
74         private static final long serialVersionUID = 47_828_986_719_691_592L;
75
76         /**
77          * Template type for pages that might be displayed in guest area and login
78          * area.
79          */
80         private String baseTemplatePathName;
81
82         /**
83          * Logged-in user instance
84          */
85         private User loggedInUser;
86
87         /**
88          * User controller
89          */
90         @Inject
91         private JobsUserWebRequestController userController;
92
93         /**
94          * Current password
95          */
96         private String userCurrentPassword;
97
98         /**
99          * Flag whether the user has logged-in, set only from inside
100          */
101         private boolean userLoggedIn;
102
103         /**
104          * Remote register session-scoped bean
105          */
106         @EJB (lookup = "java:global/jjobs-ejb/userLogin!org.mxchange.juserlogincore.model.user.login.UserLoginSessionBeanRemote")
107         private UserLoginSessionBeanRemote userLoginBean;
108
109         /**
110          * Event fired when user has logged in
111          */
112         @Inject
113         @Any
114         private Event<ObservableUserLoggedInEvent> userLoginEvent;
115
116         /**
117          * Event fired when user has logged out
118          */
119         @Inject
120         @Any
121         private Event<ObservableUserLogoutEvent> userLogoutEvent;
122
123         /**
124          * User's password history
125          */
126         private List<PasswordHistory> userPasswordHistory;
127
128         /**
129          * EJB for user's password history
130          */
131         @EJB (lookup = "java:global/jjobs-ejb/userPasswordHistory!org.mxchange.jusercore.model.user.password_history.UserPasswordHistorySessionBeanRemote")
132         private UserPasswordHistorySessionBeanRemote userPasswordHistoryBean;
133
134         /**
135          * Default constructor
136          */
137         public JobsUserLoginWebSessionBean () {
138                 // Call super constructor
139                 super();
140
141                 // Defaul template is guest
142                 this.baseTemplatePathName = GUEST_BASE_TEMPLATE_NAME;
143         }
144
145         /**
146          * Method being call after user's password has been updated (and history
147          * entry has been created).
148          * <p>
149          * @param event Event being observed
150          */
151         public void afterUserUpdatedPasswordEvent (@Observes final ObservableUpdatedUserPasswordEvent event) {
152                 // Check parameter
153                 if (null == event) {
154                         // Throw NPE
155                         throw new NullPointerException("event is null"); //NOI18N
156                 } else if (event.getPasswordHistory() == null) {
157                         // Throw NPE again
158                         throw new NullPointerException("event.passwordHistory is null"); //NOI18N
159                 } else if (event.getPasswordHistory().getUserPasswordHistoryId() == null) {
160                         // ... and again
161                         throw new NullPointerException("event.passwordHistory.userPasswordHistoryId is null"); //NOI18N
162                 } else if (event.getPasswordHistory().getUserPasswordHistoryId() < 1) {
163                         // Invalid value
164                         throw new IllegalArgumentException(MessageFormat.format("event.passwordHistory.userPasswordHistoryId={0} is in valid", event.getPasswordHistory().getUserPasswordHistoryId())); //NOI18N
165                 }
166
167                 // All fine, so update list
168                 this.updatePasswordHistory(event.getPasswordHistory());
169         }
170
171         /**
172          * Logout for administrator area. If a logged-in user instance exists, it is
173          * being logged-out, too.
174          * <p>
175          * @return Outcome (should be redirected)
176          */
177         public String doAdminLogout () {
178                 // Is a user logged-in?
179                 if (this.isUserLoggedIn()) {
180                         // Call other logout
181                         return this.doUserLogout();
182                 }
183
184                 // Invalidate session
185                 FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
186
187                 // Set template type to guest
188                 this.setBaseTemplatePathName(GUEST_BASE_TEMPLATE_NAME); //NOI18N
189
190                 // Redirect to index
191                 return "index?faces-redirect=true"; //NOI18N
192         }
193
194         /**
195          * Logins the user, if the account is found, confirmed and unlocked.
196          * <p>
197          * @return Redirect target
198          */
199         public String doUserLogin () {
200                 // Get user instance
201                 User user = this.userController.createUserLogin();
202
203                 // Create login container
204                 LoginContainer loginContainer = new UserLoginContainer(user, this.userController.getUserPassword());
205
206                 try {
207                         // Call bean
208                         User confirmedUser = this.userLoginBean.validateUserAccountStatus(loginContainer);
209
210                         // All fine here so set it here
211                         this.setLoggedInUser(confirmedUser);
212
213                         // Retrieve user's password list
214                         this.userPasswordHistory = this.userPasswordHistoryBean.getUserPasswordHistory(confirmedUser);
215
216                         // Set template to "login"
217                         this.setBaseTemplatePathName(USER_BASE_TEMPLATE_NAME); //NOI18N
218
219                         // Fire event away. Keep this last before return statement.
220                         this.userLoginEvent.fire(new UserLoggedInEvent(confirmedUser));
221
222                         // Clear this bean
223                         this.clear();
224
225                         // All fine
226                         return "login_user"; //NOI18N
227                 } catch (final UserNotFoundException ex) {
228                         // Show JSF message
229                         this.showFacesMessage("form_user_login:userName", "ERROR_USER_NOT_FOUND"); //NOI18N
230                         return ""; //NOI18N
231                 } catch (final UserStatusLockedException ex) {
232                         this.showFacesMessage("form_user_login:userName", "ERROR_USER_STATUS_LOCKED"); //NOI18N
233                         return ""; //NOI18N
234                 } catch (final UserStatusUnconfirmedException ex) {
235                         this.showFacesMessage("form_user_login:userName", "ERROR_USER_STATUS_UNCONFIRMED"); //NOI18N
236                         return ""; //NOI18N
237                 } catch (final UserPasswordMismatchException ex) {
238                         // Show JSF message
239                         this.showFacesMessage("form_user_login:userPassword", "ERROR_USER_PASSWORD_MISMATCH"); //NOI18N
240                         return ""; //NOI18N
241                 }
242         }
243
244         /**
245          * Logout for current user by invalidating the current session.
246          * <p>
247          * @return Outcome (should be redirected)
248          */
249         public String doUserLogout () {
250                 // Is loggedInUser set?
251                 if (this.getLoggedInUser() == null) {
252                         // Throw NPE
253                         throw new NullPointerException("this.loggedInUser is null"); //NOI18N
254                 } else if (this.getLoggedInUser().getUserId() == null) {
255                         // Throw again
256                         throw new NullPointerException("this.loggedInUser.userId is null"); //NOI18N
257                 } else if (this.getLoggedInUser().getUserId() < 1) {
258                         // Invalid user id
259                         throw new IllegalStateException(MessageFormat.format("this.loggedInUser.userId={0} is not valid.", this.getLoggedInUser().getUserId())); //NOI18N
260                 }
261
262                 // Fire event
263                 this.userLogoutEvent.fire(new UserLogoutEvent(this.getLoggedInUser()));
264
265                 // Invalidate session
266                 FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
267
268                 // Unset any user instances
269                 this.setLoggedInUser(null);
270                 this.setBaseTemplatePathName(GUEST_BASE_TEMPLATE_NAME); //NOI18N
271
272                 // Redirect to index
273                 return "index"; //NOI18N
274         }
275
276         @Override
277         public String getBaseTemplatePathName () {
278                 return this.baseTemplatePathName;
279         }
280
281         @Override
282         public void setBaseTemplatePathName (final String baseTemplatePathName) {
283                 this.baseTemplatePathName = baseTemplatePathName;
284         }
285
286         @Override
287         public User getLoggedInUser () {
288                 return this.loggedInUser;
289         }
290
291         @Override
292         public void setLoggedInUser (final User loggedInUser) {
293                 this.loggedInUser = loggedInUser;
294         }
295
296         /**
297          * Getter for current password (clear text)
298          * <p>
299          * @return Current password
300          */
301         public String getUserCurrentPassword () {
302                 return this.userCurrentPassword;
303         }
304
305         /**
306          * Setter for current password (clear text)
307          * <p>
308          * @param userCurrentPassword Current password
309          */
310         public void setUserCurrentPassword (final String userCurrentPassword) {
311                 this.userCurrentPassword = userCurrentPassword;
312         }
313
314         @Override
315         public List<PasswordHistory> getUserPasswordHistory () {
316                 return Collections.unmodifiableList(this.userPasswordHistory);
317         }
318
319         @Override
320         public boolean ifCurrentPasswordMatches () {
321                 // The current password must be set and not empty
322                 if (this.getUserCurrentPassword() == null) {
323                         // Is not set
324                         throw new NullPointerException("this.userCurrentPassword is null"); //NOI18N
325                 } else if (this.getUserCurrentPassword().isEmpty()) {
326                         // Is set empty
327                         throw new IllegalStateException("this.userCurrentPassword is empty."); //NOI18N
328                 }
329
330                 // Create "container"
331                 LoginContainer container = new UserLoginContainer(this.getLoggedInUser(), this.getUserCurrentPassword());
332
333                 // Now check if it matches
334                 return UserLoginUtils.ifPasswordMatches(container, this.getLoggedInUser());
335         }
336
337         @Override
338         public boolean ifUserMustChangePassword () {
339                 return ((this.isUserLoggedIn()) && (Objects.equals(this.getLoggedInUser().getUserMustChangePassword(), Boolean.TRUE)));
340         }
341
342         @Override
343         public boolean isInvisible () {
344                 // Check on login
345                 if (!this.isUserLoggedIn()) {
346                         // Not logged in!
347                         throw new IllegalStateException("isInvisible() has been invoked for a guest."); //NOI18N
348                 }
349
350                 // Check logged-in first, then invisibility
351                 return Objects.equals(this.getLoggedInUser().getUserProfileMode(), ProfileMode.INVISIBLE);
352         }
353
354         @Override
355         public boolean isPasswordInHistory (final String userPassword) {
356                 // Default is not found
357                 boolean isPasswordInHistory = false;
358
359                 // Init variables
360                 int count = 1;
361                 int maxEntries = this.getIntegerContextParameter("max_user_password_history"); //NOI18N
362
363                 // Check all passwords
364                 for (final PasswordHistory entry : this.getUserPasswordHistory()) {
365                         // Is password the same?
366                         if (UserLoginUtils.ifPasswordMatches(userPassword, entry.getUserPasswordHistoryUser())) {
367                                 // Yes, found it
368                                 isPasswordInHistory = true;
369                                 break;
370                         } else if (count == maxEntries) {
371                                 // Maximum reached
372                                 break;
373                         }
374
375                         // Count up
376                         count++;
377                 }
378
379                 // Return status
380                 return isPasswordInHistory;
381         }
382
383         @Override
384         public boolean isUserLoggedIn () {
385                 // Compare instance
386                 this.userLoggedIn = ((this.getLoggedInUser() instanceof User) && (Objects.equals(this.getLoggedInUser().getUserAccountStatus(), UserAccountStatus.CONFIRMED)));
387
388                 // Return it
389                 return this.userLoggedIn;
390         }
391
392         /**
393          * Clears this bean
394          */
395         private void clear () {
396                 // Clear all fields
397                 this.setUserCurrentPassword(null);
398         }
399
400         /**
401          * Updates password history by adding given entry to it as long as it is not
402          * there.
403          * <p>
404          * @param passwordHistory Password history entry
405          */
406         private void updatePasswordHistory (final PasswordHistory passwordHistory) {
407                 if (null == passwordHistory) {
408                         // Throw NPE
409                         throw new NullPointerException("passwordHistory is null"); //NOI18N
410                 } else if (passwordHistory.getUserPasswordHistoryId() == null) {
411                         // Throw NPE again
412                         throw new NullPointerException("passwordHistory.userPasswordHistoryId is null"); //NOI18N
413                 } else if (passwordHistory.getUserPasswordHistoryId() < 1) {
414                         // Invalid id
415                         throw new IllegalArgumentException(MessageFormat.format("passwordHistory.userPasswordHistoryId={0} is not valid.", passwordHistory.getUserPasswordHistoryId())); //NOI18N
416                 }
417
418                 // Is it there?
419                 if (this.userPasswordHistory.contains(passwordHistory)) {
420                         // Excact copy found
421                         return;
422                 }
423
424                 // Check all entries
425                 for (final PasswordHistory entry : this.userPasswordHistory) {
426                         // Is same id number?
427                         if (Objects.equals(entry.getUserPasswordHistoryId(), passwordHistory.getUserPasswordHistoryId())) {
428                                 // Found it
429                                 return;
430                         }
431                 }
432
433                 // Not found, so add it
434                 this.userPasswordHistory.add(passwordHistory);
435         }
436
437 }