package com.ibeetl.admin.core.conf.springmvc.interceptor;

import com.ibeetl.admin.core.service.CoreUserService;
import com.ibeetl.admin.core.util.RequestContextThreadLocal;
import com.ibeetl.admin.core.util.JoseJwtUtil;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

public class SessionInterceptor implements HandlerInterceptor {

  CoreUserService userService;

  public SessionInterceptor(CoreUserService userService) {
    this.userService = userService;
  }

  @Override
  public boolean preHandle(
      HttpServletRequest request, HttpServletResponse response, Object handler) {
    String token = RequestContextThreadLocal.getAuthorization();
    boolean isExpiration = JoseJwtUtil.verifyJwtJson(token);
    if (isExpiration) {
      /*验证失败，无效jwt*/
      response.setStatus(HttpStatus.UNAUTHORIZED.value());
      return false;
    } else {
      token = JoseJwtUtil.refreshIssuedAtTime(token);
      Map<String, Object> claimsMap = JoseJwtUtil.parsePayload(token);
      RequestContextThreadLocal.reset(claimsMap.get("uid"));
      response.setHeader(HttpHeaders.AUTHORIZATION, token);
    }
    return true;
  }
}
