package com.gonghang.h5clientapp.config;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 拦截器
 * @Param:
 * @Author: shiwn
 * @Date: 2020/8/11 8:40
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {

    /**
     * @Description: 进入controller层之前拦截请求
     * @Author: shiwn
     * @Date: 2020/7/6 10:34
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String path = request.getServletPath();

        //对静态文件不拦截
        if (path.endsWith("/error") //异常
                || path.endsWith(".apk")
                || path.endsWith(".css") || path.endsWith(".html")
                || path.endsWith(".js") || path.endsWith(".gif")
                || path.endsWith(".jpg") || path.endsWith(".jpeg")
                || path.endsWith(".swf") || path.endsWith(".png")
                || path.endsWith(".ico") || path.endsWith(".doc")
                || path.endsWith(".xml") || path.endsWith(".xls")
                || path.endsWith(".pdf") || path.endsWith(".txt")
                || path.endsWith(".eot") || path.endsWith(".svg")
                || path.endsWith(".ttf") || path.endsWith(".woff")
                || path.endsWith(".otf") || path.endsWith(".woff2")
                || path.endsWith(".less") || path.endsWith(".scss")
                || path.endsWith(".mp3")
        ) {
            return true;
        }
        //查看session中User是否存在
        if (request.getSession().getAttribute("loginUser") == null) {
            //ajax请求类型
            if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equals("XMLHttpRequest")) {
                response.setHeader("Session-Status", "timeout");
                response.setStatus(401);
            }
            //普通请求类型
            else {
                request.setAttribute("msg", "无访问权限");
                request.setAttribute("code", 401);
                request.getRequestDispatcher("/").forward(request, response);
            }
            return false;
        }
        return true;
    }

}
