-
-
Notifications
You must be signed in to change notification settings - Fork 928
/
handler.go
951 lines (837 loc) · 27.5 KB
/
handler.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package identity
import (
"context"
"encoding/json"
"io"
"net/http"
"time"
"github.com/ory/x/pagination/migrationpagination"
"github.com/ory/kratos/hash"
"github.com/ory/kratos/x"
"github.com/ory/kratos/cipher"
"github.com/ory/herodot"
"github.com/julienschmidt/httprouter"
"github.com/pkg/errors"
"github.com/ory/x/decoderx"
"github.com/ory/x/jsonx"
"github.com/ory/x/openapix"
"github.com/ory/x/sqlxx"
"github.com/ory/x/urlx"
"github.com/ory/kratos/driver/config"
)
const (
RouteCollection = "/identities"
RouteItem = RouteCollection + "/:id"
RouteCredentialItem = RouteItem + "/credentials/:type"
BatchPatchIdentitiesLimit = 2000
)
type (
handlerDependencies interface {
PoolProvider
PrivilegedPoolProvider
ManagementProvider
x.WriterProvider
config.Provider
x.CSRFProvider
cipher.Provider
hash.HashProvider
}
HandlerProvider interface {
IdentityHandler() *Handler
}
Handler struct {
r handlerDependencies
dx *decoderx.HTTP
}
)
func (h *Handler) Config(ctx context.Context) *config.Config {
return h.r.Config()
}
func NewHandler(r handlerDependencies) *Handler {
return &Handler{
r: r,
dx: decoderx.NewHTTP(),
}
}
func (h *Handler) RegisterPublicRoutes(public *x.RouterPublic) {
h.r.CSRFHandler().IgnoreGlobs(
RouteCollection, RouteCollection+"/*",
RouteCollection+"/*/credentials/*",
x.AdminPrefix+RouteCollection, x.AdminPrefix+RouteCollection+"/*",
x.AdminPrefix+RouteCollection+"/*/credentials/*",
)
public.GET(RouteCollection, x.RedirectToAdminRoute(h.r))
public.GET(RouteItem, x.RedirectToAdminRoute(h.r))
public.DELETE(RouteItem, x.RedirectToAdminRoute(h.r))
public.POST(RouteCollection, x.RedirectToAdminRoute(h.r))
public.PUT(RouteItem, x.RedirectToAdminRoute(h.r))
public.PATCH(RouteItem, x.RedirectToAdminRoute(h.r))
public.DELETE(RouteCredentialItem, x.RedirectToAdminRoute(h.r))
public.GET(x.AdminPrefix+RouteCollection, x.RedirectToAdminRoute(h.r))
public.GET(x.AdminPrefix+RouteItem, x.RedirectToAdminRoute(h.r))
public.DELETE(x.AdminPrefix+RouteItem, x.RedirectToAdminRoute(h.r))
public.POST(x.AdminPrefix+RouteCollection, x.RedirectToAdminRoute(h.r))
public.PUT(x.AdminPrefix+RouteItem, x.RedirectToAdminRoute(h.r))
public.PATCH(x.AdminPrefix+RouteItem, x.RedirectToAdminRoute(h.r))
public.DELETE(x.AdminPrefix+RouteCredentialItem, x.RedirectToAdminRoute(h.r))
}
func (h *Handler) RegisterAdminRoutes(admin *x.RouterAdmin) {
admin.GET(RouteCollection, h.list)
admin.GET(RouteItem, h.get)
admin.DELETE(RouteItem, h.delete)
admin.PATCH(RouteItem, h.patch)
admin.POST(RouteCollection, h.create)
admin.PATCH(RouteCollection, h.batchPatchIdentities)
admin.PUT(RouteItem, h.update)
admin.DELETE(RouteCredentialItem, h.deleteIdentityCredentials)
}
// Paginated Identity List Response
//
// swagger:response listIdentities
//
//nolint:deadcode,unused
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type listIdentitiesResponse struct {
migrationpagination.ResponseHeaderAnnotation
// List of identities
//
// in:body
Body []Identity
}
// Paginated List Identity Parameters
//
// swagger:parameters listIdentities
//
//nolint:deadcode,unused
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type listIdentitiesParameters struct {
migrationpagination.RequestParameters
// CredentialsIdentifier is the identifier (username, email) of the credentials to look up.
//
// required: false
// in: query
CredentialsIdentifier string `json:"credentials_identifier"`
}
// swagger:route GET /admin/identities identity listIdentities
//
// # List Identities
//
// Lists all [identities](https://www.ory.sh/docs/kratos/concepts/identity-user-model) in the system.
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// oryAccessToken:
//
// Responses:
// 200: listIdentities
// default: errorGeneric
func (h *Handler) list(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
page, itemsPerPage := x.ParsePagination(r)
params := ListIdentityParameters{Expand: ExpandDefault, Page: page, PerPage: itemsPerPage, CredentialsIdentifier: r.URL.Query().Get("credentials_identifier")}
if params.CredentialsIdentifier != "" {
params.Expand = ExpandEverything
}
is, err := h.r.IdentityPool().ListIdentities(r.Context(), params)
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
total := int64(len(is))
if params.CredentialsIdentifier == "" {
total, err = h.r.IdentityPool().CountIdentities(r.Context())
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
}
// Identities using the marshaler for including metadata_admin
isam := make([]WithCredentialsMetadataAndAdminMetadataInJSON, len(is))
for i, identity := range is {
isam[i] = WithCredentialsMetadataAndAdminMetadataInJSON(identity)
}
migrationpagination.PaginationHeader(w, urlx.AppendPaths(h.r.Config().SelfAdminURL(r.Context()), RouteCollection), total, page, itemsPerPage)
h.r.Writer().Write(w, r, isam)
}
// Get Identity Parameters
//
// swagger:parameters getIdentity
//
//nolint:deadcode,unused
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type getIdentity struct {
// ID must be set to the ID of identity you want to get
//
// required: true
// in: path
ID string `json:"id"`
// Include Credentials in Response
//
// Include any credential, for example `password` or `oidc`, in the response. When set to `oidc`, This will return
// the initial OAuth 2.0 Access Token, OAuth 2.0 Refresh Token and the OpenID Connect ID Token if available.
//
// required: false
// in: query
DeclassifyCredentials []string `json:"include_credential"`
}
// swagger:route GET /admin/identities/{id} identity getIdentity
//
// # Get an Identity
//
// Return an [identity](https://www.ory.sh/docs/kratos/concepts/identity-user-model) by its ID. You can optionally
// include credentials (e.g. social sign in connections) in the response by using the `include_credential` query parameter.
//
// Consumes:
// - application/json
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// oryAccessToken:
//
// Responses:
// 200: identity
// 404: errorGeneric
// default: errorGeneric
func (h *Handler) get(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
i, err := h.r.PrivilegedIdentityPool().GetIdentityConfidential(r.Context(), x.ParseUUID(ps.ByName("id")))
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
includeCredentials := r.URL.Query()["include_credential"]
var declassify []CredentialsType
for _, v := range includeCredentials {
tc, ok := ParseCredentialsType(v)
if ok {
declassify = append(declassify, tc)
} else {
h.r.Writer().WriteError(w, r, errors.WithStack(herodot.ErrBadRequest.WithReasonf("Invalid value `%s` for parameter `include_credential`.", declassify)))
return
}
}
emit, err := i.WithDeclassifiedCredentials(r.Context(), h.r, declassify)
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
h.r.Writer().Write(w, r, WithCredentialsAndAdminMetadataInJSON(*emit))
}
// Create Identity Parameters
//
// swagger:parameters createIdentity
//
//nolint:deadcode,unused
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type createIdentity struct {
// in: body
Body CreateIdentityBody
}
// Create Identity Body
//
// swagger:model createIdentityBody
type CreateIdentityBody struct {
// SchemaID is the ID of the JSON Schema to be used for validating the identity's traits.
//
// required: true
SchemaID string `json:"schema_id"`
// Traits represent an identity's traits. The identity is able to create, modify, and delete traits
// in a self-service manner. The input will always be validated against the JSON Schema defined
// in `schema_url`.
//
// required: true
Traits json.RawMessage `json:"traits"`
// Credentials represents all credentials that can be used for authenticating this identity.
//
// Use this structure to import credentials for a user.
Credentials *IdentityWithCredentials `json:"credentials"`
// VerifiableAddresses contains all the addresses that can be verified by the user.
//
// Use this structure to import verified addresses for an identity. Please keep in mind
// that the address needs to be represented in the Identity Schema or this field will be overwritten
// on the next identity update.
VerifiableAddresses []VerifiableAddress `json:"verifiable_addresses"`
// RecoveryAddresses contains all the addresses that can be used to recover an identity.
//
// Use this structure to import recovery addresses for an identity. Please keep in mind
// that the address needs to be represented in the Identity Schema or this field will be overwritten
// on the next identity update.
RecoveryAddresses []RecoveryAddress `json:"recovery_addresses"`
// Store metadata about the identity which the identity itself can see when calling for example the
// session endpoint. Do not store sensitive information (e.g. credit score) about the identity in this field.
MetadataPublic json.RawMessage `json:"metadata_public"`
// Store metadata about the user which is only accessible through admin APIs such as `GET /admin/identities/<id>`.
MetadataAdmin json.RawMessage `json:"metadata_admin,omitempty"`
// State is the identity's state.
//
// required: false
State State `json:"state"`
}
// Create Identity and Import Credentials
//
// swagger:model identityWithCredentials
type IdentityWithCredentials struct {
// Password if set will import a password credential.
Password *AdminIdentityImportCredentialsPassword `json:"password"`
// OIDC if set will import an OIDC credential.
OIDC *AdminIdentityImportCredentialsOIDC `json:"oidc"`
}
// Create Identity and Import Password Credentials
//
// swagger:model identityWithCredentialsPassword
type AdminIdentityImportCredentialsPassword struct {
// Configuration options for the import.
Config AdminIdentityImportCredentialsPasswordConfig `json:"config"`
}
// Create Identity and Import Password Credentials Configuration
//
// swagger:model identityWithCredentialsPasswordConfig
type AdminIdentityImportCredentialsPasswordConfig struct {
// The hashed password in [PHC format]( https://www.ory.sh/docs/kratos/concepts/credentials/username-email-password#hashed-password-format)
HashedPassword string `json:"hashed_password"`
// The password in plain text if no hash is available.
Password string `json:"password"`
}
// Create Identity and Import Social Sign In Credentials
//
// swagger:model identityWithCredentialsOidc
type AdminIdentityImportCredentialsOIDC struct {
// Configuration options for the import.
Config AdminIdentityImportCredentialsOIDCConfig `json:"config"`
}
// swagger:model identityWithCredentialsOidcConfig
type AdminIdentityImportCredentialsOIDCConfig struct {
// Configuration options for the import.
Config AdminIdentityImportCredentialsPasswordConfig `json:"config"`
// A list of OpenID Connect Providers
Providers []AdminCreateIdentityImportCredentialsOidcProvider `json:"providers"`
}
// Create Identity and Import Social Sign In Credentials Configuration
//
// swagger:model identityWithCredentialsOidcConfigProvider
type AdminCreateIdentityImportCredentialsOidcProvider struct {
// The subject (`sub`) of the OpenID Connect connection. Usually the `sub` field of the ID Token.
//
// required: true
Subject string `json:"subject"`
// The OpenID Connect provider to link the subject to. Usually something like `google` or `github`.
//
// required: true
Provider string `json:"provider"`
}
// swagger:route POST /admin/identities identity createIdentity
//
// # Create an Identity
//
// Create an [identity](https://www.ory.sh/docs/kratos/concepts/identity-user-model). This endpoint can also be used to
// [import credentials](https://www.ory.sh/docs/kratos/manage-identities/import-user-accounts-identities)
// for instance passwords, social sign in configurations or multifactor methods.
//
// Consumes:
// - application/json
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// oryAccessToken:
//
// Responses:
// 201: identity
// 400: errorGeneric
// 409: errorGeneric
// default: errorGeneric
func (h *Handler) create(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var cr CreateIdentityBody
if err := jsonx.NewStrictDecoder(r.Body).Decode(&cr); err != nil {
h.r.Writer().WriteErrorCode(w, r, http.StatusBadRequest, errors.WithStack(err))
return
}
i, err := h.identityFromCreateIdentityBody(r.Context(), &cr)
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
if err := h.r.IdentityManager().Create(r.Context(), i); err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
h.r.Writer().WriteCreated(w, r,
urlx.AppendPaths(
h.r.Config().SelfAdminURL(r.Context()),
"identities",
i.ID.String(),
).String(),
WithCredentialsMetadataAndAdminMetadataInJSON(*i),
)
}
func (h *Handler) identityFromCreateIdentityBody(ctx context.Context, cr *CreateIdentityBody) (*Identity, error) {
stateChangedAt := sqlxx.NullTime(time.Now())
state := StateActive
if cr.State != "" {
if err := cr.State.IsValid(); err != nil {
return nil, errors.WithStack(herodot.ErrBadRequest.WithReasonf("%s", err).WithWrap(err))
}
state = cr.State
}
i := &Identity{
SchemaID: cr.SchemaID,
Traits: []byte(cr.Traits),
State: state,
StateChangedAt: &stateChangedAt,
VerifiableAddresses: cr.VerifiableAddresses,
RecoveryAddresses: cr.RecoveryAddresses,
MetadataAdmin: []byte(cr.MetadataAdmin),
MetadataPublic: []byte(cr.MetadataPublic),
}
if err := h.importCredentials(ctx, i, cr.Credentials); err != nil {
return nil, err
}
return i, nil
}
// swagger:route PATCH /admin/identities identity batchPatchIdentities
//
// # Create and deletes multiple identities
//
// Creates or delete multiple
// [identities](https://www.ory.sh/docs/kratos/concepts/identity-user-model).
// This endpoint can also be used to [import
// credentials](https://www.ory.sh/docs/kratos/manage-identities/import-user-accounts-identities)
// for instance passwords, social sign in configurations or multifactor methods.
//
// Consumes:
// - application/json
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// oryAccessToken:
//
// Responses:
// 200: batchPatchIdentitiesResponse
// 400: errorGeneric
// 409: errorGeneric
// default: errorGeneric
func (h *Handler) batchPatchIdentities(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var (
req BatchPatchIdentitiesBody
res batchPatchIdentitiesResponse
)
if err := jsonx.NewStrictDecoder(r.Body).Decode(&req); err != nil {
h.r.Writer().WriteErrorCode(w, r, http.StatusBadRequest, errors.WithStack(err))
return
}
if len(req.Identities) > BatchPatchIdentitiesLimit {
h.r.Writer().WriteErrorCode(w, r, http.StatusBadRequest,
errors.WithStack(herodot.ErrBadRequest.WithReasonf(
"The maximum number of identities that can be created or deleted at once is %d.",
BatchPatchIdentitiesLimit)))
return
}
res.Identities = make([]*BatchIdentityPatchResponse, len(req.Identities))
// Array to look up the index of the identity in the identities array.
indexInIdentities := make([]*int, len(req.Identities))
identities := make([]*Identity, 0, len(req.Identities))
for i, patch := range req.Identities {
if patch.Create != nil {
res.Identities[i] = &BatchIdentityPatchResponse{
Action: ActionCreate,
PatchID: patch.ID,
}
identity, err := h.identityFromCreateIdentityBody(r.Context(), patch.Create)
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
identities = append(identities, identity)
idx := len(identities) - 1
indexInIdentities[i] = &idx
}
}
if err := h.r.IdentityManager().CreateIdentities(r.Context(), identities); err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
for resIdx, identitiesIdx := range indexInIdentities {
if identitiesIdx != nil {
res.Identities[resIdx].IdentityID = &identities[*identitiesIdx].ID
}
}
h.r.Writer().Write(w, r, &res)
}
// Update Identity Parameters
//
// swagger:parameters updateIdentity
//
//nolint:deadcode,unused
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type updateIdentity struct {
// ID must be set to the ID of identity you want to update
//
// required: true
// in: path
ID string `json:"id"`
// in: body
Body UpdateIdentityBody
}
// Update Identity Body
//
// swagger:model updateIdentityBody
type UpdateIdentityBody struct {
// SchemaID is the ID of the JSON Schema to be used for validating the identity's traits. If set
// will update the Identity's SchemaID.
//
// required: true
SchemaID string `json:"schema_id"`
// Traits represent an identity's traits. The identity is able to create, modify, and delete traits
// in a self-service manner. The input will always be validated against the JSON Schema defined
// in `schema_id`.
//
// required: true
Traits json.RawMessage `json:"traits"`
// Credentials represents all credentials that can be used for authenticating this identity.
//
// Use this structure to import credentials for a user.
// Note: this wil override completely identity's credentials. If used incorrectly, this can cause a user to lose
// access to their account!
Credentials *IdentityWithCredentials `json:"credentials"`
// Store metadata about the identity which the identity itself can see when calling for example the
// session endpoint. Do not store sensitive information (e.g. credit score) about the identity in this field.
MetadataPublic json.RawMessage `json:"metadata_public"`
// Store metadata about the user which is only accessible through admin APIs such as `GET /admin/identities/<id>`.
MetadataAdmin json.RawMessage `json:"metadata_admin,omitempty"`
// State is the identity's state.
//
// required: true
State State `json:"state"`
}
// swagger:route PUT /admin/identities/{id} identity updateIdentity
//
// # Update an Identity
//
// This endpoint updates an [identity](https://www.ory.sh/docs/kratos/concepts/identity-user-model). The full identity
// payload (except credentials) is expected. It is possible to update the identity's credentials as well.
//
// Consumes:
// - application/json
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// oryAccessToken:
//
// Responses:
// 200: identity
// 400: errorGeneric
// 404: errorGeneric
// 409: errorGeneric
// default: errorGeneric
func (h *Handler) update(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
var ur UpdateIdentityBody
if err := h.dx.Decode(r, &ur,
decoderx.HTTPJSONDecoder()); err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
id := x.ParseUUID(ps.ByName("id"))
identity, err := h.r.PrivilegedIdentityPool().GetIdentityConfidential(r.Context(), id)
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
if ur.SchemaID != "" {
identity.SchemaID = ur.SchemaID
}
if ur.State != "" && identity.State != ur.State {
if err := ur.State.IsValid(); err != nil {
h.r.Writer().WriteError(w, r, errors.WithStack(herodot.ErrBadRequest.WithReasonf("%s", err).WithWrap(err)))
return
}
stateChangedAt := sqlxx.NullTime(time.Now())
identity.State = ur.State
identity.StateChangedAt = &stateChangedAt
}
identity.Traits = []byte(ur.Traits)
identity.MetadataPublic = []byte(ur.MetadataPublic)
identity.MetadataAdmin = []byte(ur.MetadataAdmin)
// Although this is PUT and not PATCH, if the Credentials are not supplied keep the old one
if ur.Credentials != nil {
if err := h.importCredentials(r.Context(), identity, ur.Credentials); err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
}
if err := h.r.IdentityManager().Update(
r.Context(),
identity,
ManagerAllowWriteProtectedTraits,
); err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
h.r.Writer().Write(w, r, WithCredentialsMetadataAndAdminMetadataInJSON(*identity))
}
// Delete Identity Parameters
//
// swagger:parameters deleteIdentity
//
//nolint:deadcode,unused
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type deleteIdentity struct {
// ID is the identity's ID.
//
// required: true
// in: path
ID string `json:"id"`
}
// swagger:route DELETE /admin/identities/{id} identity deleteIdentity
//
// # Delete an Identity
//
// Calling this endpoint irrecoverably and permanently deletes the [identity](https://www.ory.sh/docs/kratos/concepts/identity-user-model) given its ID. This action can not be undone.
// This endpoint returns 204 when the identity was deleted or when the identity was not found, in which case it is
// assumed that is has been deleted already.
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// oryAccessToken:
//
// Responses:
// 204: emptyResponse
// 404: errorGeneric
// default: errorGeneric
func (h *Handler) delete(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
if err := h.r.PrivilegedIdentityPool().DeleteIdentity(r.Context(), x.ParseUUID(ps.ByName("id"))); err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
// Patch Identity Parameters
//
// swagger:parameters patchIdentity
//
//nolint:deadcode,unused
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type patchIdentity struct {
// ID must be set to the ID of identity you want to update
//
// required: true
// in: path
ID string `json:"id"`
// in: body
Body openapix.JSONPatchDocument
}
// swagger:route PATCH /admin/identities/{id} identity patchIdentity
//
// # Patch an Identity
//
// Partially updates an [identity's](https://www.ory.sh/docs/kratos/concepts/identity-user-model) field using [JSON Patch](https://jsonpatch.com/).
// The fields `id`, `stateChangedAt` and `credentials` can not be updated using this method.
//
// Consumes:
// - application/json
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// oryAccessToken:
//
// Responses:
// 200: identity
// 400: errorGeneric
// 404: errorGeneric
// 409: errorGeneric
// default: errorGeneric
func (h *Handler) patch(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
requestBody, err := io.ReadAll(r.Body)
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
id := x.ParseUUID(ps.ByName("id"))
identity, err := h.r.PrivilegedIdentityPool().GetIdentityConfidential(r.Context(), id)
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
credentials := identity.Credentials
oldState := identity.State
patchedIdentity := WithAdminMetadataInJSON(*identity)
if err := jsonx.ApplyJSONPatch(requestBody, &patchedIdentity, "/id", "/stateChangedAt", "/credentials"); err != nil {
h.r.Writer().WriteError(w, r, errors.WithStack(
herodot.
ErrBadRequest.
WithReasonf("An error occured when applying the JSON patch").
WithErrorf("%v", err).
WithWrap(err),
))
return
}
// See https://github.com/ory/cloud/issues/148
// The apply patch operation overrides the credentials with an empty map.
patchedIdentity.Credentials = credentials
if oldState != patchedIdentity.State {
// Check if the changed state was actually valid
if err := patchedIdentity.State.IsValid(); err != nil {
h.r.Writer().WriteError(w, r, errors.WithStack(
herodot.
ErrBadRequest.
WithReasonf("The supplied state ('%s') was not valid. Valid states are ('%s', '%s').", string(patchedIdentity.State), StateActive, StateInactive).
WithErrorf("%v", err).
WithWrap(err),
))
return
}
// If the state changed, we need to update the timestamp of it
stateChangedAt := sqlxx.NullTime(time.Now())
patchedIdentity.StateChangedAt = &stateChangedAt
}
updatedIdenty := Identity(patchedIdentity)
if err := h.r.IdentityManager().Update(
r.Context(),
&updatedIdenty,
ManagerAllowWriteProtectedTraits,
); err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
h.r.Writer().Write(w, r, WithCredentialsMetadataAndAdminMetadataInJSON(updatedIdenty))
}
func deletCredentialWebAuthFromIdentity(identity *Identity) (*Identity, error) {
cred, ok := identity.GetCredentials(CredentialsTypeWebAuthn)
if !ok {
// This should never happend as it's checked earlier in the code;
// But we never know...
return nil, errors.WithStack(herodot.ErrNotFound.WithReasonf("You tried to remove a CredentialsTypeWebAuthn but this user have no CredentialsTypeWebAuthn set up."))
}
var cc CredentialsWebAuthnConfig
if err := json.Unmarshal(cred.Config, &cc); err != nil {
// Database has been tampered or the json schema are incompatible (migration issue);
return nil, errors.WithStack(herodot.ErrInternalServerError.WithReasonf("Unable to decode identity credentials.").WithDebug(err.Error()))
}
updated := make([]CredentialWebAuthn, 0)
for k, cred := range cc.Credentials {
if cred.IsPasswordless {
updated = append(updated, cc.Credentials[k])
}
}
if len(updated) == 0 {
identity.DeleteCredentialsType(CredentialsTypeWebAuthn)
return identity, nil
}
cc.Credentials = updated
message, err := json.Marshal(cc)
if err != nil {
return nil, errors.WithStack(herodot.ErrInternalServerError.WithReasonf("Unable to encode identity credentials.").WithDebug(err.Error()))
}
cred.Config = message
identity.SetCredentials(CredentialsTypeWebAuthn, *cred)
return identity, nil
}
// Delete Credential Parameters
//
// swagger:parameters deleteIdentityCredentials
//
//nolint:deadcode,unused
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type deleteIdentityCredentials struct {
// ID is the identity's ID.
//
// required: true
// in: path
ID string `json:"id"`
// Type is the credential's Type.
// One of totp, webauthn, lookup
//
// enum: totp,webauthn,lookup
// required: true
// in: path
Type string `json:"type"`
}
// swagger:route DELETE /admin/identities/{id}/credentials/{type} identity deleteIdentityCredentials
//
// # Delete a credential for a specific identity
//
// Delete an [identity](https://www.ory.sh/docs/kratos/concepts/identity-user-model) credential by its type
// You can only delete second factor (aal2) credentials.
//
// Consumes:
// - application/json
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// oryAccessToken:
//
// Responses:
// 204: emptyResponse
// 404: errorGeneric
// default: errorGeneric
func (h *Handler) deleteIdentityCredentials(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
identity, err := h.r.PrivilegedIdentityPool().GetIdentityConfidential(r.Context(), x.ParseUUID(ps.ByName("id")))
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
cred, ok := identity.GetCredentials(CredentialsType(ps.ByName("type")))
if !ok {
h.r.Writer().WriteError(w, r, errors.WithStack(herodot.ErrNotFound.WithReasonf("You tried to remove a %s but this user have no %s set up.", ps.ByName("type"), ps.ByName("type"))))
return
}
switch cred.Type {
case CredentialsTypeLookup:
fallthrough
case CredentialsTypeTOTP:
identity.DeleteCredentialsType(cred.Type)
case CredentialsTypeWebAuthn:
identity, err = deletCredentialWebAuthFromIdentity(identity)
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
case CredentialsTypeOIDC:
fallthrough
case CredentialsTypePassword:
h.r.Writer().WriteError(w, r, errors.WithStack(herodot.ErrBadRequest.WithReasonf("You can't remove first factor credentials.")))
return
default:
h.r.Writer().WriteError(w, r, errors.WithStack(herodot.ErrBadRequest.WithReasonf("Unknown credentials type %s.", cred.Type)))
return
}
if err := h.r.IdentityManager().Update(
r.Context(),
identity,
ManagerAllowWriteProtectedTraits,
); err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
w.WriteHeader(http.StatusNoContent)
}