/*
 * This file is part of DebGen Biobank Software developed by ASTRID Research.
 * All rights reserved. Reproduction, modification, use or disclosure
 * to third parties without express authority is forbidden.
 *
 * Copyright ASTRID Research Inc., Hungary, 2009-2011.
 *
 * ASTRID Research
 * Headquaters: Csapo utca 42. Debrecen H-4029 HUNGARY
 * Phone: +36-52-533-173        Fax: +36-52-533-174
 * Web: http://www.astrid.hu    E-mail: info@astrid.hu
 *
 * Project name: DebGen Biobank Software project.
 * URLS:
 * Developers: Istvan Zoltan Nagy (istvan.nagy@astrid.hu)
 */
package hu.astrid.debgen.authentication.filter;

import hu.astrid.debgen.authentication.domain.DebGenUser;
import hu.astrid.debgen.exception.ServerSideException;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * A filter to authenticate the users if needed.
 * @author inagy
 */
public class AuthenticationFilter implements Filter {

    /**
     * The logger
     */
    private static Logger logger = Logger.getLogger(AuthenticationFilter.class);
    /**
     * The list of allowed actions
     */
    final static String[] allowed = new String[]{"init.html", "init.do", "login.html", "auth.do", "forgottenpassword.html", "sendreminder.html", "forgottenpassword.do", "confirmpassword.html", "cancelpassword.html"};
    /**
     * The filterconfig
     */
    private FilterConfig filterConfig = null;

    /**
     * Default constructor
     */
    public AuthenticationFilter() {
    }

    /**
     * Does the work of the filter
     * @param request The HttpRequest
     * @param response The HttpResponse
     * @param chain The filterChain
     * @throws IOException When IO error occurs
     * @throws ServletException When Servlet related error occurs
     */
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;

        //Remove the /debgen/ string from the begining of the string.
        String uri = "";
        String reqUri = req.getRequestURI();
        String appUri = "/" + filterConfig.getServletContext().getInitParameter("applicationuri") + "/";
        if (reqUri.startsWith(appUri)) {
            uri = reqUri.substring(appUri.length());
        }
        if (uri.equals("")) {
            ((HttpServletResponse) response).sendRedirect("index.html");
            return;
        }

        for (String s : allowed) {
            if (uri.startsWith(s)) {
                chain.doFilter(request, response);
                return;
            }
        }

        boolean passed = false;
        /*
         * Logged user.
         */
        DebGenUser user = null;
        try {
            user = (DebGenUser) req.getSession().getAttribute("user");
            if (user != null) {
                passed = true;
            }
        } catch (Exception ex) {
            //IGNORED
            logger.debug("User couldn't found, login process needed.");
        }

        if (!passed) {
            request.setAttribute("exception", new ServerSideException("A kért tartalom csak bejelentkezés után érhető el. Kérem jelentkezzen be a biobank szoftverbe.")); //i18
            request.getRequestDispatcher("main.jsp").forward(request, response);
        } else {
            chain.doFilter(request, response);
            return;
        }
    }

    /**
     * Destroy
     */
    public void destroy() {
    }

    /**
     * Initializes the filterConfig
     * @param filterConfig The filterConfig
     */
    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }
}
