package cn.reghao.oss.store.config.inerceptor;

import cn.reghao.oss.api.util.AuthContext;
import cn.reghao.oss.api.util.JwtUtil;
import cn.reghao.jutil.web.ServletUtil;
import cn.reghao.oss.api.dto.OssPayload;
import com.github.benmanes.caffeine.cache.Cache;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import java.io.IOException;

/**
 * @author reghao
 * @date 2023-08-25 16:14:23
 */
@Component
public class TokenFilter implements Filter {
    private final Cache<String, String> cache;

    public TokenFilter(Cache<String, String> cache) {
        this.cache = cache;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        int userId = -1;
        String token = ServletUtil.getBearerToken(request);
        if (token != null) {
            String secretKey = cache.getIfPresent(token);
            if (secretKey != null) {
                OssPayload ossPayload = JwtUtil.getOssPayload(token, secretKey);
                userId = ossPayload.getUserId();
            }
        }

        try (AuthContext context = new AuthContext(userId)) {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
    }
}
