package cn.teammodel.security.filter;

import cn.teammodel.model.entity.TmdUserDetail;
import cn.teammodel.security.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 对外的 AI chat 接口的认证过滤器
 * @author winter
 * @create 2023-11-09 10:43
 */
@Slf4j
public class ApiAuthTokenFilter extends OncePerRequestFilter {

    JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();

    @Override
    protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        SecurityContext context = SecurityContextHolder.getContext();
        // 进入此过滤器说明 OIDC 认证成功，则验证 authToken
        // 验证 authToken 合法
        String token = request.getHeader("X-Auth-Authtoken");
        if (StringUtils.isBlank(token)) {
            filterChain.doFilter(request, response);
            return;
        }
//        Claims claims = jwtTokenUtil.validAndGetClaims(token, "fXO6ko/qyXeYrkecPeKdgXnuLXf9vMEtnBC9OB3s+aA=", 315360000);
        TmdUserDetail validUserDetail1 = jwtTokenUtil.getOutterTokenDetail(request);
        if (validUserDetail1 == null) {
            SecurityContextHolder.clearContext(); // 验证失败不应该在此处抛出异常,应该维护好 context 的值,以便整个过滤器链正常运行
            filterChain.doFilter(request, response);
            return;
        }
        // 组装 authToken 的 jwt 进 authentication
        UsernamePasswordAuthenticationToken finalAuthentication = new UsernamePasswordAuthenticationToken(validUserDetail1, null, null);
        context.setAuthentication(finalAuthentication);
        filterChain.doFilter(request, response);
    }
}
