package com.yj.earth.aspect; import cn.dev33.satoken.stp.StpUtil; import com.yj.earth.annotation.RoleAccess; import com.yj.earth.business.domain.User; import com.yj.earth.business.domain.Role; import com.yj.earth.business.service.UserService; import com.yj.earth.business.service.RoleService; import com.yj.earth.common.util.ApiResponse; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.lang.reflect.Method; /** * 角色访问控制切面 */ @Aspect @Component public class RoleAccessAspect { @Resource private UserService userService; @Resource private RoleService roleService; /** * 环绕通知、验证角色权限 */ @Around("@annotation(com.yj.earth.annotation.RoleAccess)") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { // 获取当前登录用户ID if (!StpUtil.isLogin()) { return ApiResponse.failure("请先登录"); } String userId = StpUtil.getLoginIdAsString(); // 获取用户信息 User user = userService.getById(userId); if (user == null) { return ApiResponse.failure("用户不存在"); } // 获取用户角色信息 Role role = roleService.getById(user.getRoleId()); if (role == null) { return ApiResponse.failure("用户角色不存在"); } // 获取注解信息 MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); RoleAccess roleAccess = method.getAnnotation(RoleAccess.class); String[] allowedRoles = roleAccess.roleNames(); // 验证角色是否有权限 boolean hasPermission = false; for (String roleName : allowedRoles) { if (roleName.equals(role.getRoleName())) { hasPermission = true; break; } } if (!hasPermission) { return ApiResponse.failure("没有访问权限、需要角色: " + String.join(",", allowedRoles)); } // 有权限、执行原方法 return joinPoint.proceed(); } }