package com.schisandra.gateway.filter;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Classname LoginFilter
 * @BelongsProject: schisandra-cloud-storage
 * @BelongsPackage: com.schisandra.club.gateway.filter
 * @Author: schisandra
 * @CreateTime: 2024-03-03  17:41
 * @Description: 登录拦截器
 * @Version: 1.0
 */
@Component
@Slf4j
public class LoginFilter implements GlobalFilter {
    @Override
    @SneakyThrows
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();
        String url = request.getURI().getPath();
        log.info("LoginFilter.filter.url:{}", url);
        if (url.equals("/oauth/render/gitee") || url.equals("/oauth/callback/gitee") || url.equals("/auth/user/register") || url.equals("/auth/user/login") || url.equals("/system/getConfigByKey")) {
            return chain.filter(exchange);
        }
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        String userId = (String) tokenInfo.getLoginId();
        System.out.println("userId:" + userId);
        if (StringUtils.isEmpty(userId)) {
            throw new Exception("未获取到用户信息");
        }

        mutate.header("userId", userId);

        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }
}
