de.inetsource.jsfforum.beans.user.UserBean.java Source code

Java tutorial

Introduction

Here is the source code for de.inetsource.jsfforum.beans.user.UserBean.java

Source

/*
 * Copyright (C) 2014 Jrg Wiesmann
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package de.inetsource.jsfforum.beans.user;

import de.inetsource.jsfforum.db.UserFacade;
import de.inetsource.jsfforum.entity.Users;
import de.inetsource.jsfforum.security.PasswordService;
import de.inetsource.jsfforum.ui.CookieHelper;
import java.io.Serializable;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.Cookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @author Jrg Wiesmann
 */
@Component
@Scope("session")
public class UserBean implements Serializable {

    private static final long serialVersionUID = 1L;
    private static final String DEFAULT_THEME = "afterdark";
    private static final String COOKIE_NAME = "jsforumlogin";
    public static final String MAX_AGE = "maxAge";
    public static final int ONE_YEAR_IN_MS = 31536000;

    @Autowired
    protected UserFacade userFacade;
    private Users user;
    private String theme = DEFAULT_THEME;
    private String newPassword1;
    private String newPassword2;
    private boolean loginViaCookieTried = false;

    @PostConstruct
    public void init() {
        initEmptyUser();
    }

    private void initEmptyUser() {
        user = new Users();
        user.setTheme(DEFAULT_THEME);
    }

    public UserBean() {
    }

    public void login() {
        try {
            String encryptedPw = PasswordService.getInstance().encrypt(user.getPassword());
            Users users = userFacade.find(user.getUsername());
            if (users != null) {
                if (users.getPassword().equals(encryptedPw)) {
                    if (user.isRemember()) {
                        String uuid = UUID.randomUUID().toString();
                        users.setCookie(uuid);
                        users.setRemember(true);
                        userFacade.edit(users);
                        setOrCreateCookie(COOKIE_NAME, uuid);
                    } else {
                        CookieHelper ch = new CookieHelper();
                        ch.removeCookie(ch.getCookie(COOKIE_NAME));
                    }
                    user = users;
                } else {
                    logout();
                    FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login failed",
                            "Password mismatch");
                    FacesContext.getCurrentInstance().addMessage(null, message);
                }
            } else {
                logout();
                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login failed",
                        "User not found");
                FacesContext.getCurrentInstance().addMessage(null, message);
            }
        } catch (Exception ex) {
            logout();
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Login failed duo technical reason", ex.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, message);
        } finally {
            // make sure password is not send back to gui
            user.setPassword(null);
        }
        theme = user.getTheme();
    }

    public void saveTheme() {
        if (theme != null) {
            user.setTheme(theme);
            if (isLoggedIn()) {
                update();
            }
        }
    }

    public void register() {
        try {
            if (userFacade.find(user.getUsername()) == null) {
                String encryptedPw = PasswordService.getInstance().encrypt(user.getPassword());
                user.setPassword(encryptedPw);
                userFacade.create(user);
            } else {
                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Could not register user",
                        "User already registered");
                FacesContext.getCurrentInstance().addMessage(null, message);
            }
        } catch (Exception ex) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Could not register user",
                    ex.toString());
            FacesContext.getCurrentInstance().addMessage(null, message);
        } finally {
            // make sure password is not send back to gui
            user.setPassword(null);
        }
    }

    public void update() {
        if (user.getUsername() != null) {
            if (newPassword1 != null && newPassword1.equals(newPassword2) && newPassword1.length() > 0) {
                Users dbuser = userFacade.find(user.getUsername());
                try {
                    String encryptedPw = PasswordService.getInstance().encrypt(user.getPassword());
                    if (dbuser.getPassword().equals(encryptedPw)) {
                        // ready to update
                    }
                } catch (Exception ex) {

                } finally {
                    // make sure password is not send back to gui
                    user.setPassword(null);
                }
            } else {
                try {
                    Users dbuser = userFacade.find(user.getUsername());
                    user.setPassword(dbuser.getPassword());
                    userFacade.edit(user);
                } catch (Exception ex) {

                } finally {
                    // make sure password is not send back to gui
                    user.setPassword(null);
                }
            }
        }
    }

    private void setOrCreateCookie(String cookieName, String cookieValue) {
        CookieHelper ch = new CookieHelper();
        ch.setCookie(cookieName, cookieValue, ONE_YEAR_IN_MS);
    }

    public void loginUserViaCookie() {
        if (!loginViaCookieTried) {
            try {
                CookieHelper ch = new CookieHelper();
                Cookie cookie = ch.getCookie(COOKIE_NAME);
                if (cookie != null && cookie.getValue() != null) {
                    String cookieValue = cookie.getValue();
                    Users dbUser = userFacade.findUserByCookie(cookieValue);
                    if (dbUser != null) {
                        user = dbUser;
                        theme = user.getTheme();
                    } else {
                        ch.removeCookie(cookie);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                loginViaCookieTried = true;
                user.setPassword(null);
            }
        }
    }

    public void logout() {
        initEmptyUser();
    }

    public Users getUser() {
        return user;
    }

    public void setUser(Users user) {
        this.user = user;
    }

    public boolean isLoggedIn() {
        return (user != null && user.getUsername() != null && user.getUsername().length() > 0);
    }

    public String getNewPassword1() {
        return newPassword1;
    }

    public void setNewPassword1(String newPassword1) {
        this.newPassword1 = newPassword1;
    }

    public String getNewPassword2() {
        return newPassword2;
    }

    public void setNewPassword2(String newPassword2) {
        this.newPassword2 = newPassword2;
    }

    public String getTheme() {
        return theme;
    }

    public void setTheme(String theme) {
        this.theme = theme;
    }

    public boolean isLoginViaCookieTried() {
        return loginViaCookieTried;
    }

    public void setLoginViaCookieTried(boolean loginViaCookieTried) {
        this.loginViaCookieTried = loginViaCookieTried;
    }

}