5.2 权限继承机制原来是这样实现的?

2 阅读12分钟

5.2 震撼发布!权限继承机制原来是这样实现的?

在上一节中,我们介绍了RBAC权限模型的基本实现。在实际应用中,权限继承机制是RBAC模型中一个非常重要的特性,它允许我们建立角色之间的层次关系,简化权限管理。本节将深入探讨权限继承机制的实现原理,并提供完整的Go代码示例。

权限继承的核心概念

权限继承机制基于角色层次结构,允许子角色自动继承父角色的所有权限。这种设计模式具有以下优势:

  1. 简化权限分配:无需为每个角色重复分配相同的权限
  2. 提高可维护性:当权限需求变化时,只需在父角色中调整
  3. 支持组织结构:能够很好地映射现实中的组织层级关系
  4. 减少冗余:避免权限配置的重复和不一致
graph TD
    A[超级管理员] --> B(部门管理员)
    B --> C[普通员工]
    D[财务管理员] --> E(财务专员)
    E --> F[出纳员]
    
    style A fill:#ff9999
    style B fill:#ffcc99
    style C fill:#ffff99
    style D fill:#99ccff
    style E fill:#99ff99
    style F fill:#ccffcc

权限继承的实现原理

权限继承的实现主要涉及以下几个方面:

  1. 角色层次结构的建立:定义角色之间的父子关系
  2. 权限的递归继承:子角色自动获得父角色的所有权限
  3. 循环依赖检测:防止角色之间形成循环继承
  4. 权限检查优化:高效地检查用户是否具有指定权限

高级RBAC权限继承系统实现

让我们通过Go语言来实现一个支持复杂权限继承的RBAC系统:

// AdvancedRBACService 高级RBAC服务
type AdvancedRBACService struct {
    users       map[string]*User
    roles       map[string]*AdvancedRole
    permissions map[string]*Permission
    userRoles   map[string][]string
    roleGraph   *RoleGraph // 角色关系图
    cache       *PermissionCache // 权限缓存
    mutex       sync.RWMutex
}

// AdvancedRole 高级角色(支持继承和约束)
type AdvancedRole struct {
    ID              string                 `json:"id"`
    Name            string                 `json:"name"`
    Description     string                 `json:"description"`
    Permissions     []string               `json:"permissions"`
    ParentRoles     []string               `json:"parent_roles"`
    ChildRoles      []string               `json:"child_roles"`
    Constraints     []RoleConstraint       `json:"constraints"`
    Active          bool                   `json:"active"`
    CreatedAt       time.Time              `json:"created_at"`
    UpdatedAt       time.Time              `json:"updated_at"`
}

// RoleConstraint 角色约束
type RoleConstraint struct {
    Type       string                 `json:"type"`
    Parameters map[string]interface{} `json:"parameters"`
    Enabled    bool                   `json:"enabled"`
}

// RoleGraph 角色关系图
type RoleGraph struct {
    // 角色之间的直接父子关系
    parents map[string]map[string]bool // child -> parents
    children map[string]map[string]bool // parent -> children
    
    // 角色继承的权限缓存
    rolePermissions map[string]map[string]bool // role -> permissions
    
    // 循环依赖检测
    visiting map[string]bool
}

// NewRoleGraph 创建角色关系图
func NewRoleGraph() *RoleGraph {
    return &RoleGraph{
        parents:         make(map[string]map[string]bool),
        children:        make(map[string]map[string]bool),
        rolePermissions: make(map[string]map[string]bool),
        visiting:        make(map[string]bool),
    }
}

// AddParentChildRelation 添加父子角色关系
func (rg *RoleGraph) AddParentChildRelation(parentID, childID string) error {
    // 检查是否会形成循环依赖
    if rg.wouldCreateCycle(parentID, childID) {
        return fmt.Errorf("adding this relation would create a cycle")
    }
    
    // 添加父子关系
    if rg.parents[childID] == nil {
        rg.parents[childID] = make(map[string]bool)
    }
    rg.parents[childID][parentID] = true
    
    // 添加子父关系
    if rg.children[parentID] == nil {
        rg.children[parentID] = make(map[string]bool)
    }
    rg.children[parentID][childID] = true
    
    // 使相关缓存失效
    rg.invalidateCache(childID)
    
    return nil
}

// RemoveParentChildRelation 移除父子角色关系
func (rg *RoleGraph) RemoveParentChildRelation(parentID, childID string) {
    // 移除父子关系
    if rg.parents[childID] != nil {
        delete(rg.parents[childID], parentID)
        if len(rg.parents[childID]) == 0 {
            delete(rg.parents, childID)
        }
    }
    
    // 移除子父关系
    if rg.children[parentID] != nil {
        delete(rg.children[parentID], childID)
        if len(rg.children[parentID]) == 0 {
            delete(rg.children, parentID)
        }
    }
    
    // 使相关缓存失效
    rg.invalidateCache(childID)
}

// wouldCreateCycle 检查是否会形成循环依赖
func (rg *RoleGraph) wouldCreateCycle(parentID, childID string) bool {
    // 如果parentID已经是childID的子角色,则会形成循环
    return rg.isDescendant(parentID, childID)
}

// isDescendant 检查descendant是否是ancestor的后代
func (rg *RoleGraph) isDescendant(ancestor, descendant string) bool {
    if ancestor == descendant {
        return true
    }
    
    // 防止无限递归
    if rg.visiting[descendant] {
        return false
    }
    
    rg.visiting[descendant] = true
    defer delete(rg.visiting, descendant)
    
    // 检查直接子角色
    if children, exists := rg.children[descendant]; exists {
        for child := range children {
            if rg.isDescendant(ancestor, child) {
                return true
            }
        }
    }
    
    return false
}

// invalidateCache 使缓存失效
func (rg *RoleGraph) invalidateCache(roleID string) {
    // 使当前角色的权限缓存失效
    delete(rg.rolePermissions, roleID)
    
    // 使所有子角色的权限缓存失效
    rg.invalidateChildrenCache(roleID)
}

// invalidateChildrenCache 使子角色缓存失效
func (rg *RoleGraph) invalidateChildrenCache(roleID string) {
    if children, exists := rg.children[roleID]; exists {
        for child := range children {
            delete(rg.rolePermissions, child)
            rg.invalidateChildrenCache(child)
        }
    }
}

// GetAncestors 获取所有祖先角色
func (rg *RoleGraph) GetAncestors(roleID string) []string {
    ancestors := make(map[string]bool)
    rg.collectAncestors(roleID, ancestors)
    
    result := make([]string, 0, len(ancestors))
    for ancestor := range ancestors {
        result = append(result, ancestor)
    }
    
    return result
}

// collectAncestors 收集祖先角色
func (rg *RoleGraph) collectAncestors(roleID string, ancestors map[string]bool) {
    if parents, exists := rg.parents[roleID]; exists {
        for parent := range parents {
            if !ancestors[parent] {
                ancestors[parent] = true
                rg.collectAncestors(parent, ancestors)
            }
        }
    }
}

// GetDescendants 获取所有后代角色
func (rg *RoleGraph) GetDescendants(roleID string) []string {
    descendants := make(map[string]bool)
    rg.collectDescendants(roleID, descendants)
    
    result := make([]string, 0, len(descendants))
    for descendant := range descendants {
        result = append(result, descendant)
    }
    
    return result
}

// collectDescendants 收集后代角色
func (rg *RoleGraph) collectDescendants(roleID string, descendants map[string]bool) {
    if children, exists := rg.children[roleID]; exists {
        for child := range children {
            if !descendants[child] {
                descendants[child] = true
                rg.collectDescendants(child, descendants)
            }
        }
    }
}

// GetRolePermissions 获取角色的所有权限(包括继承的权限)
func (rg *RoleGraph) GetRolePermissions(roleID string, directPermissions []string) []string {
    // 检查缓存
    if cached, exists := rg.rolePermissions[roleID]; exists {
        permissions := make([]string, 0, len(cached))
        for perm := range cached {
            permissions = append(permissions, perm)
        }
        return permissions
    }
    
    // 收集权限
    permissionSet := make(map[string]bool)
    
    // 添加直接权限
    for _, perm := range directPermissions {
        permissionSet[perm] = true
    }
    
    // 添加继承的权限
    ancestors := rg.GetAncestors(roleID)
    // 注意:这里需要从外部获取祖先角色的直接权限
    
    // 缓存结果
    rg.rolePermissions[roleID] = permissionSet
    
    // 转换为切片
    permissions := make([]string, 0, len(permissionSet))
    for perm := range permissionSet {
        permissions = append(permissions, perm)
    }
    
    return permissions
}

// PermissionCache 权限缓存
type PermissionCache struct {
    cache map[string]map[string]bool // userID -> permissions
    ttl   time.Duration
    mutex sync.RWMutex
}

// NewPermissionCache 创建权限缓存
func NewPermissionCache(ttl time.Duration) *PermissionCache {
    return &PermissionCache{
        cache: make(map[string]map[string]bool),
        ttl:   ttl,
    }
}

// CheckPermission 检查权限
func (pc *PermissionCache) CheckPermission(userID, permission string) (bool, bool) {
    pc.mutex.RLock()
    defer pc.mutex.RUnlock()
    
    if userPermissions, exists := pc.cache[userID]; exists {
        if hasPermission, permExists := userPermissions[permission]; permExists {
            return hasPermission, true
        }
    }
    
    return false, false
}

// SetPermission 设置权限
func (pc *PermissionCache) SetPermission(userID, permission string, hasPermission bool) {
    pc.mutex.Lock()
    defer pc.mutex.Unlock()
    
    if pc.cache[userID] == nil {
        pc.cache[userID] = make(map[string]bool)
    }
    
    pc.cache[userID][permission] = hasPermission
    
    // 设置过期时间(简化实现,实际应使用更精确的过期机制)
    go func() {
        time.Sleep(pc.ttl)
        pc.mutex.Lock()
        defer pc.mutex.Unlock()
        if pc.cache[userID] != nil {
            delete(pc.cache[userID], permission)
        }
    }()
}

// NewAdvancedRBACService 创建高级RBAC服务
func NewAdvancedRBACService() *AdvancedRBACService {
    return &AdvancedRBACService{
        users:       make(map[string]*User),
        roles:       make(map[string]*AdvancedRole),
        permissions: make(map[string]*Permission),
        userRoles:   make(map[string][]string),
        roleGraph:   NewRoleGraph(),
        cache:       NewPermissionCache(5 * time.Minute),
    }
}

// CreateRole 创建角色
func (ar *AdvancedRBACService) CreateRole(role *AdvancedRole) error {
    ar.mutex.Lock()
    defer ar.mutex.Unlock()
    
    if _, exists := ar.roles[role.ID]; exists {
        return fmt.Errorf("role with ID %s already exists", role.ID)
    }
    
    role.Active = true
    role.CreatedAt = time.Now()
    role.UpdatedAt = time.Now()
    
    ar.roles[role.ID] = role
    return nil
}

// AddParentRole 为角色添加父角色
func (ar *AdvancedRBACService) AddParentRole(childRoleID, parentRoleID string) error {
    ar.mutex.Lock()
    defer ar.mutex.Unlock()
    
    // 检查角色是否存在
    childRole, childExists := ar.roles[childRoleID]
    if !childExists {
        return fmt.Errorf("child role with ID %s does not exist", childRoleID)
    }
    
    parentRole, parentExists := ar.roles[parentRoleID]
    if !parentExists {
        return fmt.Errorf("parent role with ID %s does not exist", parentRoleID)
    }
    
    // 检查是否已添加
    for _, existingParent := range childRole.ParentRoles {
        if existingParent == parentRoleID {
            return nil // 已经添加
        }
    }
    
    // 添加父子关系到角色图
    if err := ar.roleGraph.AddParentChildRelation(parentRoleID, childRoleID); err != nil {
        return fmt.Errorf("failed to add parent-child relation: %w", err)
    }
    
    // 更新角色信息
    childRole.ParentRoles = append(childRole.ParentRoles, parentRoleID)
    parentRole.ChildRoles = append(parentRole.ChildRoles, childRoleID)
    
    childRole.UpdatedAt = time.Now()
    parentRole.UpdatedAt = time.Now()
    
    return nil
}

// RemoveParentRole 为角色移除父角色
func (ar *AdvancedRBACService) RemoveParentRole(childRoleID, parentRoleID string) error {
    ar.mutex.Lock()
    defer ar.mutex.Unlock()
    
    // 检查角色是否存在
    childRole, childExists := ar.roles[childRoleID]
    if !childExists {
        return fmt.Errorf("child role with ID %s does not exist", childRoleID)
    }
    
    parentRole, parentExists := ar.roles[parentRoleID]
    if !parentExists {
        return fmt.Errorf("parent role with ID %s does not exist", parentRoleID)
    }
    
    // 从角色图中移除关系
    ar.roleGraph.RemoveParentChildRelation(parentRoleID, childRoleID)
    
    // 更新子角色
    newParentRoles := make([]string, 0, len(childRole.ParentRoles))
    for _, roleID := range childRole.ParentRoles {
        if roleID != parentRoleID {
            newParentRoles = append(newParentRoles, roleID)
        }
    }
    childRole.ParentRoles = newParentRoles
    
    // 更新父角色
    newChildRoles := make([]string, 0, len(parentRole.ChildRoles))
    for _, roleID := range parentRole.ChildRoles {
        if roleID != childRoleID {
            newChildRoles = append(newChildRoles, roleID)
        }
    }
    parentRole.ChildRoles = newChildRoles
    
    childRole.UpdatedAt = time.Now()
    parentRole.UpdatedAt = time.Now()
    
    return nil
}

// GetAllPermissionsForUser 获取用户的所有权限(包括继承的权限)
func (ar *AdvancedRBACService) GetAllPermissionsForUser(userID string) ([]string, error) {
    ar.mutex.RLock()
    defer ar.mutex.RUnlock()
    
    // 检查用户是否存在
    if _, exists := ar.users[userID]; !exists {
        return nil, fmt.Errorf("user with ID %s does not exist", userID)
    }
    
    // 收集用户所有角色的权限
    permissionSet := make(map[string]bool)
    
    // 获取用户直接分配的角色
    roleIDs := ar.userRoles[userID]
    
    // 对于每个角色,获取其所有权限(包括继承的权限)
    for _, roleID := range roleIDs {
        permissions := ar.getPermissionsForRole(roleID)
        for _, perm := range permissions {
            permissionSet[perm] = true
        }
    }
    
    // 转换为切片
    permissions := make([]string, 0, len(permissionSet))
    for perm := range permissionSet {
        permissions = append(permissions, perm)
    }
    
    return permissions, nil
}

// getPermissionsForRole 获取角色的所有权限(包括继承的权限)
func (ar *AdvancedRBACService) getPermissionsForRole(roleID string) []string {
    role, exists := ar.roles[roleID]
    if !exists {
        return []string{}
    }
    
    // 使用角色图获取所有权限
    return ar.roleGraph.GetRolePermissions(roleID, role.Permissions)
}

// CheckUserPermission 检查用户是否具有指定权限
func (ar *AdvancedRBACService) CheckUserPermission(userID, permission string) (bool, error) {
    // 先检查缓存
    if hasPermission, cached := ar.cache.CheckPermission(userID, permission); cached {
        return hasPermission, nil
    }
    
    ar.mutex.RLock()
    defer ar.mutex.RUnlock()
    
    // 检查用户是否存在
    if _, exists := ar.users[userID]; !exists {
        return false, fmt.Errorf("user with ID %s does not exist", userID)
    }
    
    // 获取用户所有角色
    roleIDs := ar.userRoles[userID]
    
    // 检查每个角色是否具有指定权限
    for _, roleID := range roleIDs {
        if ar.checkRolePermission(roleID, permission) {
            // 缓存结果
            ar.cache.SetPermission(userID, permission, true)
            return true, nil
        }
    }
    
    // 缓存结果
    ar.cache.SetPermission(userID, permission, false)
    return false, nil
}

// checkRolePermission 检查角色是否具有指定权限
func (ar *AdvancedRBACService) checkRolePermission(roleID, permission string) bool {
    // 检查直接权限
    role, exists := ar.roles[roleID]
    if !exists {
        return false
    }
    
    for _, perm := range role.Permissions {
        if perm == permission {
            return true
        }
    }
    
    // 检查继承的权限
    ancestors := ar.roleGraph.GetAncestors(roleID)
    for _, ancestorID := range ancestors {
        if ancestorRole, exists := ar.roles[ancestorID]; exists {
            for _, perm := range ancestorRole.Permissions {
                if perm == permission {
                    return true
                }
            }
        }
    }
    
    return false
}

// GetUserRolesWithInheritance 获取用户的所有角色(包括继承的角色)
func (ar *AdvancedRBACService) GetUserRolesWithInheritance(userID string) ([]string, error) {
    ar.mutex.RLock()
    defer ar.mutex.RUnlock()
    
    // 检查用户是否存在
    if _, exists := ar.users[userID]; !exists {
        return nil, fmt.Errorf("user with ID %s does not exist", userID)
    }
    
    // 收集角色
    roleSet := make(map[string]bool)
    
    // 添加直接分配的角色
    for _, roleID := range ar.userRoles[userID] {
        roleSet[roleID] = true
    }
    
    // 添加继承的角色
    for _, roleID := range ar.userRoles[userID] {
        ancestors := ar.roleGraph.GetAncestors(roleID)
        for _, ancestorID := range ancestors {
            roleSet[ancestorID] = true
        }
    }
    
    // 转换为切片
    roles := make([]string, 0, len(roleSet))
    for roleID := range roleSet {
        roles = append(roles, roleID)
    }
    
    return roles, nil
}

// GetRoleTree 获取角色树结构
func (ar *AdvancedRBACService) GetRoleTree() map[string]interface{} {
    ar.mutex.RLock()
    defer ar.mutex.RUnlock()
    
    tree := make(map[string]interface{})
    
    // 找到所有根角色(没有父角色的角色)
    rootRoles := make(map[string]bool)
    for roleID := range ar.roles {
        rootRoles[roleID] = true
    }
    
    // 移除有父角色的角色
    for roleID := range ar.roles {
        ancestors := ar.roleGraph.GetAncestors(roleID)
        for _, ancestor := range ancestors {
            delete(rootRoles, ancestor)
        }
    }
    
    // 构建树结构
    for rootRoleID := range rootRoles {
        tree[rootRoleID] = ar.buildRoleSubtree(rootRoleID)
    }
    
    return tree
}

// buildRoleSubtree 构建角色子树
func (ar *AdvancedRBACService) buildRoleSubtree(roleID string) map[string]interface{} {
    role, exists := ar.roles[roleID]
    if !exists {
        return nil
    }
    
    subtree := make(map[string]interface{})
    subtree["role"] = role
    
    // 添加子角色
    children := ar.roleGraph.GetDescendants(roleID)
    if len(children) > 0 {
        childMap := make(map[string]interface{})
        for _, childID := range children {
            if ar.isDirectChild(roleID, childID) {
                childMap[childID] = ar.buildRoleSubtree(childID)
            }
        }
        subtree["children"] = childMap
    }
    
    return subtree
}

// isDirectChild 检查是否是直接子角色
func (ar *AdvancedRBACService) isDirectChild(parentID, childID string) bool {
    role, exists := ar.roles[childID]
    if !exists {
        return false
    }
    
    for _, parentRoleID := range role.ParentRoles {
        if parentRoleID == parentID {
            return true
        }
    }
    
    return false
}

权限继承的实际应用示例

// 模拟一个企业组织结构的权限继承示例
func main() {
    // 创建高级RBAC服务
    rbac := NewAdvancedRBACService()
    
    // 创建权限
    permissions := []*Permission{
        {
            ID:          "perm_user_read",
            Name:        "读取用户信息",
            Resource:    "user",
            Action:      "read",
            Description: "允许读取用户基本信息",
        },
        {
            ID:          "perm_user_write",
            Name:        "修改用户信息",
            Resource:    "user",
            Action:      "write",
            Description: "允许修改用户基本信息",
        },
        {
            ID:          "perm_user_delete",
            Name:        "删除用户",
            Resource:    "user",
            Action:      "delete",
            Description: "允许删除用户",
        },
        {
            ID:          "perm_financial_read",
            Name:        "读取财务信息",
            Resource:    "financial",
            Action:      "read",
            Description: "允许读取财务信息",
        },
        {
            ID:          "perm_financial_write",
            Name:        "修改财务信息",
            Resource:    "financial",
            Action:      "write",
            Description: "允许修改财务信息",
        },
    }
    
    // 添加权限到系统
    for _, perm := range permissions {
        rbac.permissions[perm.ID] = perm
    }
    
    // 创建角色层次结构
    // 超级管理员 (拥有所有权限)
    superAdmin := &AdvancedRole{
        ID:          "super_admin",
        Name:        "超级管理员",
        Description: "系统超级管理员,拥有所有权限",
        Permissions: []string{"perm_user_read", "perm_user_write", "perm_user_delete", "perm_financial_read", "perm_financial_write"},
    }
    
    // 部门管理员 (继承超级管理员权限,但有一些限制)
    departmentAdmin := &AdvancedRole{
        ID:          "department_admin",
        Name:        "部门管理员",
        Description: "部门管理员,管理本部门用户",
        Permissions: []string{"perm_user_read", "perm_user_write"},
    }
    
    // 普通员工 (只有基本读取权限)
    employee := &AdvancedRole{
        ID:          "employee",
        Name:        "普通员工",
        Description: "普通员工,只能查看自己的信息",
        Permissions: []string{"perm_user_read"},
    }
    
    // 财务主管 (拥有财务相关权限)
    financeManager := &AdvancedRole{
        ID:          "finance_manager",
        Name:        "财务主管",
        Description: "财务部门主管,管理财务信息",
        Permissions: []string{"perm_financial_read", "perm_financial_write"},
    }
    
    // 财务专员 (继承财务主管权限)
    financeStaff := &AdvancedRole{
        ID:          "finance_staff",
        Name:        "财务专员",
        Description: "财务部门专员,处理日常财务工作",
        Permissions: []string{"perm_financial_read"},
    }
    
    // 创建角色
    rbac.CreateRole(superAdmin)
    rbac.CreateRole(departmentAdmin)
    rbac.CreateRole(employee)
    rbac.CreateRole(financeManager)
    rbac.CreateRole(financeStaff)
    
    // 建立角色继承关系
    // 部门管理员继承超级管理员的部分权限
    rbac.AddParentRole("department_admin", "super_admin")
    
    // 普通员工继承部门管理员权限
    rbac.AddParentRole("employee", "department_admin")
    
    // 财务专员继承财务主管权限
    rbac.AddParentRole("finance_staff", "finance_manager")
    
    // 创建用户
    users := []*User{
        {
            ID:       "user001",
            Username: "张总",
            Email:    "zhangzong@company.com",
        },
        {
            ID:       "user002",
            Username: "李经理",
            Email:    "lijingli@company.com",
        },
        {
            ID:       "user003",
            Username: "王员工",
            Email:    "wangyuangong@company.com",
        },
        {
            ID:       "user004",
            Username: "赵财务主管",
            Email:    "zhaocaiwu@company.com",
        },
        {
            ID:       "user005",
            Username: "钱财务专员",
            Email:    "qiancaiwu@company.com",
        },
    }
    
    // 添加用户到系统
    for _, user := range users {
        rbac.users[user.ID] = user
    }
    
    // 为用户分配角色
    rbac.userRoles["user001"] = []string{"super_admin"}
    rbac.userRoles["user002"] = []string{"department_admin"}
    rbac.userRoles["user003"] = []string{"employee"}
    rbac.userRoles["user004"] = []string{"finance_manager"}
    rbac.userRoles["user005"] = []string{"finance_staff"}
    
    // 测试权限检查
    fmt.Println("=== 权限检查测试 ===")
    
    // 测试超级管理员权限
    hasPerm, _ := rbac.CheckUserPermission("user001", "perm_user_delete")
    fmt.Printf("超级管理员是否有删除用户权限: %t\n", hasPerm)
    
    hasPerm, _ = rbac.CheckUserPermission("user001", "perm_financial_write")
    fmt.Printf("超级管理员是否有修改财务信息权限: %t\n", hasPerm)
    
    // 测试普通员工权限
    hasPerm, _ = rbac.CheckUserPermission("user003", "perm_user_read")
    fmt.Printf("普通员工是否有读取用户信息权限: %t\n", hasPerm)
    
    hasPerm, _ = rbac.CheckUserPermission("user003", "perm_user_delete")
    fmt.Printf("普通员工是否有删除用户权限: %t\n", hasPerm)
    
    // 测试财务专员权限(继承自财务主管)
    hasPerm, _ = rbac.CheckUserPermission("user005", "perm_financial_read")
    fmt.Printf("财务专员是否有读取财务信息权限: %t\n", hasPerm)
    
    hasPerm, _ = rbac.CheckUserPermission("user005", "perm_financial_write")
    fmt.Printf("财务专员是否有修改财务信息权限: %t\n", hasPerm)
    
    // 获取用户的所有权限
    fmt.Println("\n=== 用户权限列表 ===")
    allPerms, _ := rbac.GetAllPermissionsForUser("user003")
    fmt.Printf("普通员工的所有权限: %v\n", allPerms)
    
    allPerms, _ = rbac.GetAllPermissionsForUser("user005")
    fmt.Printf("财务专员的所有权限: %v\n", allPerms)
    
    // 显示角色树结构
    fmt.Println("\n=== 角色层次结构 ===")
    roleTree := rbac.GetRoleTree()
    printRoleTree(roleTree, 0)
}

// printRoleTree 打印角色树结构
func printRoleTree(tree map[string]interface{}, depth int) {
    indent := strings.Repeat("  ", depth)
    for roleID, value := range tree {
        if subtree, ok := value.(map[string]interface{}); ok {
            if roleInfo, exists := subtree["role"]; exists {
                if role, ok := roleInfo.(*AdvancedRole); ok {
                    fmt.Printf("%s%s (%s)\n", indent, role.Name, role.ID)
                }
            }
            if children, exists := subtree["children"]; exists {
                if childTree, ok := children.(map[string]interface{}); ok {
                    printRoleTree(childTree, depth+1)
                }
            }
        }
    }
}

权限继承的高级特性

1. 条件继承

在某些场景下,我们可能需要基于条件来决定是否继承权限:

// ConditionalRoleConstraint 条件角色约束
type ConditionalRoleConstraint struct {
    Condition string                 `json:"condition"`
    Parameters map[string]interface{} `json:"parameters"`
}

// EvaluateCondition 评估条件
func (crc *ConditionalRoleConstraint) EvaluateCondition(context map[string]interface{}) bool {
    // 这里实现条件评估逻辑
    // 例如:基于时间、IP地址、用户属性等条件
    return true
}

2. 权限覆盖

有时子角色需要覆盖父角色的某些权限:

// PermissionOverride 权限覆盖
type PermissionOverride struct {
    PermissionID string `json:"permission_id"`
    Allowed      bool   `json:"allowed"`
}

// ApplyPermissionOverride 应用权限覆盖
func (ar *AdvancedRBACService) ApplyPermissionOverride(roleID, permissionID string, allowed bool) error {
    ar.mutex.Lock()
    defer ar.mutex.Unlock()
    
    role, exists := ar.roles[roleID]
    if !exists {
        return fmt.Errorf("role with ID %s does not exist", roleID)
    }
    
    // 添加或更新权限覆盖
    override := PermissionOverride{
        PermissionID: permissionID,
        Allowed:      allowed,
    }
    
    // 这里需要实现权限覆盖的存储和处理逻辑
    
    role.UpdatedAt = time.Now()
    return nil
}

总结

通过以上实现,我们构建了一个功能强大的支持权限继承的RBAC系统,具有以下特点:

  1. 完整的角色层次结构:支持多级角色继承关系
  2. 循环依赖检测:防止角色之间形成循环继承
  3. 高效的权限检查:使用缓存和图算法优化权限检查性能
  4. 灵活的扩展性:支持条件继承、权限覆盖等高级特性

在实际应用中,还需要考虑以下几点:

  1. 持久化存储:将角色关系和权限数据存储到数据库中
  2. 性能优化:对于大规模系统,需要进一步优化图算法和缓存策略
  3. 安全审计:记录角色和权限变更日志
  4. API接口:提供RESTful API供其他服务调用

权限继承机制是RBAC模型的核心特性之一,通过合理设计和实现,可以极大地简化权限管理的复杂性,提高系统的可维护性和安全性。