/**
 * Copyright &copy; 2012-2013 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.cftech.sys.interceptor;

import com.cftech.core.util.JWTUtils;
import com.cftech.core.util.SpringContextHolder;
import com.cftech.core.util.StringUtils;
import com.cftech.sys.dao.LogMapper;
import com.cftech.sys.model.Log;
import com.cftech.sys.model.User;
import com.cftech.sys.security.UserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * JWT 移动端 拦截器
 * Jasper huang 2018/06/05
 */
public class JWTInterceptor implements HandlerInterceptor {

	protected final Logger logger = LoggerFactory
			.getLogger(JWTInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
			Object handler) throws Exception {
		if(request.getRequestURI().endsWith("/mobile/wxjs/oauth"))
		{
			return true;
		}
		String signature = request.getParameter("signature");
		if(StringUtils.isNotBlank(signature))
		{
			int status =  JWTUtils.verifyJWT(signature,request);
			if(status==0)
			{
				return true;
			}else if(status==-1)
			{
				response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
				return false;
			}else
			{
				response.sendError(HttpServletResponse.SC_FORBIDDEN);
				return false;
			}
		}else
		{
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return false;
		}
	}
	@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 {
	}

}
