/**  
 * @Title: TokenFilter.java
 * @Package: com.fuzamei.filter
 * @Description: TODO 
 * @author: Ma Amin
 * @date: 2017-10-31 下午12:02:38
 */
package com.fuzamei.interceptor;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fuzamei.service.UserAuthoricationService;
import com.fuzamei.util.JSONUtil;
import com.fuzamei.util.ValidationUtil;

/**
 * 
 * @className:TokenInterceptor[每次访问需要在请求头上带上tokenId，key为Authorization，不然会被拦截器拦截]
 * @author:ylx--->[yanglingxiao2009@163.com]
 * @date:2018年1月30日下午5:01:29
 * @version v1.0
 */
public class TokenInterceptor extends HandlerInterceptorAdapter{
	@Autowired
	private UserAuthoricationService userAuthoricationService;
	 
	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws IOException {
		try {
			String tokenAndUserId = request.getHeader("Authorization");
			if(tokenAndUserId==null||"".equals(tokenAndUserId.trim())){//请求头不能为null
				throw new RuntimeException("Authorization为空");
			}
			String token =ValidationUtil.checkBlankAndAssignString(tokenAndUserId.split("&")[0].replace("Bearer", ""));//token校验
			int userId = ValidationUtil.checkAndAssignInt(tokenAndUserId.split("&")[1]);//账户id校验
			boolean flag = userAuthoricationService.verificationToken(userId, token);//校验userId和token值是否符合
			if(!flag){//token校验未通过
				throw new RuntimeException("token验证失败");
			}
			return true;
		} catch (Exception e) {
			PrintWriter writer = response.getWriter();
			Map<String, Object> jsonMap = JSONUtil.getJsonMap(300, false, e.getMessage(), null);
			response.setContentType("application/json");
			writer.append(JSON.toJSONString(jsonMap));
			return false;
		}
	}
}
