package cn.reghao.oss.store.inerceptor;

import cn.reghao.oss.store.service.StoreLocalService;
import cn.reghao.oss.store.util.JwtUtil;
import cn.reghao.oss.store.util.UserContext;
import cn.reghao.jutil.web.ServletUtil;
import cn.reghao.oss.storeapi.dto.OssPayload;
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 StoreLocalService storeLocalService;

    public TokenFilter(StoreLocalService storeLocalService) {
        this.storeLocalService = storeLocalService;
    }

    @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) {
            OssPayload ossPayload = JwtUtil.getOssPayload(token, storeLocalService.getSecretKey());
            userId = ossPayload.getUserId();
        }

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

    @Override
    public void destroy() {
    }
}
