package com.backendsys.config.Interceptor;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class PreAuthorizeInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 判断方法上是否标注了 @PreAuthorize 注解
        if (method.isAnnotationPresent(PreAuthorize.class)) {
            // PreAuthorize preAuthorize = method.getAnnotation(PreAuthorize.class);
            // String value = preAuthorize.value();

            // out: @sr.hasPermission('1.3')

            // 判断权限表达式中是否包含"/api/public"
            String uri = request.getRequestURI(); // 获取当前请求的 URI
            if (uri.contains("/api/public")) {
                throw new Exception("访问拒绝 (公共接口不应出现权限注解)");
            }
        }
        return true;
    }
}