package com.skic.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
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;

public class AdminPermissionFilter implements Filter {

    /**
     * Default constructor. 
     */
    public AdminPermissionFilter() {
        
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {

	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		String servletPathString = req.getServletPath();
		HttpSession session = req.getSession();
		String flag = session.getAttribute("login_status").toString();
		String adminflag = session.getAttribute("adminflag").toString();
		String rootflag = session.getAttribute("rootflag").toString();
		if (servletPathString!= null
				&&(servletPathString.equals("/login.jsp"))||
				(servletPathString.equals("/page/homepage.jsp"))||
				(servletPathString.equalsIgnoreCase("/CheckLoginServlet"))
				) 
		{
			chain.doFilter(request, response);
		}else {
			if (flag.equals("1") && rootflag.equals("超级管理员")||adminflag.equals("管理员")) {
				chain.doFilter(request, response);
			}else if (flag.equals("1")&&adminflag.equals("")) {
				req.setAttribute("msg", "你不是管理员！");
				req.setAttribute("return_uri", servletPathString);
				RequestDispatcher rd = req.getRequestDispatcher("/page/homepage.jsp");
				rd.forward(req, resp);
			}else {
				req.setAttribute("msg", "您尚未登录");
				req.setAttribute("return_uri", servletPathString);
				RequestDispatcher rd = req.getRequestDispatcher("/login.jsp");
				rd.forward(req, resp);
			}
		}

	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {

	}

}
