urbac/privilege.go

54 lines
1.2 KiB
Go
Raw Permalink Normal View History

2024-10-31 17:56:26 +08:00
package urbac
import (
"context"
"fmt"
"strings"
)
2024-10-31 17:56:26 +08:00
type Privilege struct {
CreatedAt int64 `json:"created_at" gorm:"column:created_at;autoCreateTime:milli"`
UpdatedAt int64 `json:"updated_at" gorm:"column:updated_at;autoUpdateTime:milli"`
DeletedAt int64 `json:"deleted_at" gorm:"index;column:deleted_at;default:0"`
Code string `json:"code" gorm:"column:code;primaryKey"`
Label string
ParentId uint64
Scope string
2024-10-31 17:56:26 +08:00
}
func (u *Urbac) newPrivilege(ctx context.Context, code, label string, parentId uint64, scope string) (*Privilege, error) {
p := &Privilege{Code: code, Label: label, ParentId: parentId, Scope: scope}
codes := strings.SplitN(code, ":", 4)
if len(codes) != 4 {
return nil, fmt.Errorf("invalid code format")
}
wailcard := false
for _, item := range codes {
if item == "*" {
wailcard = true
}
if wailcard && item != "*" {
return nil, fmt.Errorf("invalid code format")
}
if len(item) > 8 {
return nil, fmt.Errorf("invalid code format: code snippet too long")
}
}
if codes[0] != "*" {
if _, err := u.GetScopeGroup(ctx, codes[0]); err != nil {
return nil, err
}
}
if err := u.store.Session(ctx).Create(p).Error; err != nil {
return nil, err
}
return p, nil
2024-10-31 17:56:26 +08:00
}