package com.eitc.framework.interceptor.app;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.eitc.common.constant.Constants;
import com.eitc.common.constant.HttpStatus;
import com.eitc.common.utils.JWTUtil;
import com.eitc.common.utils.PatientBaseUtil;
import com.eitc.common.utils.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * JWTInterceptor
 *
 * @author mtx
 * @date: 2024/06/07 15:09
 */
@Component
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED);
        //获取请求头里的token
        String token = request.getHeader(Constants.TOKEN);

        if (token == null || "".equals(token) || "NULL".equalsIgnoreCase(token)) {
            map.put("msg", "未授权");
        } else {
            //验证
            String userId = null;
            try {
                userId = JWTUtil.getAppUserId();
            } catch (Exception e) {
                map.put("code", HttpStatus.FORBIDDEN);
                map.put("msg", "token无效");
            }
            if (StringUtils.isNull(userId)) {
                map.put("code", HttpStatus.FORBIDDEN);
                map.put("msg", "无效签名");
            } else {
                try {
                    String secretKey = PatientBaseUtil.getSecretKey(userId);
                    JWTUtil.verify(token, secretKey); //验证令牌
                    return true;
                    //签名异常
                } catch (SignatureVerificationException e) {
                    map.put("code", HttpStatus.FORBIDDEN);
                    map.put("msg", "无效签名");
                    //过期异常
                } catch (TokenExpiredException e) {
                    map.put("code", HttpStatus.FORBIDDEN);
                    map.put("msg", "token过期");
                    //算法不匹配
                } catch (AlgorithmMismatchException e) {
                    map.put("code", HttpStatus.FORBIDDEN);
                    map.put("msg", "token算法不一致");
                    //总异常
                } catch (Exception e) {
                    map.put("code", HttpStatus.FORBIDDEN);
                    map.put("msg", "token无效");
                }
            }
        }

        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
