monitor-ai/src/lib/permissions.ts

43 lines
1.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// src/lib/permissions.ts — RBAC 权限定义 + 检查函数
export const PERMISSIONS = [
{ key: 'dashboard:view', name: '查看仪表盘' },
{ key: 'services:view', name: '查看服务列表' },
{ key: 'services:manage', name: '管理服务' },
{ key: 'alerts:view', name: '查看告警历史' },
{ key: 'alerts:manage', name: '管理告警渠道' },
{ key: 'status_history:view', name: '查看状态历史' },
{ key: 'status_history:stats', name: '查看可用率统计' },
{ key: 'audit:view', name: '查看审计日志' },
{ key: 'users:view', name: '查看用户列表' },
{ key: 'users:manage', name: '管理用户角色' },
{ key: 'roles:manage', name: '管理角色权限' },
] as const
// 角色默认权限映射
export const ROLE_DEFAULT_PERMISSIONS: Record<string, string[]> = {
admin: PERMISSIONS.map(p => p.key),
editor: ['dashboard:view', 'services:view', 'alerts:view', 'status_history:view', 'status_history:stats'],
viewer: ['dashboard:view', 'services:view', 'status_history:view'],
}
// 检查角色是否拥有某项权限
export function hasPermission(role: string, permissionKey: string): boolean {
if (role === 'localadmin') return true
if (role === 'admin') return true // admin 拥有全部权限
const perms = ROLE_DEFAULT_PERMISSIONS[role]
return perms ? perms.includes(permissionKey) : false
}
// API 服务端权限检查(从 cookie 中读取 role
export function checkPermission(request: { cookies: { get(name: string): { value: string } | undefined } }, permissionKey: string): boolean {
const token = request.cookies.get('tlyq_session')?.value
if (!token) return false
try {
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString())
const role = payload.role || 'viewer'
return hasPermission(role, permissionKey)
} catch {
return false
}
}