package com.bjsxt.web.filter;

import com.bjsxt.pojo.Funs;
import com.bjsxt.pojo.Users;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 权限过滤器
 */
public class SafeFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // 获取HttpServletResponse
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取请求的uri
        String uri = request.getRequestURI();
        // 对静态资源放行处理
        if(uri.endsWith(".jsp") || uri.endsWith(".css") || uri.endsWith(".gif")){ // uri结尾是.jsp或.css或.gif的就放行
            // 放行
            filterChain.doFilter(servletRequest, servletResponse);
        }else { // 访问的是动态资源
            // 如果是用户登录资源，则放行
            if(uri.indexOf("login") != -1 || uri.indexOf("userLogin") != -1){
                // 放行
                filterChain.doFilter(servletRequest, servletResponse);
            }else { // 不是用户登录的资源
                // 获取HttpSession
                HttpSession session = request.getSession();
                // 获取Users对象
                Users user = (Users) session.getAttribute("user");
                List<Funs> funs = user.getFuns();
                // 设置是否放行的开关。默认不放行
                boolean flag = false;
                for(Funs f:funs){
                    // 判断当前访问的uri是否包含在功能数据中
                    if (uri.indexOf(f.getFunurl()) != -1){ // 包含则放行
                        flag = true;
                        break;
                    }
                }
                // 根据开关的值来判断是否放行
                if (flag){
                    filterChain.doFilter(servletRequest, servletResponse);
                }else {
                    // 重定向跳转到错误页面
                    response.sendRedirect("roleerror");
                }
            }
        }


    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}