package com.visualpatterns.timex.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.visualpatterns.timex.model.Employee;
import com.visualpatterns.timex.util.ApplicationSecurityManager;

/**
 * Przejmuje requesty HTTP aby upewnic sie ze uzytkownik jest poprawnie zalogowany; rowniez zamyka
 * zamyka sesje Hibernate dla biezacego watku.
 * @author anil 
 */
public class HttpRequestInterceptor extends HandlerInterceptorAdapter
{
    private String signInPage;
    private ApplicationSecurityManager applicationSecurityManager;

    /**
     * Uses ApplicationSecurityManager upewnia sie ze uzytkownik jest zalogowany; jesli nie,
     * uzytkownik jest przekierowany do strony logowania.
     * @see ApplicationSecurityManager
     */
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) throws Exception
    {
        Employee employee = (Employee) applicationSecurityManager
                .getEmployee(request);
        if (employee == null)
        {
            response.sendRedirect(this.signInPage);
            return false;
        }

        return true;
    }

    public String getSignInPage()
    {
        return signInPage;
    }

    public void setSignInPage(String signInPage)
    {
        this.signInPage = signInPage;
    }

    public ApplicationSecurityManager getApplicationSecurityManager()
    {
        return applicationSecurityManager;
    }

    public void setApplicationSecurityManager(
            ApplicationSecurityManager applicationSecurityManager)
    {
        this.applicationSecurityManager = applicationSecurityManager;
    }
}
