package com.imdroid.sec_exapi.auth;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.imdroid.secapi.dto.ApiKey;
import com.imdroid.secapi.dto.ApiKeyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

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

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private ApiKeyMapper apiMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)   {
        String token = request.getHeader("Authorization");
        //如果不映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        // 执行认证
        if (StrUtil.isBlank(token)) {
            response.setStatus(401);
            return false;
        }
        // 获取 token 中的userId
        String apiKey;
        try {
            apiKey = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            response.setStatus(401);
            return false;
        }
        //根据token中的userid查询数据库
        QueryWrapper<ApiKey> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("apikey",apiKey);
        ApiKey api = apiMapper.selectOne(queryWrapper);
        if (api == null) {
            response.setStatus(401);
            return false;
        }
        // 用户密码加签验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(api.getSecret())).build();
        try{
            jwtVerifier.verify(token); // 验证token
        } catch (JWTVerificationException e) {
            response.setStatus(401);
            return false;
        }

        request.setAttribute("tenantId",api.getTenantid());
        return true;
    }
}