package com.cf.imes.framework.organ.core.web;

import com.cf.imes.framework.organ.core.context.OrganContextHolder;
import com.cf.imes.framework.web.core.util.WebFrameworkUtils;
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;

/**
 * 多组织 Context Web 过滤器
 * 将请求 Header 中的 tenant-id 解析出来，添加到 {@link OrganContextHolder} 中，这样后续的 DB 等操作，可以获得到组织编号。
 *
 * @author 晨丰科技
 */
public class OrganContextWebFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        // 设置
        Long organId = WebFrameworkUtils.getOrganId(request);
        if (organId != null) {
            OrganContextHolder.setOrganId(organId);
        }
        try {
            chain.doFilter(request, response);
        } finally {
            // 清理
            OrganContextHolder.clear();
        }
    }

}
