]> git.mxchange.org Git - addressbook-war.git/blob - src/java/org/mxchange/addressbook/beans/login/AddressbookUserLoginWebSessionBean.java
Please cherry-pick:
[addressbook-war.git] / src / java / org / mxchange / addressbook / beans / login / AddressbookUserLoginWebSessionBean.java
1 /*
2  * Copyright (C) 2016 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.addressbook.beans.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.addressbook.beans.BaseAddressbookController;
36 import org.mxchange.addressbook.beans.user.AddressbookUserWebSessionController;
37 import org.mxchange.jusercore.container.login.LoginContainer;
38 import org.mxchange.jusercore.container.login.UserLoginContainer;
39 import org.mxchange.jusercore.events.login.ObservableUserLoggedInEvent;
40 import org.mxchange.jusercore.events.login.UserLoggedInEvent;
41 import org.mxchange.jusercore.events.logout.ObservableUserLogoutEvent;
42 import org.mxchange.jusercore.events.logout.UserLogoutEvent;
43 import org.mxchange.jusercore.events.user.password_change.ObservableUpdatedUserPasswordEvent;
44 import org.mxchange.jusercore.exceptions.UserNotFoundException;
45 import org.mxchange.jusercore.exceptions.UserPasswordMismatchException;
46 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
47 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
48 import org.mxchange.jusercore.model.login.UserLoginSessionBeanRemote;
49 import org.mxchange.jusercore.model.user.User;
50 import org.mxchange.jusercore.model.user.UserUtils;
51 import org.mxchange.jusercore.model.user.password_history.PasswordHistory;
52 import org.mxchange.jusercore.model.user.password_history.UserPasswordHistorySessionBeanRemote;
53 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
54 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
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 AddressbookUserLoginWebSessionBean extends BaseAddressbookController implements AddressbookUserLoginWebSessionController {
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 AddressbookUserWebSessionController 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 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 AddressbookUserLoginWebSessionBean () {
147                 // Defaul template is guest
148                 this.baseTemplatePathName = GUEST_BASE_TEMPLATE_NAME;
149         }
150
151         /**
152          * Method being call after user's password has been updated (and history
153          * entry has been created).
154          * <p>
155          * @param event Event being observed
156          */
157         public void afterUserUpdatedPasswordEvent (@Observes final ObservableUpdatedUserPasswordEvent event) {
158                 // Check parameter
159                 if (null == event) {
160                         // Throw NPE
161                         throw new NullPointerException("event is null"); //NOI18N
162                 } else if (event.getPasswordHistory() == null) {
163                         // Throw NPE again
164                         throw new NullPointerException("event.passwordHistory is null"); //NOI18N
165                 } else if (event.getPasswordHistory().getUserPasswordHistoryId() == null) {
166                         // ... and again
167                         throw new NullPointerException("event.passwordHistory.userPasswordHistoryId is null"); //NOI18N
168                 } else if (event.getPasswordHistory().getUserPasswordHistoryId() < 1) {
169                         // Invalid value
170                         throw new IllegalArgumentException(MessageFormat.format("event.passwordHistory.userPasswordHistoryId={0} is in valid", event.getPasswordHistory().getUserPasswordHistoryId())); //NOI18N
171                 }
172
173                 // All fine, so update list
174                 this.updatePasswordHistory(event.getPasswordHistory());
175         }
176
177         @Override
178         public String doAdminLogout () {
179                 // Is a user logged-in?
180                 if (this.isUserLoggedIn()) {
181                         // Call other logout
182                         return this.doUserLogout();
183                 }
184
185                 // Invalidate session
186                 FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
187
188                 // Set template type to guest
189                 this.setBaseTemplatePathName(GUEST_BASE_TEMPLATE_NAME); //NOI18N
190
191                 // Redirect to index
192                 return "index?faces-redirect=true"; //NOI18N
193         }
194
195         @Override
196         public String doUserLogin () {
197                 // Get user instance
198                 User user = this.userController.createUserLogin();
199
200                 // Create login container
201                 LoginContainer container = new UserLoginContainer(user, this.userController.getUserPassword());
202
203                 try {
204                         // Call bean
205                         User confirmedUser = this.userLoginBean.validateUserAccountStatus(container);
206
207                         // All fine here so set it here
208                         this.setLoggedInUser(confirmedUser);
209
210                         // Retrieve user's password list
211                         this.userPasswordHistory = this.userPasswordHistoryBean.getUserPasswordHistory(confirmedUser);
212
213                         // Set template to "login"
214                         this.setBaseTemplatePathName(USER_BASE_TEMPLATE_NAME); //NOI18N
215
216                         // Fire event away. Keep this last before return statement.
217                         this.userLoginEvent.fire(new UserLoggedInEvent(confirmedUser));
218
219                         // Clear this bean
220                         this.clear();
221
222                         // All fine
223                         return "login_user"; //NOI18N
224                 } catch (final UserNotFoundException ex) {
225                         // Show JSF message
226                         this.showFacesMessage("form_user_login:userName", "ERROR_USER_NOT_FOUND"); //NOI18N
227                         return ""; //NOI18N
228                 } catch (final UserStatusLockedException ex) {
229                         this.showFacesMessage("form_user_login:userName", "ERROR_USER_STATUS_LOCKED"); //NOI18N
230                         return ""; //NOI18N
231                 } catch (final UserStatusUnconfirmedException ex) {
232                         this.showFacesMessage("form_user_login:userName", "ERROR_USER_STATUS_UNCONFIRMED"); //NOI18N
233                         return ""; //NOI18N
234                 } catch (final UserPasswordMismatchException ex) {
235                         // Show JSF message
236                         this.showFacesMessage("form_user_login:userPassword", "ERROR_USER_PASSWORD_MISMATCH"); //NOI18N
237                         return ""; //NOI18N
238                 }
239         }
240
241         @Override
242         public String doUserLogout () {
243                 // Is loggedInUser set?
244                 if (this.getLoggedInUser() == null) {
245                         // Throw NPE
246                         throw new NullPointerException("this.loggedInUser is null"); //NOI18N
247                 } else if (this.getLoggedInUser().getUserId() == null) {
248                         // Throw again
249                         throw new NullPointerException("this.loggedInUser.userId is null"); //NOI18N
250                 } else if (this.getLoggedInUser().getUserId() < 1) {
251                         // Invalid user id
252                         throw new IllegalStateException(MessageFormat.format("this.loggedInUser.userId={0} is not valid.", this.getLoggedInUser().getUserId())); //NOI18N
253                 }
254
255                 // Fire event
256                 this.userLogoutEvent.fire(new UserLogoutEvent(this.getLoggedInUser()));
257
258                 // Invalidate session
259                 FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
260
261                 // Unset any user instances
262                 this.setLoggedInUser(null);
263                 this.setBaseTemplatePathName(GUEST_BASE_TEMPLATE_NAME); //NOI18N
264
265                 // Redirect to index
266                 return "index"; //NOI18N
267         }
268
269         @Override
270         public String getBaseTemplatePathName () {
271                 return this.baseTemplatePathName;
272         }
273
274         @Override
275         public void setBaseTemplatePathName (final String baseTemplatePathName) {
276                 this.baseTemplatePathName = baseTemplatePathName;
277         }
278
279         @Override
280         public User getLoggedInUser () {
281                 return this.loggedInUser;
282         }
283
284         @Override
285         public void setLoggedInUser (final User loggedInUser) {
286                 this.loggedInUser = loggedInUser;
287         }
288
289         @Override
290         public String getUserCurrentPassword () {
291                 return this.userCurrentPassword;
292         }
293
294         @Override
295         public void setUserCurrentPassword (final String userCurrentPassword) {
296                 this.userCurrentPassword = userCurrentPassword;
297         }
298
299         @Override
300         public List<PasswordHistory> getUserPasswordHistory () {
301                 return Collections.unmodifiableList(this.userPasswordHistory);
302         }
303
304         @Override
305         public boolean ifCurrentPasswordMatches () {
306                 // The current password must be set and not empty
307                 if (this.getUserCurrentPassword() == null) {
308                         // Is not set
309                         throw new NullPointerException("this.userCurrentPassword is null"); //NOI18N
310                 } else if (this.getUserCurrentPassword().isEmpty()) {
311                         // Is set empty
312                         throw new IllegalStateException("this.userCurrentPassword is empty."); //NOI18N
313                 }
314
315                 // Create "container"
316                 LoginContainer container = new UserLoginContainer(this.getLoggedInUser(), this.getUserCurrentPassword());
317
318                 // Now check if it matches
319                 return UserUtils.ifPasswordMatches(container, this.getLoggedInUser());
320         }
321
322         @Override
323         public boolean ifUserMustChangePassword () {
324                 return ((this.isUserLoggedIn()) && (Objects.equals(this.getLoggedInUser().getUserMustChangePassword(), Boolean.TRUE)));
325         }
326
327         /**
328          * Post-construction method
329          */
330         @PostConstruct
331         public void init () {
332                 try {
333                         // Get initial context
334                         Context context = new InitialContext();
335
336                         // Try to lookup
337                         this.userLoginBean = (UserLoginSessionBeanRemote) context.lookup("java:global/addressbook-ejb/login!org.mxchange.jusercore.model.login.UserLoginSessionBeanRemote"); //NOI18N
338
339                         // Also find this
340                         this.userPasswordHistoryBean = (UserPasswordHistorySessionBeanRemote) context.lookup("java:global/addressbook-ejb/userPasswordHistory!org.mxchange.jusercore.model.user.password_history.UserPasswordHistorySessionBeanRemote"); //NOI18N
341
342                         // Defaul template is guest
343                         this.baseTemplatePathName = GUEST_BASE_TEMPLATE_NAME;
344                 } catch (final NamingException ex) {
345                         // Continue to throw
346                         throw new FaceletException(ex);
347                 }
348         }
349
350         @Override
351         public boolean isInvisible () {
352                 // Check on login
353                 if (!this.isUserLoggedIn()) {
354                         // Not logged in!
355                         throw new IllegalStateException("isInvisible() has been invoked for a guest."); //NOI18N
356                 }
357
358                 // Check logged-in first, then invisibility
359                 return Objects.equals(this.getLoggedInUser().getUserProfileMode(), ProfileMode.INVISIBLE);
360         }
361
362         @Override
363         public boolean isPasswordInHistory (final String userPassword) {
364                 // Default is not found
365                 boolean isPasswordInHistory = false;
366
367                 // Init variables
368                 int count = 1;
369                 int maxEntries = this.getIntegerContextParameter("max_user_password_history"); //NOI18N
370
371                 // Check all passwords
372                 for (final PasswordHistory entry : this.getUserPasswordHistory()) {
373                         // Is password the same?
374                         if (UserUtils.ifPasswordMatches(userPassword, entry.getUserPasswordHistoryUser())) {
375                                 // Yes, found it
376                                 isPasswordInHistory = true;
377                                 break;
378                         } else if (count == maxEntries) {
379                                 // Maximum reached
380                                 break;
381                         }
382
383                         // Count up
384                         count++;
385                 }
386
387                 // Return status
388                 return isPasswordInHistory;
389         }
390
391         @Override
392         public boolean isUserLoggedIn () {
393                 // Compare instance
394                 this.userLoggedIn = ((this.getLoggedInUser() instanceof User) && (Objects.equals(this.getLoggedInUser().getUserAccountStatus(), UserAccountStatus.CONFIRMED)));
395
396                 // Return it
397                 return this.userLoggedIn;
398         }
399
400         /**
401          * Clears this bean
402          */
403         private void clear () {
404                 // Clear all fields
405                 this.setUserCurrentPassword(null);
406         }
407
408         /**
409          * Updates password history by adding given entry to it as long as it is not
410          * there.
411          * <p>
412          * @param passwordHistory Password history entry
413          */
414         private void updatePasswordHistory (final PasswordHistory passwordHistory) {
415                 if (null == passwordHistory) {
416                         // Throw NPE
417                         throw new NullPointerException("passwordHistory is null"); //NOI18N
418                 } else if (passwordHistory.getUserPasswordHistoryId() == null) {
419                         // Throw NPE again
420                         throw new NullPointerException("passwordHistory.userPasswordHistoryId is null"); //NOI18N
421                 } else if (passwordHistory.getUserPasswordHistoryId() < 1) {
422                         // Invalid id
423                         throw new IllegalArgumentException(MessageFormat.format("passwordHistory.userPasswordHistoryId={0} is not valid.", passwordHistory.getUserPasswordHistoryId())); //NOI18N
424                 }
425
426                 // Is it there?
427                 if (this.userPasswordHistory.contains(passwordHistory)) {
428                         // Excact copy found
429                         return;
430                 }
431
432                 // Check all entries
433                 for (final PasswordHistory entry : this.userPasswordHistory) {
434                         // Is same id number?
435                         if (Objects.equals(entry.getUserPasswordHistoryId(), passwordHistory.getUserPasswordHistoryId())) {
436                                 // Found it
437                                 return;
438                         }
439                 }
440
441                 // Not found, so add it
442                 this.userPasswordHistory.add(passwordHistory);
443         }
444
445 }