package cn.teammodel.security.filter;

import cn.teammodel.model.entity.TmdUserDetail;
import cn.teammodel.security.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
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;
import java.util.Collection;

/**
 * x-auth-authToken filter
 * @author winter
 * @create 2023-11-09 10:43
 */
@Slf4j
public class AuthInnerTokenFilter extends OncePerRequestFilter {
    JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,  FilterChain filterChain) throws ServletException, IOException {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        // 进入此过滤器说明 OIDC 认证成功，则验证 authToken
        // 验证 authToken 合法
        TmdUserDetail tmdUserDetail = jwtTokenUtil.getValidUserDetail(request);
        if (tmdUserDetail == null) {
//            log.error("authToken authentication failed: {}", request.getHeader("x-auth-authToken"));
            SecurityContextHolder.clearContext(); // 验证失败不应该在此处抛出异常,应该维护好 context 的值,以便整个过滤器链正常运行
            filterChain.doFilter(request, response);
            return;
        }
        // 组装 authToken 的 jwt 进 authentication
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        UsernamePasswordAuthenticationToken finalAuthentication = new UsernamePasswordAuthenticationToken(tmdUserDetail, null, authorities);
        context.setAuthentication(finalAuthentication);
        filterChain.doFilter(request, response);
    }
}
