83 lines
2.3 KiB
Go
83 lines
2.3 KiB
Go
|
|
package repository
|
||
|
|
|
||
|
|
import (
|
||
|
|
"seeyon-filesystem/config"
|
||
|
|
"seeyon-filesystem/model"
|
||
|
|
|
||
|
|
"gorm.io/gorm"
|
||
|
|
)
|
||
|
|
|
||
|
|
// PermissionRepository 权限数据访问
|
||
|
|
type PermissionRepository struct{}
|
||
|
|
|
||
|
|
func NewPermissionRepository() *PermissionRepository {
|
||
|
|
return &PermissionRepository{}
|
||
|
|
}
|
||
|
|
|
||
|
|
// FindByID 根据ID查找权限
|
||
|
|
func (r *PermissionRepository) FindByID(id uint64) (*model.Permission, error) {
|
||
|
|
var perm model.Permission
|
||
|
|
err := config.DB.First(&perm, id).Error
|
||
|
|
if err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
return &perm, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// FindByCode 根据权限标识查找
|
||
|
|
func (r *PermissionRepository) FindByCode(code string) (*model.Permission, error) {
|
||
|
|
var perm model.Permission
|
||
|
|
err := config.DB.Where("code = ?", code).First(&perm).Error
|
||
|
|
if err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
return &perm, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// List 查询所有权限
|
||
|
|
func (r *PermissionRepository) List() ([]model.Permission, error) {
|
||
|
|
var perms []model.Permission
|
||
|
|
err := config.DB.Order("resource ASC, action ASC").Find(&perms).Error
|
||
|
|
return perms, err
|
||
|
|
}
|
||
|
|
|
||
|
|
// ListByResource 按资源类型查询权限
|
||
|
|
func (r *PermissionRepository) ListByResource(resource string) ([]model.Permission, error) {
|
||
|
|
var perms []model.Permission
|
||
|
|
err := config.DB.Where("resource = ?", resource).Order("action ASC").Find(&perms).Error
|
||
|
|
return perms, err
|
||
|
|
}
|
||
|
|
|
||
|
|
// GetUserPermissionCodes 获取用户的所有权限标识(通过角色)
|
||
|
|
func (r *PermissionRepository) GetUserPermissionCodes(userID uint64) ([]string, error) {
|
||
|
|
var codes []string
|
||
|
|
err := config.DB.Table("fs_permission p").
|
||
|
|
Select("DISTINCT p.code").
|
||
|
|
Joins("JOIN fs_role_permission rp ON rp.permission_id = p.id").
|
||
|
|
Joins("JOIN fs_user_role ur ON ur.role_id = rp.role_id").
|
||
|
|
Where("ur.user_id = ?", userID).
|
||
|
|
Pluck("p.code", &codes).Error
|
||
|
|
return codes, err
|
||
|
|
}
|
||
|
|
|
||
|
|
// Create 创建权限
|
||
|
|
func (r *PermissionRepository) Create(perm *model.Permission) error {
|
||
|
|
return config.DB.Create(perm).Error
|
||
|
|
}
|
||
|
|
|
||
|
|
// Update 更新权限
|
||
|
|
func (r *PermissionRepository) Update(perm *model.Permission) error {
|
||
|
|
return config.DB.Save(perm).Error
|
||
|
|
}
|
||
|
|
|
||
|
|
// Delete 删除权限
|
||
|
|
func (r *PermissionRepository) Delete(id uint64) error {
|
||
|
|
return config.DB.Transaction(func(tx *gorm.DB) error {
|
||
|
|
// 删除角色-权限关联
|
||
|
|
if err := tx.Where("permission_id = ?", id).Delete(&model.RolePermission{}).Error; err != nil {
|
||
|
|
return err
|
||
|
|
}
|
||
|
|
return tx.Delete(&model.Permission{}, id).Error
|
||
|
|
})
|
||
|
|
}
|