/**
 * 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 java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;

import com.crunii.micro.common.security.BasicAuth;

import lombok.extern.slf4j.Slf4j;

/**
 * @author 田平 create 2019年5月27日下午2:18:53
 */
@Slf4j
public class BasicAuthFilter implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		String basic = req.getHeader(HttpHeaders.AUTHORIZATION);
		if (BasicAuth.matchAuth(basic)) {
			chain.doFilter(request, response);
		} else {
			log.info("path:{} not have basic auth header!", 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() {

	}

}
