package org.ccpit.base.security;


import org.apache.commons.lang.StringUtils;
import org.ccpit.base.controller.BaseController;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.jstl.sql.Result;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 用户登录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&&request.getSession().getAttribute("registerInfo")==null) {
            response.sendRedirect(redirectPath);
            return;
        }
        filterChain.doFilter(request,servletResponse);
    }

    @Override
    public void destroy() {

    }

}
