keyctl/pkg/api/v1/schema/schema.go
2023-03-15 02:11:37 +01:00

102 lines
2.1 KiB
Go

// Copyright (C) 2023 Marius Schellenberger
package schema
import (
"errors"
"git.giftfish.de/ston1th/keyctl/pkg/api/types"
"git.giftfish.de/ston1th/keyctl/pkg/core"
"golang.org/x/exp/slices"
)
const (
Version = "v1"
KeyName = "key"
ReqName = "req"
KeyPath = "/" + Version + "/" + KeyName
ReqPath = "/" + Version + "/" + ReqName
)
type NewKey struct {
Name string `json:"name"`
Size int `json:"size"`
Encoding core.Encoding `json:"encoding"`
}
var (
ErrEmptyKeyName = errors.New("empty key name")
ErrInvalidKeyName = errors.New("invalid key name")
ErrInvalidKeySize = errors.New("invalid key size")
)
const (
MinKeySize = 1
MaxKeySize = 1024
)
func (nk NewKey) Validate() error {
if nk.Name == "" {
return ErrEmptyKeyName
}
if core.NameRe.MatchString(nk.Name) {
return ErrInvalidKeyName
}
if nk.Size > MaxKeySize || nk.Size < MinKeySize {
return ErrInvalidKeySize
}
return nil
}
func ApproveURL(id, aid string) string {
return KeyPath + "/" + id + "/" + aid
}
type Key struct {
ID string `json:"id"`
Name string `json:"name"`
Created int64 `json:"created"`
Size int `json:"size"`
Encoding core.Encoding `json:"encoding"`
Key string `json:"key,omitempty"`
}
type Keys []Key
func (Keys) Less(a, b Key) bool { return a.Name < b.Name }
func (k Keys) Sort() { slices.SortStableFunc(k, k.Less) }
func NewKeys(keys core.Keys) (k Keys) {
for _, key := range keys {
k = append(k, Key(key))
}
k.Sort()
return
}
type Approval struct {
ID string `json:"id"`
AID string `json:"aid"`
Name string `json:"name"`
Created int64 `json:"created"`
Status types.Status `json:"status"`
}
type Approvals []Approval
func (Approvals) Less(a, b Approval) bool { return a.Name < b.Name }
func (a Approvals) Sort() { slices.SortStableFunc(a, a.Less) }
func NewApprovals(m types.ApprovalMap) (a Approvals) {
for k, v := range m {
a = append(a, Approval{
ID: v.ID,
AID: k,
Name: v.Name,
Created: v.Created,
Status: v.Status,
})
}
a.Sort()
return
}