package com.games.gateway.filters;

import com.games.gateway.config.FilterOrderedConfig;
import com.games.gateway.utils.AuthCache;
import com.games.gateway.utils.Constant;
import com.games.gateway.utils.MatchStartUrlCheckUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 黑名单 全局过滤器
 */
@Order(FilterOrderedConfig.URLBlackListGlobalFilter)
@Component
@Slf4j
public class URLBlackListGlobalFilter implements GlobalFilter {

    @Autowired
    private AuthCache authCache;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().value();
        //获取服务名称
        String applicationName = exchange.getRequest().getHeaders().getFirst(Constant.APPLICATION_NAME);
        //验证请求url的前缀是否在配置列表中，如果不再的话则直接拦截掉（用来阻止掉我们不知道的一些开放url被访问到）
        boolean notMatchStartUrlBl = MatchStartUrlCheckUtils.notMatchPrefixUrlCheck(applicationName, path);
        //检查当前的url是否在请求黑名单中
        boolean inBlackList = inBlackList(path, applicationName);

        log.info("===> URLBlackListGlobalFilter url : {}, applicationName : {}, notMatchStartUrlBl : {}, inBlackList ; {}", path, applicationName, notMatchStartUrlBl, inBlackList);

        if (notMatchStartUrlBl || inBlackList) {
            log.info("===> path : {} in block access", path);
            exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * 判断是否在黑名单 内
     *
     * @param path
     * @return
     */
    private boolean inBlackList(String path, String applicationName) {
        List<String> urlBlacklist = authCache.getUrlBlacklist(applicationName);
        if (!CollectionUtils.isEmpty(urlBlacklist)) {
            AntPathMatcher antPathMatcher = new AntPathMatcher();
            for (String uri : urlBlacklist) {
                boolean match = antPathMatcher.match(uri, path);
                if (match) {
                    return true;
                }
            }
        }
        return false;
    }

}

