package com.jeesite.modules.sso.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;


@Component
@Slf4j
public class AuthorizeFilter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("======拦截器拦截======");
        String requestURI = request.getRequestURI();
        StringBuffer requestURL = request.getRequestURL();


        if(request.getRequestURI().contains("/authorize") || request.getRequestURI().contains("/token")){
            //放行
            log.info("======放行======");
            return true;
        }

        //验证是否携带token
        String authorization = request.getHeader("Authorization");
        if(authorization==null){
            log.info("======拦截token======");
            HashMap<String,String> hashMap=new HashMap<>();
            hashMap.put("result","false");
            hashMap.put("message","未携带token,验证失败");
            String jsonString = JSON.toJSONString(hashMap);
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().println(jsonString);
            return false;
        }
        log.info("======放行======");
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
