package org.ccpit.base.security;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.ccpit.base.controller.BaseController;

/**
 * 用户登录Filter 拦截后台所有请求
 *
 * Created by sqp on 2015/9/30.
 */
public class LoginFilter implements Filter {
    //排除的URL
    private List<String> exceptPaths = new ArrayList<String>();
    //拦截之后重定向的url
    private String redirectPath = "";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        String exceptPath = filterConfig.getInitParameter("exceptPaths");
        if (StringUtils.isNotBlank(exceptPath)) {
            exceptPaths.addAll(Arrays.asList(exceptPath.split(",")));
        }

        redirectPath = filterConfig.getInitParameter("redirectPath");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        if (exceptPaths.contains(request.getRequestURI())){
            filterChain.doFilter(request,servletResponse);
            return;
        }

        if (request.getSession().getAttribute(BaseController.USER_IN_SESSION) == null) {
            response.sendRedirect(redirectPath);
            return;
        }
        filterChain.doFilter(request,servletResponse);
    }

    @Override
    public void destroy() {

    }

}
