package com.persagy.calendar.aop;

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

import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.persagy.common.enums.ResponseCode;
import com.persagy.common.exception.BusinessException;
import com.persagy.common.utils.StringUtil;

import cn.hutool.http.HttpUtil;
import cn.hutool.http.useragent.Browser;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;

/**
 * 非浏览器请求直接拒绝
 * 
 * @version 1.0.0
 * @company persagy 
 * @author zhangqiankun
 * @date 2022年3月21日 下午6:27:39
 */
@Component
public class UserAgentInterceptor extends HandlerInterceptorAdapter {

	@Value("${calendar.person.center.url:http://127.0.0.1:8814}")
	private String personUrl; 
	
	@Value("${calendar.user.agent.browser:false}")
	private boolean isUserAgent; 
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (isUserAgent) {
			UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
			Browser browser = userAgent == null ? null : userAgent.getBrowser();
			if (browser == null || "Unknown".equalsIgnoreCase(browser.getName())) {
				throw new BusinessException("非法请求");
			}
			String token = request.getHeader("Authorization");
			JSONObject params = new JSONObject();
			params.put("token", token);
			
			String url = personUrl + "/user/checkToken";
			String responseStr = HttpUtil.createPost(url).body(params.toJSONString(),
	    			ContentType.APPLICATION_JSON.toString()).timeout(180*1000).execute().body();
			if (StringUtil.isBlank(responseStr)) {
				throw new BusinessException("token校验异常");
			}
			JSONObject parseObject = JSONObject.parseObject(responseStr);
			String code = parseObject.getString("respCode");
			if (!ResponseCode.A00000.getCode().equals(code)) {
				throw new BusinessException("token校验异常");
			}
		}
		return super.preHandle(request, response, handler);
	}
	
}
