permission.md 10.3 KB

权限管理

Venus Admin 提供了完善的权限管理系统,支持基于角色的访问控制(RBAC)和细粒度的权限控制。

权限设计

权限系统采用 RBAC(Role-Based Access Control)模型:

用户(User) -> 角色(Role) -> 权限(Permission)
  • 用户:系统的使用者
  • 角色:用户的分类,如管理员、普通用户等
  • 权限:具体的操作权限,如查看用户列表、编辑用户等

权限配置

路由权限

在路由的 meta 中配置所需权限:

{
  path: '/system/user',
  name: 'SystemUser',
  component: () => import('@/views/system/user/index.vue'),
  meta: {
    title: '用户管理',
    icon: 'lucide:users',
    authority: ['system:user:view'], // 需要的权限码
  },
}

按钮权限

使用指令或组件控制按钮的显示:

<template>
  <!-- 使用指令 -->
  <button v-auth="'system:user:add'">新增用户</button>

  <!-- 使用多个权限(满足任一即可) -->
  <button v-auth="['system:user:add', 'system:user:edit']">操作</button>

  <!-- 使用组件 -->
  <Auth :authority="'system:user:add'">
    <button>新增用户</button>
  </Auth>
</template>

权限指令

v-auth 指令

// src/directives/auth.ts
import type { Directive } from 'vue';
import { useAuthStore } from '@/store/modules/auth';

export const auth: Directive = {
  mounted(el, binding) {
    const { value } = binding;
    const authStore = useAuthStore();

    if (!value) return;

    const authorities = Array.isArray(value) ? value : [value];
    const hasPermission = authStore.hasAuthority(authorities);

    if (!hasPermission) {
      el.parentNode?.removeChild(el);
    }
  },
};

注册指令

// src/main.ts
import { auth } from '@/directives/auth';

app.directive('auth', auth);

权限组件

Auth 组件

<!-- src/components/Auth/index.vue -->
<template>
  <slot v-if="hasPermission" />
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { useAuthStore } from '@/store/modules/auth';

interface Props {
  authority: string | string[];
}

const props = defineProps<Props>();

const authStore = useAuthStore();

const hasPermission = computed(() => {
  const authorities = Array.isArray(props.authority) 
    ? props.authority 
    : [props.authority];

  return authStore.hasAuthority(authorities);
});
</script>

使用示例

<template>
  <div>
    <Auth :authority="'system:user:view'">
      <div>有权限才显示的内容</div>
    </Auth>

    <Auth :authority="['system:user:add', 'system:user:edit']">
      <button>操作按钮</button>
    </Auth>
  </div>
</template>

权限 Store

定义权限 Store

// src/store/modules/auth.ts
import { defineStore } from 'pinia';

interface AuthState {
  // 用户信息
  userInfo: UserInfo | null;
  // 角色列表
  roles: string[];
  // 权限列表
  authorities: string[];
  // 是否已加载动态路由
  isDynamicRouteAdded: boolean;
}

export const useAuthStore = defineStore('auth', {
  state: (): AuthState => ({
    userInfo: null,
    roles: [],
    authorities: [],
    isDynamicRouteAdded: false,
  }),

  getters: {
    // 是否已登录
    isLoggedIn: (state) => !!state.userInfo,

    // 获取用户信息
    getUserInfo: (state) => state.userInfo,

    // 获取角色列表
    getRoles: (state) => state.roles,

    // 获取权限列表
    getAuthorities: (state) => state.authorities,
  },

  actions: {
    // 设置用户信息
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo;
    },

    // 设置角色
    setRoles(roles: string[]) {
      this.roles = roles;
    },

    // 设置权限
    setAuthorities(authorities: string[]) {
      this.authorities = authorities;
    },

    // 检查是否有权限
    hasAuthority(authority: string | string[]): boolean {
      const authorities = Array.isArray(authority) ? authority : [authority];

      // 超级管理员拥有所有权限
      if (this.roles.includes('super-admin')) {
        return true;
      }

      // 检查是否有任一权限
      return authorities.some(auth => this.authorities.includes(auth));
    },

    // 检查是否有角色
    hasRole(role: string | string[]): boolean {
      const roles = Array.isArray(role) ? role : [role];
      return roles.some(r => this.roles.includes(r));
    },

    // 获取用户路由
    async fetchUserRoutes() {
      const { data } = await getUserRoutes();
      return data;
    },

    // 登录
    async login(credentials: LoginCredentials) {
      const { data } = await loginApi(credentials);

      this.setUserInfo(data.userInfo);
      this.setRoles(data.roles);
      this.setAuthorities(data.authorities);

      return data;
    },

    // 登出
    async logout() {
      await logoutApi();
      this.reset();
    },

    // 重置状态
    reset() {
      this.userInfo = null;
      this.roles = [];
      this.authorities = [];
      this.isDynamicRouteAdded = false;
    },
  },

  persist: {
    key: 'auth',
    paths: ['userInfo', 'roles', 'authorities'],
  },
});

路由权限控制

权限守卫

// src/router/guard/permission.ts
import { Router } from 'vue-router';
import { useAuthStore } from '@/store/modules/auth';

export function createPermissionGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    const authStore = useAuthStore();

    // 白名单路由,直接放行
    const whiteList = ['/login', '/register', '/404', '/403'];
    if (whiteList.includes(to.path)) {
      next();
      return;
    }

    // 检查是否登录
    if (!authStore.isLoggedIn) {
      next({
        path: '/login',
        query: { redirect: to.fullPath },
      });
      return;
    }

    // 加载动态路由
    if (!authStore.isDynamicRouteAdded) {
      try {
        const routes = await authStore.fetchUserRoutes();
        routes.forEach(route => {
          router.addRoute(route);
        });
        authStore.isDynamicRouteAdded = true;

        // 重新进入目标路由
        next({ ...to, replace: true });
        return;
      } catch (error) {
        console.error('加载路由失败', error);
        authStore.reset();
        next('/login');
        return;
      }
    }

    // 检查路由权限
    if (to.meta.authority) {
      const hasPermission = authStore.hasAuthority(to.meta.authority as string[]);
      if (!hasPermission) {
        next('/403');
        return;
      }
    }

    next();
  });
}

API 权限控制

请求拦截器

// src/api/request.ts
import axios from 'axios';
import { useAuthStore } from '@/store/modules/auth';

const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000,
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const authStore = useAuthStore();
    const token = authStore.userInfo?.token;

    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 未登录或 token 过期
          const authStore = useAuthStore();
          authStore.reset();
          window.location.href = '/login';
          break;
        case 403:
          // 无权限
          window.location.href = '/403';
          break;
        default:
          break;
      }
    }
    return Promise.reject(error);
  },
);

export default request;

组合式 API

useAuth

// src/composables/useAuth.ts
import { computed } from 'vue';
import { useAuthStore } from '@/store/modules/auth';

export function useAuth() {
  const authStore = useAuthStore();

  // 是否已登录
  const isLoggedIn = computed(() => authStore.isLoggedIn);

  // 用户信息
  const userInfo = computed(() => authStore.userInfo);

  // 检查权限
  const hasAuthority = (authority: string | string[]) => {
    return authStore.hasAuthority(authority);
  };

  // 检查角色
  const hasRole = (role: string | string[]) => {
    return authStore.hasRole(role);
  };

  // 登录
  const login = async (credentials: LoginCredentials) => {
    return await authStore.login(credentials);
  };

  // 登出
  const logout = async () => {
    return await authStore.logout();
  };

  return {
    isLoggedIn,
    userInfo,
    hasAuthority,
    hasRole,
    login,
    logout,
  };
}

使用示例

<script setup lang="ts">
import { useAuth } from '@/composables/useAuth';

const { userInfo, hasAuthority, hasRole } = useAuth();

// 检查权限
const canAdd = hasAuthority('system:user:add');
const canEdit = hasAuthority('system:user:edit');

// 检查角色
const isAdmin = hasRole('admin');
</script>

<template>
  <div>
    <div>用户名:{{ userInfo?.username }}</div>

    <button v-if="canAdd">新增</button>
    <button v-if="canEdit">编辑</button>

    <div v-if="isAdmin">
      管理员专属内容
    </div>
  </div>
</template>

权限最佳实践

1. 权限粒度

权限码建议采用三段式命名:模块:功能:操作

system:user:view    # 查看用户
system:user:add     # 新增用户
system:user:edit    # 编辑用户
system:user:delete  # 删除用户

2. 超级管理员

超级管理员应该拥有所有权限,无需配置具体权限码:

hasAuthority(authority: string | string[]): boolean {
  // 超级管理员拥有所有权限
  if (this.roles.includes('super-admin')) {
    return true;
  }

  // 其他用户检查权限
  return authorities.some(auth => this.authorities.includes(auth));
}

3. 前后端权限统一

前后端使用相同的权限码,确保权限的一致性。

4. 权限缓存

将用户权限缓存到本地,避免频繁请求:

persist: {
  key: 'auth',
  paths: ['userInfo', 'roles', 'authorities'],
}

下一步