| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| import { useState, useEffect } from 'react'; |
| import { API } from '../../helpers'; |
|
|
| |
| |
| |
| |
| export const useUserPermissions = () => { |
| const [permissions, setPermissions] = useState(null); |
| const [loading, setLoading] = useState(true); |
| const [error, setError] = useState(null); |
|
|
| |
| const loadPermissions = async () => { |
| try { |
| setLoading(true); |
| setError(null); |
| const res = await API.get('/api/user/self'); |
| if (res.data.success) { |
| const userPermissions = res.data.data.permissions; |
| setPermissions(userPermissions); |
| console.log('用户权限加载成功:', userPermissions); |
| } else { |
| setError(res.data.message || '获取权限失败'); |
| console.error('获取权限失败:', res.data.message); |
| } |
| } catch (error) { |
| setError('网络错误,请重试'); |
| console.error('加载用户权限异常:', error); |
| } finally { |
| setLoading(false); |
| } |
| }; |
|
|
| useEffect(() => { |
| loadPermissions(); |
| }, []); |
|
|
| |
| const hasSidebarSettingsPermission = () => { |
| return permissions?.sidebar_settings === true; |
| }; |
|
|
| |
| const isSidebarSectionAllowed = (sectionKey) => { |
| if (!permissions?.sidebar_modules) return true; |
| const sectionPerms = permissions.sidebar_modules[sectionKey]; |
| return sectionPerms !== false; |
| }; |
|
|
| |
| const isSidebarModuleAllowed = (sectionKey, moduleKey) => { |
| if (!permissions?.sidebar_modules) return true; |
| const sectionPerms = permissions.sidebar_modules[sectionKey]; |
|
|
| |
| if (sectionPerms === false) return false; |
|
|
| |
| if (sectionPerms && sectionPerms[moduleKey] === false) return false; |
|
|
| return true; |
| }; |
|
|
| |
| const getAllowedSidebarSections = () => { |
| if (!permissions?.sidebar_modules) return []; |
|
|
| return Object.keys(permissions.sidebar_modules).filter((sectionKey) => |
| isSidebarSectionAllowed(sectionKey), |
| ); |
| }; |
|
|
| |
| const getAllowedSidebarModules = (sectionKey) => { |
| if (!permissions?.sidebar_modules) return []; |
| const sectionPerms = permissions.sidebar_modules[sectionKey]; |
|
|
| if (sectionPerms === false) return []; |
| if (!sectionPerms || typeof sectionPerms !== 'object') return []; |
|
|
| return Object.keys(sectionPerms).filter( |
| (moduleKey) => |
| moduleKey !== 'enabled' && sectionPerms[moduleKey] === true, |
| ); |
| }; |
|
|
| return { |
| permissions, |
| loading, |
| error, |
| loadPermissions, |
| hasSidebarSettingsPermission, |
| isSidebarSectionAllowed, |
| isSidebarModuleAllowed, |
| getAllowedSidebarSections, |
| getAllowedSidebarModules, |
| }; |
| }; |
|
|
| export default useUserPermissions; |
|
|