forked from ory/kratos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschema.go
108 lines (90 loc) · 2.42 KB
/
schema.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package schema
import (
"context"
"encoding/base64"
"io"
"net/url"
"strings"
"sync"
"github.com/pkg/errors"
"github.com/tidwall/gjson"
"github.com/ory/herodot"
"github.com/ory/jsonschema/v3"
"github.com/ory/kratos/driver/config"
"github.com/ory/x/pagination"
"github.com/ory/x/urlx"
)
type Schemas []Schema
type IdentityTraitsProvider interface {
IdentityTraitsSchemas(ctx context.Context) (Schemas, error)
}
func (s Schemas) GetByID(id string) (*Schema, error) {
if id == "" {
id = config.DefaultIdentityTraitsSchemaID
}
for _, ss := range s {
if ss.ID == id {
return &ss, nil
}
}
return nil, errors.WithStack(herodot.ErrBadRequest.WithReasonf("Unable to find JSON Schema ID: %s", id))
}
func (s Schemas) Total() int {
return len(s)
}
func (s Schemas) List(page, perPage int) Schemas {
if page < 0 {
page = 0
}
if perPage < 1 {
perPage = 1
}
start, end := pagination.Index((page+1)*perPage, page*perPage, len(s))
return s[start:end]
}
var orderedKeyCacheMutex sync.RWMutex
var orderedKeyCache map[string][]string
func init() {
orderedKeyCache = make(map[string][]string)
}
func computeKeyPositions(schema []byte, dest *[]string, parents []string) {
switch gjson.GetBytes(schema, "type").String() {
case "object":
gjson.GetBytes(schema, "properties").ForEach(func(key, value gjson.Result) bool {
computeKeyPositions([]byte(value.Raw), dest, append(parents, strings.ReplaceAll(key.String(), ".", "\\.")))
return true
})
default:
*dest = append(*dest, strings.Join(parents, "."))
}
}
func GetKeysInOrder(ctx context.Context, schemaRef string) ([]string, error) {
orderedKeyCacheMutex.RLock()
keysInOrder, ok := orderedKeyCache[schemaRef]
orderedKeyCacheMutex.RUnlock()
if !ok {
sio, err := jsonschema.LoadURL(ctx, schemaRef)
if err != nil {
return nil, errors.WithStack(err)
}
schema, err := io.ReadAll(sio)
if err != nil {
return nil, errors.WithStack(err)
}
computeKeyPositions(schema, &keysInOrder, []string{})
orderedKeyCacheMutex.Lock()
orderedKeyCache[schemaRef] = keysInOrder
orderedKeyCacheMutex.Unlock()
}
return keysInOrder, nil
}
type Schema struct {
ID string `json:"id"`
URL *url.URL `json:"-"`
RawURL string `json:"url"`
}
func (s *Schema) SchemaURL(host *url.URL) *url.URL {
return urlx.AppendPaths(host, SchemasPath, base64.RawURLEncoding.EncodeToString([]byte(s.ID)))
}