You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
77 lines
2.2 KiB
77 lines
2.2 KiB
package repository |
|
|
|
import ( |
|
"gofaster/internal/auth/model" |
|
"gofaster/internal/shared/repository" |
|
|
|
"gorm.io/gorm" |
|
) |
|
|
|
type PermissionRepo struct { |
|
repository.BaseRepo |
|
} |
|
|
|
func NewPermissionRepo(db *gorm.DB) *PermissionRepo { |
|
return &PermissionRepo{BaseRepo: *repository.NewBaseRepo(db)} |
|
} |
|
|
|
func (r *PermissionRepo) FindAll(permissions *[]model.Permission) error { |
|
return r.DB().Find(permissions).Error |
|
} |
|
|
|
func (r *PermissionRepo) Create(permission *model.Permission) error { |
|
return r.DB().Create(permission).Error |
|
} |
|
|
|
func (r *PermissionRepo) GetByID(id uint) (*model.Permission, error) { |
|
var permission model.Permission |
|
err := r.DB().First(&permission, id).Error |
|
return &permission, err |
|
} |
|
|
|
func (r *PermissionRepo) GetByName(name string) (*model.Permission, error) { |
|
var permission model.Permission |
|
err := r.DB().Where("name = ?", name).First(&permission).Error |
|
return &permission, err |
|
} |
|
|
|
func (r *PermissionRepo) Update(permission *model.Permission) error { |
|
return r.DB().Save(permission).Error |
|
} |
|
|
|
func (r *PermissionRepo) Delete(id uint) error { |
|
return r.DB().Delete(&model.Permission{}, id).Error |
|
} |
|
|
|
func (r *PermissionRepo) List(page, pageSize int) ([]model.Permission, int64, error) { |
|
var permissions []model.Permission |
|
var count int64 |
|
|
|
err := r.DB().Model(&model.Permission{}).Count(&count).Error |
|
if err != nil { |
|
return nil, 0, err |
|
} |
|
|
|
offset := (page - 1) * pageSize |
|
err = r.DB().Offset(offset).Limit(pageSize).Find(&permissions).Error |
|
return permissions, count, err |
|
} |
|
|
|
func (r *PermissionRepo) GetByResourceAction(resource, action string) (*model.Permission, error) { |
|
var permission model.Permission |
|
err := r.DB().Where("resource = ? AND action = ?", resource, action).First(&permission).Error |
|
return &permission, err |
|
} |
|
|
|
func (r *PermissionRepo) CheckUserPermission(userID uint, permissionName string) bool { |
|
var count int64 |
|
|
|
// 查询用户是否有该权限 |
|
r.DB().Model(&model.UserRole{}). |
|
Joins("JOIN role_permissions ON user_roles.role_id = role_permissions.role_id"). |
|
Joins("JOIN permissions ON role_permissions.permission_id = permissions.id"). |
|
Where("user_roles.user_id = ? AND permissions.name = ?", userID, permissionName). |
|
Count(&count) |
|
|
|
return count > 0 |
|
}
|
|
|