package com.mortals.xhx.busiz.security.filter;

import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.service.IAuthTokenService;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.web.interceptor.BaseInterceptor;
import com.mortals.xhx.base.framework.annotation.ApiUserAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

import static com.mortals.xhx.common.key.ErrorCode.TOKEN_AUTH_FAIL;
import static com.mortals.xhx.common.key.ErrorCode.TOKEN_AUTH_FAIL_CONTENT;
import static com.mortals.xhx.common.key.RedisKey.KEY_TOKEN_API_CACHE;

/**
 * api接口权限验证
 *
 * @author: zxfei
 * @date: 2022/4/11 15:50
 */
@Component
public class ApiSubmitInterceptor extends BaseInterceptor {

    @Autowired
    private IAuthTokenService authTokenService;
    @Autowired
    private ICacheService cacheService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            ApiUserAuth annotation = method.getAnnotation(ApiUserAuth.class);
            if (annotation != null) {
                //校验 校验路径是否允许
                if (!this.verifyApiUser(request)) {
                    JSONObject ret = new JSONObject();
                    ret.put("code", TOKEN_AUTH_FAIL);
                    ret.put("msg", TOKEN_AUTH_FAIL_CONTENT);
                    super.writeJsonResponse(response, 200, JSONObject.toJSONString(ret));
                    return false;
                }
            }
            return true;
        } else {
            return super.preHandle(request, response, handler);
        }
    }

    public boolean verifyApiUser(HttpServletRequest request) {
        String token = authTokenService.getToken(request);
        if (cacheService.exists(KEY_TOKEN_API_CACHE + token)) return true;
        return false;
    }
}
