package com.ruoyi.system.utils;

import com.ruoyi.common.core.domain.AjaxResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: ZouTiancong
 * @Date: 2022/05/23/22:39
 * @Description:
 */
@Component
@Aspect
public class AuthAspect {

    private static HttpServletRequest request;
    @Resource
    public void setHttpServletRequest(HttpServletRequest request) {
        AuthAspect.request = request;
    }


    @Pointcut("@annotation(com.ruoyi.system.utils.Auth)")
    private void authPointcut() {
    }

    @Around("authPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法签名信息从而获取方法名和参数类型
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

        // 获取目标方法对象上注解中的属性值
        Auth auth = methodSignature.getMethod().getAnnotation(Auth.class);

        // 校验签名
        if (auth.token()) {
            boolean token = JwtUtil.verify(request.getHeader("token"));
            // 如果token校验失败返回
            if (!token) {
                return AjaxResult.error(401,"token已过期，请重新登录！");
            }
        }
        return joinPoint.proceed();
    }
}
