2 * Copyright (C) 2016 Roland Häder
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.
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.
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/>.
17 package org.mxchange.addressbook.beans.login;
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;
57 * A web bean for user registration
59 * @author Roland Häder<roland@mxchange.org>
61 @Named ("userLoginController")
63 public class AddressbookUserLoginWebSessionBean extends BaseAddressbookController implements AddressbookUserLoginWebSessionController {
66 * Path name for guest base template
68 private static final String GUEST_BASE_TEMPLATE_NAME = "guest/guest"; //NOI18N
71 * Path name for logged-in user base template
73 private static final String USER_BASE_TEMPLATE_NAME = "login/user/user"; //NOI18N
78 private static final long serialVersionUID = 47_828_986_719_691_592L;
81 * Template type for pages that might be displayed in guest area and login
84 private String baseTemplatePathName;
89 private String currentPassword;
92 * Logged-in user instance
94 private User loggedInUser;
100 private AddressbookUserWebSessionController userController;
103 * Flag whether the user has logged-in, set only from inside
105 private boolean userLoggedIn;
110 private UserLoginSessionBeanRemote userLoginBean;
113 * Event fired when user has logged in
117 private Event<ObservableUserLoggedInEvent> userLoginEvent;
120 * Event fired when user has logged out
124 private Event<ObservableUserLogoutEvent> userLogoutEvent;
127 * User's password history
129 private List<PasswordHistory> userPasswordHistory;
132 * EJB for user's password history
134 private UserPasswordHistorySessionBeanRemote userPasswordHistoryBean;
137 * Default constructor
139 public AddressbookUserLoginWebSessionBean () {
140 // Defaul template is guest
141 this.baseTemplatePathName = GUEST_BASE_TEMPLATE_NAME;
145 * Method being call after user's password has been updated (and history
146 * entry has been created).
148 * @param event Event being observed
150 public void afterUserUpdatedPasswordEvent (@Observes final ObservableUpdatedUserPasswordEvent event) {
154 throw new NullPointerException("event is null"); //NOI18N
155 } else if (event.getPasswordHistory() == null) {
157 throw new NullPointerException("event.passwordHistory is null"); //NOI18N
158 } else if (event.getPasswordHistory().getUserPasswordHistoryId() == null) {
160 throw new NullPointerException("event.passwordHistory.userPasswordHistoryId is null"); //NOI18N
161 } else if (event.getPasswordHistory().getUserPasswordHistoryId() < 1) {
163 throw new IllegalArgumentException(MessageFormat.format("event.passwordHistory.userPasswordHistoryId={0} is in valid", event.getPasswordHistory().getUserPasswordHistoryId())); //NOI18N
166 // All fine, so update list
167 this.updatePasswordHistory(event.getPasswordHistory());
171 public String doAdminLogout () {
172 // Is a user logged-in?
173 if (this.isUserLoggedIn()) {
175 return this.doUserLogout();
178 // Invalidate session
179 FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
181 // Set template type to guest
182 this.setBaseTemplatePathName(GUEST_BASE_TEMPLATE_NAME); //NOI18N
185 return "index?faces-redirect=true"; //NOI18N
189 public String doUserLogin () {
191 User user = this.userController.createUserLogin();
193 // Create login container
194 LoginContainer container = new UserLoginContainer(user, this.userController.getUserPassword());
198 User confirmedUser = this.userLoginBean.validateUserAccountStatus(container);
200 // All fine here so set it here
201 this.setLoggedInUser(confirmedUser);
203 // Retrieve user's password list
204 this.userPasswordHistory = this.userPasswordHistoryBean.getUserPasswordHistory(confirmedUser);
206 // Set template to "login"
207 this.setBaseTemplatePathName(USER_BASE_TEMPLATE_NAME); //NOI18N
209 // Fire event away. Keep this last before return statement.
210 this.userLoginEvent.fire(new UserLoggedInEvent(confirmedUser));
216 return "login"; //NOI18N
217 } catch (final UserNotFoundException | UserStatusLockedException | UserStatusUnconfirmedException ex) {
219 this.showFacesMessage("form_user_login:userName", ex); //NOI18N
221 } catch (final UserPasswordMismatchException ex) {
223 this.showFacesMessage("form_user_login:userPassword", ex); //NOI18N
229 public String doUserLogout () {
230 // Is loggedInUser set?
231 if (this.getLoggedInUser() == null) {
233 throw new NullPointerException("this.loggedInUser is null"); //NOI18N
234 } else if (this.getLoggedInUser().getUserId() == null) {
236 throw new NullPointerException("this.loggedInUser.userId is null"); //NOI18N
237 } else if (this.getLoggedInUser().getUserId() < 1) {
239 throw new IllegalStateException(MessageFormat.format("this.loggedInUser.userId={0} is not valid.", this.getLoggedInUser().getUserId())); //NOI18N
243 this.userLogoutEvent.fire(new UserLogoutEvent(this.getLoggedInUser()));
245 // Invalidate session
246 FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
248 // Unset any user instances
249 this.setLoggedInUser(null);
250 this.setBaseTemplatePathName(GUEST_BASE_TEMPLATE_NAME); //NOI18N
253 return "index"; //NOI18N
257 public String getBaseTemplatePathName () {
258 return this.baseTemplatePathName;
262 public void setBaseTemplatePathName (final String baseTemplatePathName) {
263 this.baseTemplatePathName = baseTemplatePathName;
267 public String getCurrentPassword () {
268 return this.currentPassword;
272 public void setCurrentPassword (final String currentPassword) {
273 this.currentPassword = currentPassword;
277 public User getLoggedInUser () {
278 return this.loggedInUser;
282 public void setLoggedInUser (final User loggedInUser) {
283 this.loggedInUser = loggedInUser;
287 public List<PasswordHistory> getUserPasswordHistory () {
288 return Collections.unmodifiableList(this.userPasswordHistory);
292 public boolean ifCurrentPasswordMatches () {
293 // The current password must be set and not empty
294 if (this.getCurrentPassword() == null) {
296 throw new NullPointerException("this.currentPassword is null"); //NOI18N
297 } else if (this.getCurrentPassword().isEmpty()) {
299 throw new IllegalStateException("this.currentPassword is empty."); //NOI18N
302 // Create "container"
303 LoginContainer container = new UserLoginContainer(this.getLoggedInUser(), this.getCurrentPassword());
305 // Now check if it matches
306 return UserUtils.ifPasswordMatches(container, this.getLoggedInUser());
310 public boolean ifUserMustChangePassword () {
311 return (this.isUserLoggedIn() && this.getLoggedInUser().getUserMustChangePassword());
315 * Post-construction method
318 public void init () {
320 // Get initial context
321 Context context = new InitialContext();
324 this.userLoginBean = (UserLoginSessionBeanRemote) context.lookup("java:global/addressbook-ejb/login!org.mxchange.jusercore.model.login.UserLoginSessionBeanRemote"); //NOI18N
327 this.userPasswordHistoryBean = (UserPasswordHistorySessionBeanRemote) context.lookup("java:global/addressbook-ejb/userPasswordHistory!org.mxchange.jusercore.model.user.password_history.UserPasswordHistorySessionBeanRemote"); //NOI18N
328 } catch (final NamingException ex) {
330 throw new FaceletException(ex);
335 public boolean isInvisible () {
337 if (!this.isUserLoggedIn()) {
339 throw new IllegalStateException("isInvisible() has been invoked for a guest."); //NOI18N
342 // Check logged-in first, then invisibility
343 return this.getLoggedInUser().getUserProfileMode().equals(ProfileMode.INVISIBLE);
347 public boolean isPasswordInHistory (final String userPassword) {
348 // Default is not found
349 boolean isPasswordInHistory = false;
353 int maxEntries = this.getIntegerContextParameter("max_user_password_history"); //NOI18N
355 // Check all passwords
356 for (final PasswordHistory entry : this.getUserPasswordHistory()) {
357 // Is password the same?
358 if (UserUtils.ifPasswordMatches(userPassword, entry.getUserPasswordHistoryUser())) {
360 isPasswordInHistory = true;
362 } else if (count == maxEntries) {
372 return isPasswordInHistory;
376 public boolean isUserLoggedIn () {
377 this.userLoggedIn = ((this.getLoggedInUser() instanceof User) && (Objects.equals(this.getLoggedInUser().getUserAccountStatus(), UserAccountStatus.CONFIRMED)));
380 return this.userLoggedIn;
386 private void clear () {
388 this.setCurrentPassword(null);
392 * Updates password history by adding given entry to it as long as it is not
395 * @param passwordHistory Password history entry
397 private void updatePasswordHistory (final PasswordHistory passwordHistory) {
398 if (null == passwordHistory) {
400 throw new NullPointerException("passwordHistory is null"); //NOI18N
401 } else if (passwordHistory.getUserPasswordHistoryId() == null) {
403 throw new NullPointerException("passwordHistory.userPasswordHistoryId is null"); //NOI18N
404 } else if (passwordHistory.getUserPasswordHistoryId() < 1) {
406 throw new IllegalArgumentException(MessageFormat.format("passwordHistory.userPasswordHistoryId={0} is not valid.", passwordHistory.getUserPasswordHistoryId())); //NOI18N
410 if (this.userPasswordHistory.contains(passwordHistory)) {
416 for (final PasswordHistory entry : this.userPasswordHistory) {
417 // Is same id number?
418 if (Objects.equals(entry.getUserPasswordHistoryId(), passwordHistory.getUserPasswordHistoryId())) {
424 // Not found, so add it
425 this.userPasswordHistory.add(passwordHistory);