|
|
@@ -0,0 +1,66 @@
|
|
|
+package common.interceptor.role;
|
|
|
+
|
|
|
+import com.jfinal.aop.Interceptor;
|
|
|
+import com.jfinal.aop.Invocation;
|
|
|
+import com.jfinal.core.Controller;
|
|
|
+import com.jfinal.kit.StrKit;
|
|
|
+import common.utils.http.MyRet;
|
|
|
+
|
|
|
+public class RoleInterceptor implements Interceptor {
|
|
|
+ // Session 中存储用户角色的 key
|
|
|
+ private static final String SESSION_ROLE_KEY = "role";
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void intercept(Invocation inv) {
|
|
|
+ // 1. 获取方法上的 RequiredRole 注解
|
|
|
+ RequiredRoleInterface requiredRole = inv.getMethod().getAnnotation(RequiredRoleInterface.class);
|
|
|
+
|
|
|
+ // 如果方法没有 RequiredRole 注解,表示不需要权限检查,直接放行
|
|
|
+ if (requiredRole == null) {
|
|
|
+ inv.invoke();
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 2. 获取允许的角色数组
|
|
|
+ int[] allowedRoles = requiredRole.value();
|
|
|
+ Controller controller = inv.getController();
|
|
|
+
|
|
|
+ // 3. 从 Session 中获取当前用户的角色
|
|
|
+ String currentUserRoleStr = controller.getSessionAttr(SESSION_ROLE_KEY);
|
|
|
+ Integer currentUserRole = null;
|
|
|
+ // 判断是否为空,不为空则尝试转换为 Integer
|
|
|
+ if (StrKit.notBlank(currentUserRoleStr)) {
|
|
|
+ try {
|
|
|
+ currentUserRole = Integer.parseInt(currentUserRoleStr);
|
|
|
+ } catch (NumberFormatException e) {
|
|
|
+ // 如果 Session 中的 role 字符串无法转换为数字,说明数据有问题
|
|
|
+ controller.renderJson(MyRet.fail("权限校验失败:用户角色数据异常"));
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // 4. 权限校验逻辑
|
|
|
+ // 如果用户未登录(Session 中没有 role)
|
|
|
+ if (currentUserRole == null) {
|
|
|
+ controller.renderJson(MyRet.fail("权限不足:用户未登录或会话已过期"));
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 检查当前用户的角色ID是否在允许的角色数组中
|
|
|
+ boolean hasPermission = false;
|
|
|
+ for (int allowedRole : allowedRoles) {
|
|
|
+ if (currentUserRole == allowedRole) {
|
|
|
+ hasPermission = true;
|
|
|
+ break; // 找到匹配的角色,跳出循环
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // 5. 根据权限判断是否放行
|
|
|
+ if (hasPermission) {
|
|
|
+ inv.invoke(); // 有权限,放行请求
|
|
|
+ } else {
|
|
|
+ // 没有权限,返回错误信息
|
|
|
+ controller.renderJson(MyRet.fail("权限不足:当前角色无权访问此接口").setCode(MyRet.CODE_NO_POWER));
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|