package cn.reghao.tnb.common.auth;

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 java.lang.reflect.Method;

/**
 * @author reghao
 * @date 2023-07-18 15:17:35
 */
@Component
@Aspect
public class AuthUserAspect {
    @Pointcut("@annotation(cn.reghao.tnb.common.auth.AuthUser)")
    public void loginPointCut(){
    }

    @Around("loginPointCut()")
    public Object processMethod(ProceedingJoinPoint point) throws Throwable {
        Class<?> aClass = point.getTarget().getClass();
        MethodSignature ms = (MethodSignature)point.getSignature();
        Method method = aClass.getDeclaredMethod(ms.getName(),ms.getParameterTypes());

        AuthUser authUser = method.getAnnotation(AuthUser.class);
        boolean auth = authUser.value();
        LoginUser loginUser = UserContext.getLoginUser();
        if (auth && loginUser.getUserId() != -1) {
            boolean ret = loginUser.getRoles().contains(AccountRole.user.getValue());
            return point.proceed(point.getArgs());
        }

        throw new AuthException("接口需要认证后才可访问");
    }

    @Around("@within(authUser)")
    public Object processClass(ProceedingJoinPoint point, AuthUser authUser) throws Throwable {
        boolean auth = authUser.value();
        LoginUser loginUser = UserContext.getLoginUser();
        if (auth && loginUser.getUserId() != -1) {
            return point.proceed(point.getArgs());
        }

        throw new AuthException("接口需要认证后才可访问");
    }
}
