77 lines
2.5 KiB
Go
77 lines
2.5 KiB
Go
package gormstore
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"git.itzana.me/StrafesNET/dev-service/pkg/datastore"
|
|
"git.itzana.me/StrafesNET/dev-service/pkg/model"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
var ErrNotExists = datastore.ErrNotExists
|
|
|
|
// CreatePermission creates a new Permission in the database.
|
|
func (g *Gormstore) CreatePermission(ctx context.Context, permission *model.Permission) error {
|
|
result := g.db.WithContext(ctx).Create(permission)
|
|
return result.Error
|
|
}
|
|
|
|
// GetPermission retrieves a single Permission by ID.
|
|
func (g *Gormstore) GetPermission(ctx context.Context, id uint32) (*model.Permission, error) {
|
|
var permission model.Permission
|
|
result := g.db.WithContext(ctx).First(&permission, id)
|
|
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
|
|
return nil, ErrNotExists
|
|
}
|
|
return &permission, result.Error
|
|
}
|
|
|
|
// GetAllPermissions retrieves all Permissions from the database.
|
|
func (g *Gormstore) GetAllPermissions(ctx context.Context) ([]model.Permission, error) {
|
|
var permissions []model.Permission
|
|
result := g.db.WithContext(ctx).Find(&permissions)
|
|
return permissions, result.Error
|
|
}
|
|
|
|
// UpdatePermission updates an existing Permission in the database.
|
|
func (g *Gormstore) UpdatePermission(ctx context.Context, permission *model.Permission) error {
|
|
result := g.db.WithContext(ctx).Save(permission)
|
|
return result.Error
|
|
}
|
|
|
|
// DeletePermission deletes a Permission by ID from the database.
|
|
func (g *Gormstore) DeletePermission(ctx context.Context, id uint32) error {
|
|
result := g.db.WithContext(ctx).Delete(&model.Permission{}, id)
|
|
if result.RowsAffected == 0 {
|
|
return ErrNotExists
|
|
}
|
|
return result.Error
|
|
}
|
|
|
|
// GetDefaultPermissions retrieves all default Permissions from the database.
|
|
func (g *Gormstore) GetDefaultPermissions(ctx context.Context) ([]model.Permission, error) {
|
|
var permissions []model.Permission
|
|
result := g.db.WithContext(ctx).Where("is_default = ?", true).Order("permissions.id asc").Find(&permissions)
|
|
return permissions, result.Error
|
|
}
|
|
|
|
// SetPermissionAsDefault sets whether a permission is default or not.
|
|
func (g *Gormstore) SetPermissionAsDefault(ctx context.Context, id uint32, isDefault bool) error {
|
|
// First check if the permission exists
|
|
var permission model.Permission
|
|
result := g.db.WithContext(ctx).First(&permission, id)
|
|
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
|
|
return ErrNotExists
|
|
}
|
|
if result.Error != nil {
|
|
return result.Error
|
|
}
|
|
|
|
// Update the default status
|
|
result = g.db.WithContext(ctx).Model(&model.Permission{}).
|
|
Where("id = ?", id).
|
|
Update("is_default", isDefault)
|
|
|
|
return result.Error
|
|
}
|