Files
oslstats/internal/db/permission.go
2026-02-10 18:07:44 +11:00

97 lines
2.9 KiB
Go

package db
import (
"context"
"git.haelnorr.com/h/oslstats/internal/permissions"
"github.com/pkg/errors"
"github.com/uptrace/bun"
)
type Permission struct {
bun.BaseModel `bun:"table:permissions,alias:p"`
ID int `bun:"id,pk,autoincrement"`
Name permissions.Permission `bun:"name,unique,notnull"`
DisplayName string `bun:"display_name,notnull"`
Description string `bun:"description"`
Resource string `bun:"resource,notnull"`
Action string `bun:"action,notnull"`
IsSystem bool `bun:"is_system,default:false"`
CreatedAt int64 `bun:"created_at,notnull"`
Roles []Role `bun:"m2m:role_permissions,join:Permission=Role"`
}
func (p Permission) isSystem() bool {
return p.IsSystem
}
// GetPermissionByName queries the database for a permission matching the given name
// Returns nil, nil if no permission is found
func GetPermissionByName(ctx context.Context, tx bun.Tx, name permissions.Permission) (*Permission, error) {
if name == "" {
return nil, errors.New("name cannot be empty")
}
return GetByField[Permission](tx, "name", name).Get(ctx)
}
// GetPermissionByID queries the database for a permission matching the given ID
// Returns nil, nil if no permission is found
func GetPermissionByID(ctx context.Context, tx bun.Tx, id int) (*Permission, error) {
if id <= 0 {
return nil, errors.New("id must be positive")
}
return GetByID[Permission](tx, id).Get(ctx)
}
// GetPermissionsByResource queries for all permissions for a given resource
func GetPermissionsByResource(ctx context.Context, tx bun.Tx, resource string) ([]*Permission, error) {
if resource == "" {
return nil, errors.New("resource cannot be empty")
}
return GetList[Permission](tx).
Where("resource = ?", resource).GetAll(ctx)
}
// ListAllPermissions returns all permissions
func ListAllPermissions(ctx context.Context, tx bun.Tx) ([]*Permission, error) {
return GetList[Permission](tx).GetAll(ctx)
}
// CreatePermission creates a new permission
func CreatePermission(ctx context.Context, tx bun.Tx, perm *Permission) error {
if perm == nil {
return errors.New("permission cannot be nil")
}
if perm.Name == "" {
return errors.New("name cannot be empty")
}
if perm.DisplayName == "" {
return errors.New("display name cannot be empty")
}
if perm.Resource == "" {
return errors.New("resource cannot be empty")
}
if perm.Action == "" {
return errors.New("action cannot be empty")
}
err := Insert(tx, perm).
Returning("id").
Exec(ctx)
if err != nil {
return errors.Wrap(err, "db.Insert")
}
return nil
}
// DeletePermission deletes a permission (checks IsSystem protection)
func DeletePermission(ctx context.Context, tx bun.Tx, id int) error {
if id <= 0 {
return errors.New("id must be positive")
}
return DeleteWithProtection[Permission](ctx, tx, id)
}