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