- 4 表设计: permissions, roles, role_permissions(m2m), user_roles - 多租户隔离: 角色和用户角色分配按 tenant_id 隔离 - 权限并集: 多角色用户取权限并集,无继承 - 系统角色保护: is_system 角色不可修改/删除 - 种子数据: 7 个默认权限 + 3 个系统角色(super_admin/tenant_admin/member) - 权限中间件: RequirePermission 支持按路由粒度控制 - API 路由: /api/v1/rbac/ 下完整 CRUD 端点 - fx 注册: RBAC Module 集成到 app.go
83 lines
2.2 KiB
Go
83 lines
2.2 KiB
Go
package domain
|
|
|
|
import "time"
|
|
|
|
type Role struct {
|
|
ID uint `json:"id" gorm:"primaryKey"`
|
|
TenantID string `json:"tenant_id" gorm:"type:uuid;not null;primaryKey;index:idx_tenant_role_name,unique"`
|
|
Name string `json:"name" gorm:"size:64;not null;index:idx_tenant_role_name,unique"`
|
|
Description string `json:"description" gorm:"size:256"`
|
|
IsSystem bool `json:"is_system" gorm:"default:false"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
|
|
Permissions []Permission `json:"permissions,omitempty" gorm:"many2many:role_permissions;"`
|
|
}
|
|
|
|
func (Role) TableName() string {
|
|
return "roles"
|
|
}
|
|
|
|
type RolePermission struct {
|
|
RoleID uint `gorm:"primaryKey"`
|
|
PermissionID uint `gorm:"primaryKey"`
|
|
}
|
|
|
|
func (RolePermission) TableName() string {
|
|
return "role_permissions"
|
|
}
|
|
|
|
type UserRole struct {
|
|
UserID uint `json:"user_id" gorm:"primaryKey"`
|
|
TenantID string `json:"tenant_id" gorm:"type:uuid;not null;primaryKey"`
|
|
RoleID uint `json:"role_id" gorm:"not null"`
|
|
}
|
|
|
|
func (UserRole) TableName() string {
|
|
return "user_roles"
|
|
}
|
|
|
|
type RoleDTO struct {
|
|
ID uint `json:"id"`
|
|
TenantID string `json:"tenant_id"`
|
|
Name string `json:"name"`
|
|
Description string `json:"description"`
|
|
IsSystem bool `json:"is_system"`
|
|
Permissions []PermissionDTO `json:"permissions,omitempty"`
|
|
}
|
|
|
|
func ToRoleDTO(r *Role) RoleDTO {
|
|
dto := RoleDTO{
|
|
ID: r.ID,
|
|
TenantID: r.TenantID,
|
|
Name: r.Name,
|
|
Description: r.Description,
|
|
IsSystem: r.IsSystem,
|
|
}
|
|
if r.Permissions != nil {
|
|
dto.Permissions = make([]PermissionDTO, len(r.Permissions))
|
|
for i, p := range r.Permissions {
|
|
dto.Permissions[i] = ToPermissionDTO(&p)
|
|
}
|
|
}
|
|
return dto
|
|
}
|
|
|
|
type CreateRoleRequest struct {
|
|
Name string `json:"name" binding:"required"`
|
|
Description string `json:"description"`
|
|
}
|
|
|
|
type UpdateRoleRequest struct {
|
|
Name string `json:"name"`
|
|
Description string `json:"description"`
|
|
}
|
|
|
|
type SetRolePermissionsRequest struct {
|
|
PermissionIDs []uint `json:"permission_ids" binding:"required"`
|
|
}
|
|
|
|
type AssignRoleRequest struct {
|
|
RoleID uint `json:"role_id" binding:"required"`
|
|
}
|