- 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
46 lines
1.3 KiB
Go
46 lines
1.3 KiB
Go
package infrastructure
|
|
|
|
import (
|
|
"context"
|
|
|
|
"mengstack/internal/modules/rbac/domain"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type userRoleRepo struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewUserRoleRepository(db *gorm.DB) domain.UserRoleRepository {
|
|
return &userRoleRepo{db: db}
|
|
}
|
|
|
|
func (r *userRoleRepo) Assign(ctx context.Context, ur *domain.UserRole) error {
|
|
return r.db.WithContext(ctx).Create(ur).Error
|
|
}
|
|
|
|
func (r *userRoleRepo) Remove(ctx context.Context, userID uint, tenantID string, roleID uint) error {
|
|
return r.db.WithContext(ctx).
|
|
Where("user_id = ? AND tenant_id = ? AND role_id = ?", userID, tenantID, roleID).
|
|
Delete(&domain.UserRole{}).Error
|
|
}
|
|
|
|
func (r *userRoleRepo) FindByUser(ctx context.Context, userID uint, tenantID string) ([]domain.UserRole, error) {
|
|
var urs []domain.UserRole
|
|
err := r.db.WithContext(ctx).
|
|
Where("user_id = ? AND tenant_id = ?", userID, tenantID).
|
|
Find(&urs).Error
|
|
return urs, err
|
|
}
|
|
|
|
func (r *userRoleRepo) FindRolesByUser(ctx context.Context, userID uint, tenantID string) ([]domain.Role, error) {
|
|
var roles []domain.Role
|
|
err := r.db.WithContext(ctx).
|
|
Joins("JOIN user_roles ON user_roles.role_id = roles.id").
|
|
Where("user_roles.user_id = ? AND user_roles.tenant_id = ?", userID, tenantID).
|
|
Preload("Permissions").
|
|
Find(&roles).Error
|
|
return roles, err
|
|
}
|