001package top.cenze.utils.aspect;
002
003import cn.hutool.core.util.ObjectUtil;
004import com.alibaba.fastjson.JSON;
005import lombok.extern.slf4j.Slf4j;
006import org.aspectj.lang.JoinPoint;
007import org.aspectj.lang.annotation.Before;
008import org.aspectj.lang.annotation.Pointcut;
009import org.aspectj.lang.reflect.MethodSignature;
010import org.springframework.web.context.request.RequestContextHolder;
011import org.springframework.web.context.request.ServletRequestAttributes;
012import top.cenze.utils.aop.ApiAuth;
013import top.cenze.utils.plugins.ApiPlugin;
014
015import javax.servlet.http.HttpServletRequest;
016import java.lang.reflect.Method;
017
018/**
019 * @desc: 接口鉴权切面
020 * @author: chengze
021 * @createByDate: 2023/12/29 11:21
022 */
023@Slf4j
024public abstract class ApiAuthAspect extends ApiPlugin {
025    @Pointcut("@annotation(top.cenze.utils.aop.ApiAuth)")
026    public void authPointcut() {}
027
028    @Before("authPointcut()")
029    public void authBefore(JoinPoint joinPoint) throws Exception {
030        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
031        Method method = methodSignature.getMethod();
032        ApiAuth apiAuth = method.getAnnotation(ApiAuth.class);
033        if (ObjectUtil.isNull(apiAuth)) {
034            return;
035        }
036        log.info("authBefore apiAuth: {}", JSON.toJSONString(apiAuth));
037
038        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
039        // 此处无需判断 requestAttributes 是否为空
040        HttpServletRequest request = requestAttributes.getRequest();
041        // 获取请求头中的 Authorization 信息
042//        String authorization = request.getHeader("Authorization");
043
044        // 当前请求鉴权是否通过
045        if (apiAuth.chkAuth() && !auth(request, true)) {
046            throw new Exception("未鉴权的访问");
047        }
048
049        // 当前请求访问次数超限制
050        if (apiAuth.chkLimit() && exceedLimitCount(request)) {
051            throw new Exception("超过请求次数,请稍后再试");
052        }
053    }
054}