package com.keao.edu.zuul.web.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

@Component
public class AuthFilter extends ZuulFilter {

	public static String ACCESS_TOKEN = "access_token";
	
	public static String BEARER_TYPE = "Bearer";
	
	@Override
	public Object run() throws ZuulException {//过滤器核心业务方法
		RequestContext requestContext = RequestContext.getCurrentContext();
		HttpServletRequest request = requestContext.getRequest();
		String token = extractHeaderToken(request);
		
		if(StringUtils.isBlank(token)){
			token = request.getParameter(ACCESS_TOKEN);
		}
		
		/*if(StringUtils.isBlank(token)){
			HttpServletResponse response = requestContext.getResponse();
			requestContext.setSendZuulResponse(false);
			response.setStatus(HttpStatus.FORBIDDEN.value());
			requestContext.setResponseBody("token验证失败");
		}*/

		return null;
	}

	@Override
	public boolean shouldFilter() {// 返回true，必须执行过滤器；false，不执行过滤器
		return true;
	}

	@Override
	public int filterOrder() {// 过滤器的执行顺序，数字越小越先执行
		return 0;
	}

	@Override
	public String filterType() {// 过滤类型，前置过滤器，后置过滤器
		return "pre";
	}
	
	private String extractHeaderToken(HttpServletRequest request) {
		Enumeration<String> headers = request.getHeaders("Authorization");
		while (headers.hasMoreElements()) { // typically there is only one (most servers enforce that)
			String value = headers.nextElement();
			if ((value.toLowerCase().startsWith(BEARER_TYPE.toLowerCase()))) {
				String authHeaderValue = value.substring(BEARER_TYPE.length()).trim();
				int commaIndex = authHeaderValue.indexOf(',');
				if (commaIndex > 0) {
					authHeaderValue = authHeaderValue.substring(0, commaIndex);
				}
				return authHeaderValue;
			}
		}

		return null;
	}
}
