Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Take field order from schema #205

Merged
merged 9 commits into from
Jan 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/api.swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -1010,6 +1010,9 @@
{
"type": "object"
},
{
"type": "object"
},
{
"type": "object"
}
Expand Down
16 changes: 15 additions & 1 deletion driver/configuration/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"net/url"
"time"

"github.com/pkg/errors"

"github.com/ory/x/tracing"
)

Expand All @@ -31,6 +33,18 @@ type SchemaConfig struct {
URL string `json:"url"`
}

type SchemaConfigs []SchemaConfig

func (s SchemaConfigs) FindSchemaByID(id string) (*SchemaConfig, error) {
for _, sc := range s {
if sc.ID == id {
return &sc, nil
}
}

return nil, errors.Errorf("could not find schema with id \"%s\"", id)
}

const DefaultIdentityTraitsSchemaID = "default"

type Provider interface {
Expand Down Expand Up @@ -67,7 +81,7 @@ type Provider interface {
CourierTemplatesRoot() string

DefaultIdentityTraitsSchemaURL() *url.URL
IdentityTraitsSchemas() []SchemaConfig
IdentityTraitsSchemas() SchemaConfigs

WhitelistedReturnToDomains() []url.URL

Expand Down
6 changes: 3 additions & 3 deletions driver/configuration/provider_viper.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,17 +107,17 @@ func (p *ViperProvider) DefaultIdentityTraitsSchemaURL() *url.URL {
return mustParseURLFromViper(p.l, ViperKeyDefaultIdentityTraitsSchemaURL)
}

func (p *ViperProvider) IdentityTraitsSchemas() []SchemaConfig {
func (p *ViperProvider) IdentityTraitsSchemas() SchemaConfigs {
ds := SchemaConfig{
ID: DefaultIdentityTraitsSchemaID,
URL: p.DefaultIdentityTraitsSchemaURL().String(),
}
var b bytes.Buffer
var ss []SchemaConfig
var ss SchemaConfigs
raw := viper.Get(ViperKeyIdentityTraitsSchemas)

if raw == nil {
return []SchemaConfig{ds}
return SchemaConfigs{ds}
}

if err := json.NewEncoder(&b).Encode(raw); err != nil {
Expand Down
22 changes: 22 additions & 0 deletions internal/httpclient/models/registration_request_method.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

48 changes: 48 additions & 0 deletions schema/schema.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
package schema

import (
"io/ioutil"
"net/url"
"strings"
"sync"

"github.com/santhosh-tekuri/jsonschema/v2"
"github.com/tidwall/gjson"

"github.com/ory/kratos/driver/configuration"

Expand All @@ -26,6 +32,48 @@ func (s Schemas) GetByID(id string) (*Schema, error) {
return nil, errors.WithStack(errors.Errorf("unable to find JSON schema with ID: %s", id))
}

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.Replace(key.String(), ".", "\\.", -1)))
return true
})
default:
*dest = append(*dest, strings.Join(parents, "."))
}
}

func GetKeysInOrder(schemaRef string) ([]string, error) {
orderedKeyCacheMutex.RLock()
keysInOrder, ok := orderedKeyCache[schemaRef]
orderedKeyCacheMutex.RUnlock()
if !ok {
sio, err := jsonschema.LoadURL(schemaRef)
if err != nil {
return nil, errors.WithStack(err)
}
schema, err := ioutil.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:"-"`
Expand Down
16 changes: 16 additions & 0 deletions schema/schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,19 @@ func TestSchemas_GetByID(t *testing.T) {
assert.Equal(t, (*Schema)(nil), s)
})
}

func TestGetKeysInOrder(t *testing.T) {
for i, tc := range []struct {
schemaRef string
keys []string
}{
{schemaRef: "file://./stub/identity.schema.json", keys: []string{"bar", "email"}},
{schemaRef: "file://./stub/complex.schema.json", keys: []string{"meal.name", "meal.chef", "fruits", "vegetables"}},
} {
t.Run(fmt.Sprintf("case=%d schemaRef=%s", i, tc.schemaRef), func(t *testing.T) {
actual, err := GetKeysInOrder(tc.schemaRef)
require.NoError(t, err)
assert.Equal(t, tc.keys, actual)
})
}
}
52 changes: 52 additions & 0 deletions schema/stub/complex.schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
{
"$id": "https://example.com/complex.schema.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["meal"],
"properties": {
"meal": {
"type": "object",
"required": ["name"],
"properties": {
"name": {
"type": "string"
},
"chef": {
"type": "string"
}
}
},
"fruits": {
"type": "array",
"items": {
"type": "string"
}
},
"vegetables": {
"type": "array",
"items": {
"$ref": "#/definitions/veggie"
}
}
},
"definitions": {
"veggie": {
"type": "object",
"required": [
"veggieName",
"veggieLike"
],
"properties": {
"veggieName": {
"type": "string"
},
"veggieLike": {
"type": "boolean"
},
"veggieAmount": {
"type": "number"
}
}
}
}
}
53 changes: 47 additions & 6 deletions selfservice/flow/profile/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import (
"encoding/json"
"net/http"
"net/url"
"sort"

"github.com/gofrs/uuid"

"github.com/ory/kratos/schema"

"github.com/gofrs/uuid"
"github.com/julienschmidt/httprouter"
"github.com/justinas/nosurf"
"github.com/pkg/errors"
Expand Down Expand Up @@ -107,6 +107,16 @@ func (h *Handler) initUpdateProfile(w http.ResponseWriter, r *http.Request, ps h
urlx.AppendPaths(h.c.SelfPublicURL(), PublicProfileManagementUpdatePath),
url.Values{"request": {a.ID.String()}},
).String(), json.RawMessage(s.Identity.Traits), "traits")

traitsSchema, err := h.c.IdentityTraitsSchemas().FindSchemaByID(s.Identity.TraitsSchemaID)
if err != nil {
h.d.SelfServiceErrorManager().ForwardError(r.Context(), w, r, err)
return
}
if err := a.Form.SortFields(traitsSchema.URL, "traits"); err != nil {
h.d.SelfServiceErrorManager().ForwardError(r.Context(), w, r, err)
return
}
if err := h.d.ProfileRequestPersister().CreateProfileRequest(r.Context(), a); err != nil {
h.d.SelfServiceErrorManager().ForwardError(r.Context(), w, r, err)
return
Expand Down Expand Up @@ -184,7 +194,18 @@ func (h *Handler) fetchUpdateProfileRequest(w http.ResponseWriter, r *http.Reque
}

ar.Form.SetCSRF(nosurf.Token(r))
sort.Sort(ar.Form.Fields)

traitsSchema, err := h.c.IdentityTraitsSchemas().FindSchemaByID(ar.Identity.TraitsSchemaID)
if err != nil {
h.d.Logger().Error(err)
return errors.WithStack(herodot.ErrInternalServerError.WithReason("The traits schema for this identity could not be found. This is an configuration error."))
}

if err := ar.Form.SortFields(traitsSchema.URL, "traits"); err != nil {
h.d.Logger().Error(err)
return errors.WithStack(herodot.ErrInternalServerError.WithReason("There was an error with sorting the form fields. This is an configuration error."))
}

h.d.Writer().Write(w, r, ar)
return nil
}
Expand Down Expand Up @@ -340,7 +361,17 @@ func (h *Handler) completeProfileManagementFlow(w http.ResponseWriter, r *http.R
ar.Form.SetField(field.Name, field)
}
ar.Form.SetCSRF(nosurf.Token(r))
sort.Sort(ar.Form.Fields)

traitsSchema, err := h.c.IdentityTraitsSchemas().FindSchemaByID(i.TraitsSchemaID)
if err != nil {
h.handleProfileManagementError(w, r, ar, i.Traits, err)
return
}
err = ar.Form.SortFields(traitsSchema.URL, "traits")
if err != nil {
h.handleProfileManagementError(w, r, ar, i.Traits, err)
return
}

if err := h.d.ProfileRequestPersister().UpdateProfileRequest(r.Context(), ar); err != nil {
h.handleProfileManagementError(w, r, ar, i.Traits, err)
Expand Down Expand Up @@ -371,7 +402,18 @@ func (h *Handler) handleProfileManagementError(w http.ResponseWriter, r *http.Re
}
}
rr.Form.SetCSRF(nosurf.Token(r))
sort.Sort(rr.Form.Fields)

// try to sort, might fail if the error before was sorting related
traitsSchema, err := h.c.IdentityTraitsSchemas().FindSchemaByID(rr.Identity.TraitsSchemaID)
if err != nil {
h.d.ProfileRequestRequestErrorHandler().HandleProfileManagementError(w, r, identity.CredentialsTypePassword, rr, err)
return
}
err = rr.Form.SortFields(traitsSchema.URL, "traits")
if err != nil {
h.d.ProfileRequestRequestErrorHandler().HandleProfileManagementError(w, r, identity.CredentialsTypePassword, rr, err)
return
}
}

h.d.ProfileRequestRequestErrorHandler().HandleProfileManagementError(w, r, identity.CredentialsTypePassword, rr, err)
Expand All @@ -387,7 +429,6 @@ func (h *Handler) newProfileManagementDecoder(i *identity.Identity) (decoderx.HT
"type": "object",
"required": ["traits"],
"properties": {
"request": { "type": "string" },
"traits": {}
}
}
Expand Down
Loading