/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved.
 * <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.web.filter;

import com.crunii.micro.common.constants.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <pre>
 *     微服务互调需要权限控制的可以配置filter，
 *     feignClient默认会加上这个header
 * </pre>
 *
 * @author 田平 create 2023-01-12 11:50:53
 */
@Slf4j
public class InnerAuthFilter implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		String token = req.getHeader(CommonConstants.HEADER_INNER_AUTH_TOKEN);
		if (CommonConstants.INNER_AUTH_TOKEN.equals(token)) {
			chain.doFilter(request, response);
		} else {
			log.warn("path:{} not have INNER_AUTH_TOKEN:{} header!", CommonConstants.HEADER_INNER_AUTH_TOKEN, req.getRequestURI());
			HttpServletResponse rsp = (HttpServletResponse) response;
			rsp.setStatus(HttpStatus.UNAUTHORIZED.value());
		}
	}

	/**
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	/**
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {

	}

}
