AssignRole 为用户分配角色
(userID, roleID string)
| 432 | |
| 433 | // AssignRole 为用户分配角色 |
| 434 | func (ac *AccessController) AssignRole(userID, roleID string) error { |
| 435 | ac.mu.Lock() |
| 436 | defer ac.mu.Unlock() |
| 437 | |
| 438 | user, exists := ac.users[userID] |
| 439 | if !exists { |
| 440 | return fmt.Errorf("user %s not found", userID) |
| 441 | } |
| 442 | |
| 443 | role, exists := ac.roles[roleID] |
| 444 | if !exists { |
| 445 | return fmt.Errorf("role %s not found", roleID) |
| 446 | } |
| 447 | |
| 448 | // 添加到用户的角色列表 |
| 449 | if !contains(user.Roles, roleID) { |
| 450 | user.Roles = append(user.Roles, roleID) |
| 451 | user.UpdatedAt = time.Now() |
| 452 | } |
| 453 | |
| 454 | // 更新用户角色索引 |
| 455 | if _, exists := ac.userRoles[userID]; !exists { |
| 456 | ac.userRoles[userID] = []string{} |
| 457 | } |
| 458 | if !contains(ac.userRoles[userID], roleID) { |
| 459 | ac.userRoles[userID] = append(ac.userRoles[userID], roleID) |
| 460 | } |
| 461 | |
| 462 | // 清除用户权限缓存 |
| 463 | delete(ac.userPermissions, userID) |
| 464 | |
| 465 | // 记录审计日志 |
| 466 | if ac.config.EnableAudit && ac.auditLog != nil { |
| 467 | _ = ac.auditLog.LogEvent(AuditEvent{ |
| 468 | Type: AuditTypeRoleAssigned, |
| 469 | UserID: userID, |
| 470 | Timestamp: time.Now(), |
| 471 | Message: fmt.Sprintf("Role %s assigned to user %s", role.Name, user.Username), |
| 472 | Metadata: map[string]any{ |
| 473 | "role_id": roleID, |
| 474 | "role_name": role.Name, |
| 475 | }, |
| 476 | }) |
| 477 | } |
| 478 | |
| 479 | return nil |
| 480 | } |
| 481 | |
| 482 | // RevokeRole 撤销用户角色 |
| 483 | func (ac *AccessController) RevokeRole(userID, roleID string) error { |