package isrp.filters;

import isrp.hibernate.model.businessobject.User;
import isrp.viewbeans.VisitBean;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class AuthorizationFilter implements Filter {
	FilterConfig config = null;
	ServletContext servletContext = null;
    private static final Log log = LogFactory.getLog(AuthorizationFilter.class);
	public AuthorizationFilter() {
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		config = filterConfig;
		servletContext = config.getServletContext();
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		log.debug("author... filter");
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		HttpSession session = httpRequest.getSession();
		String requestPath = httpRequest.getPathInfo();

		VisitBean visitBean = (VisitBean)session.getAttribute("visitBean");
		User user = visitBean.getUser();
		log.debug("authorization path: "+requestPath);		
		if (user == null) {
			log.debug("null");
			httpResponse.sendRedirect(httpRequest.getContextPath()
					+ "/faces/jsp/login.jsp");
		} else {
			if ((user.getRole()==2 && requestPath.indexOf("/admin/")>0)
				|| (user.getRole()==2 && requestPath.indexOf("/reviewer/")>0 && requestPath.indexOf("/reviewer/reviewDetailsPage.jsp")== -1)
				|| (user.getRole()==3 && requestPath.indexOf("/admin/")>0)
				|| (user.getRole()==3 && requestPath.indexOf("/author/")>0 && requestPath.indexOf("/author/paperDetailsPage.jsp")== -1)				
					){
				httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN,
                        "you are not allowed to visit this site");
			}else{
				chain.doFilter(request, response);
			}
		}

	}

	public void destroy() {
	}
}
