package cn.component.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import cn.constant.CommonConst;
import cn.pojo.vo.LoginUser;
import cn.service.token.JwtTokenService;
import cn.util.core.IsKit;

/**
* 自定义权限拦截器AuthenticationInterceptor，需实现HandlerInterceptor。
* 在preHandle中调用tokenUtils.getUserByToken(token)，获取到当前用户，
* 最后塞进request中
*/
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

	@Autowired
	private JwtTokenService service;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String token = request.getHeader("Authorization");
		LoginUser user = service.getLoginUser(token);
		if(IsKit.isNotNullOrEmpty(user)){
			request.setAttribute(CommonConst.CURRENT_USER, user);
		}
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
	}
}

