package cn.reghao.tnb.user.app.config.web;

import cn.reghao.jutil.web.ServletUtil;
import cn.reghao.tnb.common.auth.LoginUser;
import cn.reghao.tnb.common.auth.UserContext;
import org.springframework.stereotype.Component;

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

/**
 * @author reghao
 * @date 2023-08-25 21:14:23
 */
@Component
public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        long userId = -1L;
        String userIdStr = ServletUtil.getHeader("x-user-id");
        if (userIdStr != null) {
            userId = Long.parseLong(userIdStr);
        }

        String loginId = ServletUtil.getHeader("x-login-id");
        LoginUser loginUser = new LoginUser(userId);
        try (UserContext context = new UserContext(loginUser)) {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
    }
}
