package cn.wise.sc.acquisition.business.filter;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.wise.sc.acquisition.business.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * Token过滤器
 *
 * @author zhutianwei
 */
@Component
public class TokenFilter extends OncePerRequestFilter {

	private static final Logger log = LoggerFactory.getLogger("TokenFilter");

	public static final String TOKEN_KEY = "Authorization";

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String token = getToken(request);
		if (StringUtils.isNotBlank(token)) {
			Map map = null;
			try {
				map = JwtUtil.parserToken(token);
				//过期时间
				Long gqTime = Long.valueOf(map.get("timeStamp").toString()) + 60 * 60 * 1000;
				long nowTime = (new Date()).getTime();
				if (nowTime > gqTime) {
					log.error("token过期");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		filterChain.doFilter(request, response);
	}

	/**
	 * 根据参数或者header获取token
	 *
	 * @param request
	 * @return
	 */
	public static String getToken(HttpServletRequest request) {
		String token = request.getParameter(TOKEN_KEY);
		if (StringUtils.isBlank(token)) {
			token = request.getHeader(TOKEN_KEY);
		}
		return token;
	}

}
