liusuyi
2025-02-20 35f1a08b31531d971169403978cddf3328accb26
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.ard.tianyu.aspect;
 
import com.ard.common.exception.NoPermissionException;
import com.ard.common.utils.SecurityUtils;
import com.ard.tianyu.service.impl.UavControlManager;
import lombok.extern.slf4j.Slf4j;
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.Field;
import java.lang.reflect.Method;
 
 
/**
 * 控制权限切面
 *
 * @author liusuyi
 */
@Aspect
@Component
@Slf4j
public class ControlAuthorityAspect {
 
    @Pointcut("@annotation(com.ard.tianyu.aspect.annotation.CheckControlAuthority)")
    public void dsPointCut() {
 
    }
 
    @Around("dsPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Boolean result = controlScopeFilter(point);
        if (result) {
            log.debug("已获取无人机控制权--{}", method.getName());
            // 执行目标方法
            return point.proceed();
        }
        log.debug("未获取无人机控制权--{}", method.getName());
        throw new NoPermissionException("未获取无人机控制权");
    }
 
    /**
     * 操控判断逻辑
     *
     * @param joinPoint 切点
     */
    public Boolean controlScopeFilter(ProceedingJoinPoint joinPoint) {
        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        // 使用反射获取参数中的 boxSn
        for (Object arg : args) {
            String boxSn = getBoxSn(arg);
            if (boxSn != null) {
                //判断无人机控制者是否为当前登录用户
                Long currentControllerId = UavControlManager.droneControlMap.get(boxSn);
                if (currentControllerId != null && currentControllerId.equals(SecurityUtils.getUserId())) {
                    return true;
                }
            }
        }
        return false;
    }
 
    // 通过反射获取对象中的无人机boxSn字段
    public static String getBoxSn(Object dto) {
        try {
            // 获取类的所有字段
            Field[] fields = dto.getClass().getDeclaredFields();
            for (Field field : fields) {
                // 设置字段可访问
                field.setAccessible(true);
 
                // 判断是否是 boxSn 字段
                if ("boxSn".equals(field.getName())) {
                    // 获取并返回 droneId 的值
                    return (String) field.get(dto);
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null; // 如果没有找到 droneId 字段,返回 null
    }
}