package com.huiju.foyo.filter;

import com.huiju.foyo.model.SysUser;
import com.huiju.foyo.session.SessionLoad;
import com.huiju.foyo.session.UserControl;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

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

/**
 * 过滤器
 * @author weiximei
 */
@Component
public class FoyoFilter implements Filter {

    private PathMatcher pathMatcher = new AntPathMatcher();

    /**
     * 重定向路径
     */
    private static final String TO_LOGIN = "/admin/toLogin";

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

        if (request.getRequestURI().equals("/admin/login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 非 admin 请求直接放过
        if (!pathMatcher.match("/admin/**", request.getRequestURI()) ) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        SysUser user = SessionLoad.getUser();
        if (null == user) {
            user = (SysUser) request.getSession().getAttribute(UserControl.SESSION_USER);
            if (null == user) {
                // 重定向登录
                request.getRequestDispatcher(TO_LOGIN).forward(servletRequest, servletResponse);
                return;
            }
        }

        // 设置用户
        UserControl.setUser(user);

        // 继续执行
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
