package com.fjs.scenic.interceptor;

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

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.fjs.scenic.cyt.utils.JsonUtils;
import com.fjs.scenic.utils.Cons;
import com.fjs.scenic.utils.ReturnResult;

@Component
public class TokenInterceper implements HandlerInterceptor{
	
	Logger log = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String token = request.getHeader("token");
		String result = redisTemplate.opsForValue().get(token);
		if(StringUtils.isBlank(result)){
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			response.getWriter().write(JsonUtils.marshalToString(ReturnResult.build(401, "未登录")));
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	
}
