package cn.superdesk.uniorder.interceptor.security;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.superdesk.uniorder.common.constants.BaseMessageConf;
import cn.superdesk.uniorder.common.constants.ResponseResultConstants;
import cn.superdesk.uniorder.common.rest.response.AnResponseStreamUtils;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.rest.response.ResponseResultOuterUtils;
import cn.superdesk.uniorder.common.security.JwtUtil;
import cn.superdesk.uniorder.common.security.dto.LoginSysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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


/**
 * @Description: JWT
 * @Author: linjinyu 补充 修改
 * @CreateDate: 4/29/20 5:45 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 4/29/20 5:45 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
public class JwtInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		String token      = request.getHeader("token");
		String JSESSIONID = request.getRequestedSessionId();

		log.info("preHandle \n-> request::session -> {} \n-> request::token -> {} \n", JSESSIONID, token);

		if (StrUtil.isBlank(token)) {

			R<String> rt = ResponseResultOuterUtils.createErrorResult(ResponseResultConstants.NO_OPERATION_AUTHORITY, BaseMessageConf.RESTAPI_NO_PRIVILEGE);
			AnResponseStreamUtils.outputJson(JSONUtil.toJsonStr(rt), response);

			return false;
		}

		LoginSysUser loginSysUser = JwtUtil.getLoginSysUser(token);

		// 验证是否合法
		if (ObjectUtil.isNotNull(loginSysUser)) {

//			Object redisToken = redisService.hgetKey(RedisKeyPrefix.TOKEN_CACHE.getKey() + ":" + userName, "token");
//			if(redisToken != null && !redisToken.toString().equals(authHeader)) {
//				throw new MyException(ExceptionMsg.TOKEN_EXPIRED.getCode(),ExceptionMsg.TOKEN_EXPIRED.getMsg());
//			}

			return true;

		} else {

			R<String> rt = ResponseResultOuterUtils.createErrorResult(ResponseResultConstants.NO_OPERATION_AUTHORITY, BaseMessageConf.INVALID_TOKEN);
			AnResponseStreamUtils.outputJson(JSONUtil.toJsonStr(rt), response);

			return false;
		}

	}


}
