forked from ory/kratos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.go
75 lines (58 loc) · 1.53 KB
/
validator.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
package schema
import (
"bytes"
"encoding/json"
"sync"
"github.com/pkg/errors"
"github.com/ory/herodot"
"github.com/ory/jsonschema/v3"
)
type Validator struct {
sync.RWMutex
}
type ValidationProvider interface {
SchemaValidator() *Validator
}
func NewValidator() *Validator {
return &Validator{}
}
type validatorOptions struct {
e *ExtensionRunner
}
func WithExtensionRunner(e *ExtensionRunner) func(*validatorOptions) {
return func(o *validatorOptions) {
o.e = e
}
}
func (v *Validator) Validate(
href string,
document json.RawMessage,
opts ...func(*validatorOptions),
) error {
var o validatorOptions
for _, opt := range opts {
opt(&o)
}
compiler := jsonschema.NewCompiler()
resource, err := jsonschema.LoadURL(href)
if err != nil {
return errors.WithStack(herodot.ErrInternalServerError.WithReasonf("Unable to parse validate JSON object against JSON schema.").WithDebugf("%s", err))
}
if o.e != nil {
o.e.Register(compiler)
}
if err := compiler.AddResource(href, resource); err != nil {
return errors.WithStack(herodot.ErrInternalServerError.WithReasonf("Unable to parse validate JSON object against JSON schema.").WithDebugf("%s", err))
}
schema, err := compiler.Compile(href)
if err != nil {
return errors.WithStack(herodot.ErrInternalServerError.WithReasonf("Unable to parse validate JSON object against JSON schema.").WithDebugf("%s", err))
}
if err := schema.Validate(bytes.NewBuffer(document)); err != nil {
return errors.WithStack(err)
}
if o.e != nil {
return o.e.Finish()
}
return nil
}