-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
1089 lines (983 loc) · 26.6 KB
/
handlers.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
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package authorize
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"io"
"net/http"
"net/url"
"path"
"strings"
"time"
"git.sr.ht/~mariusor/lw"
"git.sr.ht/~mariusor/mask"
vocab "github.com/go-ap/activitypub"
"github.com/go-ap/auth"
"github.com/go-ap/authorize/internal/assets"
"github.com/go-ap/errors"
"github.com/go-ap/filters"
"github.com/go-ap/processing"
"github.com/go-chi/chi/v5"
"github.com/mariusor/render"
"github.com/openshift/osin"
"github.com/pborman/uuid"
)
type PasswordChanger interface {
PasswordSet(vocab.Item, []byte) error
PasswordCheck(vocab.Item, []byte) error
}
type account struct {
username string
pw string
actor *vocab.Actor
}
type FullStorage interface {
ClientSaver
ClientLister
osin.Storage
processing.Store
processing.KeyLoader
PasswordChanger
}
type ClientSaver interface {
// UpdateClient updates the client (identified by it's id) and replaces the values with the values of client.
UpdateClient(c osin.Client) error
// CreateClient stores the client in the database and returns an error, if something went wrong.
CreateClient(c osin.Client) error
// RemoveClient removes a client (identified by id) from the database. Returns an error if something went wrong.
RemoveClient(id string) error
}
type ClientLister interface {
// ListClients lists existing clients
ListClients() ([]osin.Client, error)
GetClient(id string) (osin.Client, error)
}
func (a account) IsLogged() bool {
return a.actor != nil && a.actor.PreferredUsername.First().Value.String() == a.username
}
func (a *account) FromActor(p *vocab.Actor) {
a.username = p.PreferredUsername.First().String()
a.actor = p
}
type Service struct {
Stores []FullStorage
Client auth.Client
Logger lw.Logger
}
// GenerateID creates an IRI that can be used to uniquely identify the "it" item, based on the collection "col" and
// its creator "by"
func (s *Service) generateID(it vocab.Item, _ vocab.Item, by vocab.Item) (vocab.ID, error) {
app, _, err := s.findMatchingStorage(iriBaseURL(it.GetLink()))
if err != nil {
return "", errors.NewNotFound(err, "not found")
}
base := app.GetLink().GetID()
typ := it.GetType()
var partOf vocab.IRI
if vocab.ActivityTypes.Contains(typ) || vocab.IntransitiveActivityTypes.Contains(typ) {
partOf = filters.ActivitiesType.IRI(base)
} else if vocab.ActorTypes.Contains(typ) || typ == vocab.ActorType {
partOf = filters.ActorsType.IRI(base)
} else {
partOf = filters.ObjectsType.IRI(base)
}
return generateID(it, partOf, by)
}
// GenerateID generates a unique identifier for the 'it' [vocab.Item].
func generateID(it vocab.Item, partOf vocab.IRI, by vocab.Item) (vocab.ID, error) {
uid := uuid.New()
id := partOf.GetLink().AddPath(uid)
typ := it.GetType()
if vocab.ActivityTypes.Contains(typ) || vocab.IntransitiveActivityTypes.Contains(typ) {
err := vocab.OnIntransitiveActivity(it, func(a *vocab.IntransitiveActivity) error {
if rec := a.Recipients(); rec.Contains(vocab.PublicNS) {
return nil
}
if vocab.IsNil(by) {
by = a.Actor
}
if !vocab.IsNil(by) {
// if "it" is not a public activity, save it to its actor Outbox instead of the global activities collection
outbox := vocab.Outbox.IRI(by)
id = vocab.ID(fmt.Sprintf("%s/%s", outbox, uid))
}
return nil
})
if err != nil {
return id, err
}
err = vocab.OnObject(it, func(a *vocab.Object) error {
a.ID = id
return nil
})
return id, err
}
if it.IsLink() {
return id, vocab.OnLink(it, func(l *vocab.Link) error {
l.ID = id
return nil
})
}
return id, vocab.OnObject(it, func(o *vocab.Object) error {
o.ID = id
return nil
})
return id, nil
}
const (
meKey = "me"
redirectUriKey = "redirect_uri"
clientIdKey = "client_id"
responseTypeKey = "response_type"
ID osin.AuthorizeRequestType = "id"
)
func (s *Service) findMatchingStorage(hosts ...string) (vocab.Actor, FullStorage, error) {
var app vocab.Actor
for _, db := range s.Stores {
for _, host := range hosts {
res, err := db.Load(vocab.IRI(host))
if err != nil {
continue
}
err = vocab.OnActor(res, func(actor *vocab.Actor) error {
app = *actor
return nil
})
if err != nil {
continue
}
if app.ID != "" {
return app, db, nil
}
}
}
return app, nil, fmt.Errorf("unable to find storage")
}
func (s *Service) server(req *http.Request) (*auth.Server, error) {
app, db, err := s.findMatchingStorage(baseURL(req)...)
if err != nil {
return nil, errors.NewNotFound(err, "resource not found %s", req.Host)
}
if db == nil {
return nil, errors.NotFoundf("resource not found %s", req.Host)
}
return auth.New(
auth.WithURL(app.GetLink().String()),
auth.WithStorage(db),
auth.WithClient(s.Client),
auth.WithLogger(s.Logger.WithContext(lw.Ctx{"log": "osin"})),
)
}
func (s *Service) IsValidRequest(r *http.Request) bool {
clientID, err := url.QueryUnescape(r.FormValue(clientIdKey))
if err != nil {
return false
}
clURL, err := url.ParseRequestURI(clientID)
if err != nil || clURL.Host == "" || clURL.Scheme == "" {
return false
}
return true
}
func IndieAuthClientActor(author vocab.Item, url *url.URL) *vocab.Actor {
now := time.Now().UTC()
preferredUsername := url.Host
p := vocab.Person{
Type: vocab.ApplicationType,
AttributedTo: author.GetLink(),
Audience: vocab.ItemCollection{vocab.PublicNS},
Generator: author.GetLink(),
Published: now,
Summary: vocab.NaturalLanguageValues{
{vocab.NilLangRef, vocab.Content("IndieAuth generated actor")},
},
Updated: now,
PreferredUsername: vocab.NaturalLanguageValues{
{vocab.NilLangRef, vocab.Content(preferredUsername)},
},
URL: vocab.IRI(url.String()),
}
return &p
}
func (s *Service) ValidateClient(r *http.Request) (*vocab.Actor, error) {
_ = r.ParseForm()
clientID, err := url.QueryUnescape(r.FormValue(clientIdKey))
if err != nil {
return nil, err
}
if clientID == "" {
return nil, nil
}
clientURL, err := url.Parse(clientID)
if err != nil {
return nil, nil
}
unescapedUri, err := url.QueryUnescape(r.FormValue(redirectUriKey))
if err != nil {
return nil, err
}
// load the 'me' value of the actor that wants to authenticate
me, err := url.QueryUnescape(r.FormValue(meKey))
if err != nil {
return nil, err
}
app, storage, err := s.findMatchingStorage(baseURL(r)...)
if err != nil {
return nil, err
}
baseIRI := app.GetLink()
// check for existing user actor
var actor vocab.Item
if me != "" {
iri := SearchActorsIRI(baseIRI, ByType(vocab.PersonType), ByURL(vocab.IRI(me)))
actor, err = storage.Load(iri)
if err != nil {
return nil, err
}
if actor == nil {
return nil, errors.NotFoundf("unknown actor")
}
}
// check for existing application actor
iri := SearchActorsIRI(baseIRI, ByType(vocab.ApplicationType), ByURL(vocab.IRI(clientID)))
clientActor, err := storage.Load(iri, filters.SameURL(vocab.IRI(clientID)), filters.HasType(vocab.ApplicationType))
if err != nil {
return nil, err
}
if clientActor == nil {
newClient := IndieAuthClientActor(actor, clientURL)
if err != nil {
return nil, err
}
if newId, err := s.generateID(newClient, vocab.Outbox.IRI(actor), nil); err == nil {
newClient.ID = newId
}
clientActor, err = storage.Save(newClient)
if err != nil {
return nil, err
}
}
id := path.Base(clientActor.GetID().String())
// must have a valid client
if _, err = storage.GetClient(id); err != nil {
if errors.IsNotFound(err) {
// create client
newClient := osin.DefaultClient{
Id: id,
Secret: "",
RedirectUri: unescapedUri,
//UserData: userData,
}
if err = storage.CreateClient(&newClient); err != nil {
return nil, err
}
} else {
return nil, err
}
r.Form.Set(clientIdKey, id)
if osin.AuthorizeRequestType(r.FormValue(responseTypeKey)) == ID {
r.Form.Set(responseTypeKey, "code")
}
if act, ok := actor.(*vocab.Actor); ok {
return act, nil
}
}
return nil, nil
}
var scopeAnonymousUserCreate = "anonUserCreate"
func iriBaseURL(iri vocab.IRI) string {
u, _ := iri.URL()
u.Path = "/"
u.RawQuery = ""
u.RawFragment = ""
return u.String()
}
func (s *Service) loadAccountByID(iri vocab.IRI) (*vocab.Actor, error) {
_, storage, err := s.findMatchingStorage(iriBaseURL(iri))
if err != nil {
return nil, err
}
actors, err := storage.Load(iri)
if err != nil {
return nil, err
}
if actors == nil {
return nil, errNotFound
}
if actors.IsCollection() {
vocab.OnCollectionIntf(actors, func(col vocab.CollectionInterface) error {
actors = col.Collection()
return nil
})
}
var actor *vocab.Actor
err = vocab.OnActor(actors, func(act *vocab.Actor) error {
actor = act
return nil
})
if err != nil || actor == nil {
return nil, errNotFound
}
return actor, nil
}
type secret string
func (s secret) String() string {
if len(s) <= 3 {
return "***"
}
if len(s) <= 5 {
hidden := strings.Repeat("*", len(s)-2)
return hidden + string(s[len(s)-2:])
}
hidden := strings.Repeat("*", len(s)-3)
return string(s[0]) + hidden + string(s[len(s)-2:])
}
func (s *Service) loadAccountFromPost(r *http.Request) (*account, error) {
pw := r.PostFormValue("pw")
handle := r.PostFormValue("handle")
//a := ap.Self(i.baseIRI)
app, storage, err := s.findMatchingStorage(baseURL(r)...)
if err != nil {
return nil, err
}
baseIRI := app.GetLink()
searchIRI := SearchActorsIRI(baseIRI, ByName(handle), ByType(vocab.PersonType))
actors, err := storage.Load(searchIRI, filters.NameIs(handle), filters.HasType(vocab.PersonType))
if err != nil {
return nil, errUnauthorized
}
if actors.IsCollection() {
vocab.OnCollectionIntf(actors, func(col vocab.CollectionInterface) error {
actors = col.Collection()
return nil
})
}
var act *account
var logger = s.Logger.WithContext(lw.Ctx{
"handle": handle,
"pass": mask.S(pw).String(),
})
if act, err = checkPw(actors, []byte(pw), storage); err != nil {
logger.WithContext(lw.Ctx{"error": err.Error()}).Errorf("failed")
return nil, err
}
logger.Infof("Login success")
return act, nil
}
func reqUrl(r *http.Request) string {
proto := "http"
if r.TLS != nil {
proto = "https"
}
return fmt.Sprintf("%s://%s%s", proto, r.Host, r.RequestURI)
}
func (s *Service) Authorize(w http.ResponseWriter, r *http.Request) {
a, err := s.server(r)
if err != nil {
s.HandleError(err).ServeHTTP(w, r)
return
}
resp := a.NewResponse()
defer resp.Close()
loader, ok := a.Storage.(processing.ReadStore)
if !ok {
s.HandleError(errors.Newf("invalid storage to load actor")).ServeHTTP(w, r)
return
}
var actor vocab.Item = &auth.AnonymousActor
if s.IsValidRequest(r) {
if actor, err = s.ValidateClient(r); err != nil {
resp.SetError(osin.E_INVALID_REQUEST, err.Error())
s.redirectOrOutput(resp, w, r)
return
}
}
if c := chi.URLParam(r, "id"); c != "" {
if actorUrl, err := url.ParseRequestURI(reqUrl(r)); err == nil {
actorUrl.Path = actorUrl.Path[:strings.Index(actorUrl.Path, "/oauth")]
actorUrl.RawQuery = ""
actorUrl.Fragment = ""
if it, err := loader.Load(vocab.IRI(actorUrl.String())); err == nil {
actor = it
}
}
}
ltx := lw.Ctx{}
var overrideRedir = false
ar := a.HandleAuthorizeRequest(resp, r)
if ar != nil {
ltx["grant_type"] = ar.Type
ltx["client"] = ar.Client.GetId()
ltx["state"] = ar.State
if r.Method == http.MethodGet {
if ar.Scope == scopeAnonymousUserCreate {
// FIXME(marius): this seems like a way to backdoor our selves, we need a better way
ar.Authorized = true
overrideRedir = true
iri := ar.HttpRequest.URL.Query().Get("actor")
ar.UserData = iri
} else {
// this is basically the login page, with client being set
m := login{title: "Login"}
m.account = actor
var it vocab.Item
// check for existing application actor
for _, baseIRI := range baseURL(r) {
clientIRI := filters.ActorsType.IRI(vocab.IRI(baseIRI)).AddPath(ar.Client.GetId())
if u, err := url.ParseRequestURI(ar.Client.GetId()); err == nil && u.Host != "" {
clientIRI = vocab.IRI(ar.Client.GetId())
}
it, _ = loader.Load(clientIRI)
if !vocab.IsNil(it) {
m.client = it
m.state = ar.State
break
}
}
if vocab.IsNil(it) {
resp.SetError(osin.E_INVALID_REQUEST, fmt.Sprintf("invalid client: %+s", err))
s.redirectOrOutput(resp, w, r)
return
}
s.renderTemplate(r, w, "login", m)
return
}
} else {
handle := r.PostFormValue("handle")
if vocab.IsNil(actor) || vocab.PreferredNameOf(actor) != handle {
resp.SetError(osin.E_ACCESS_DENIED, "authorization failed")
s.Logger.WithContext(ltx).Errorf("Authorization failed")
} else {
ar.Authorized = true
ar.UserData = actor.GetLink()
ltx["handle"] = vocab.PreferredNameOf(actor)
}
}
}
a.FinishAuthorizeRequest(resp, r, ar)
if overrideRedir {
resp.Type = osin.DATA
}
ltx["return_url"] = resp.URL
logFn := s.Logger.WithContext(ltx).Warnf
if ar != nil {
ltx["authorized"] = ar.Authorized
ltx["state"] = ar.State
if ar.Authorized {
logFn = s.Logger.WithContext(ltx).Infof
}
}
logFn("Authorize")
s.redirectOrOutput(resp, w, r)
}
func checkPw(it vocab.Item, pw []byte, pwLoader PasswordChanger) (*account, error) {
acc := new(account)
found := false
err := vocab.OnActor(it, func(p *vocab.Actor) error {
if found {
return nil
}
if err := pwLoader.PasswordCheck(p, pw); err == nil {
acc.FromActor(p)
found = true
}
return nil
})
if !found {
return nil, errUnauthorized
}
return acc, err
}
func ByName(names ...string) url.Values {
q := make(url.Values)
q["name"] = names
return q
}
func ByType(types ...vocab.ActivityVocabularyType) url.Values {
q := make(url.Values)
tt := make([]string, len(types))
for i, t := range types {
tt[i] = string(t)
}
q["type"] = tt
return q
}
func ByURL(urls ...vocab.IRI) url.Values {
q := make(url.Values)
uu := make([]string, len(urls))
for i, u := range urls {
uu[i] = u.String()
}
q["url"] = uu
return q
}
func IRIWithFilters(iri vocab.IRI, searchParams ...url.Values) vocab.IRI {
q := make(url.Values)
for _, params := range searchParams {
for k, vals := range params {
if _, ok := q[k]; !ok {
q[k] = make([]string, 0)
}
q[k] = append(q[k], vals...)
}
}
if s, err := iri.URL(); err == nil {
s.RawQuery = q.Encode()
iri = vocab.IRI(s.String())
}
return iri
}
func SearchActorsIRI(baseIRI vocab.IRI, searchParams ...url.Values) vocab.IRI {
return IRIWithFilters(filters.ActorsType.IRI(baseIRI), searchParams...)
}
var AnonymousAcct = account{
username: "anonymous",
actor: &auth.AnonymousActor,
}
func (s *Service) Token(w http.ResponseWriter, r *http.Request) {
a, err := s.server(r)
if err != nil {
s.HandleError(err).ServeHTTP(w, r)
return
}
resp := a.NewResponse()
defer resp.Close()
app, storage, err := s.findMatchingStorage(baseURL(r)...)
if err != nil {
s.HandleError(err).ServeHTTP(w, r)
return
}
baseIRI := app.GetLink()
acc := &AnonymousAcct
if ar := a.HandleAccessRequest(resp, r); ar != nil {
var actorSearchIRI vocab.IRI
var actorCtx lw.Ctx
authCtx := lw.Ctx{
"grant_type": ar.Type,
"client": ar.Client.GetId(),
}
switch ar.Type {
case osin.PASSWORD:
if u, _ := url.ParseRequestURI(ar.Username); u != nil && u.Host != "" {
// NOTE(marius): here we send the full actor IRI as a username to avoid handler collisions
actorSearchIRI = vocab.IRI(ar.Username)
actorCtx = lw.Ctx{
"actor": ar.Username,
"pass": mask.S(ar.Password).String(),
}
} else {
actorSearchIRI = SearchActorsIRI(baseIRI, ByName(ar.Username))
actorCtx = lw.Ctx{
"handle": ar.Username,
"actor": actorSearchIRI,
}
}
case osin.AUTHORIZATION_CODE:
if iri, ok := ar.UserData.(vocab.IRI); ok {
actorSearchIRI = iri
}
actorCtx = lw.Ctx{
"actor": actorSearchIRI,
"code": mask.S(ar.Code).String(),
}
}
actor, err := storage.Load(actorSearchIRI)
if err != nil {
s.Logger.Errorf("%+s", err)
s.HandleError(errUnauthorized).ServeHTTP(w, r)
return
}
if ar.Type == osin.PASSWORD {
if actor.IsCollection() {
err = vocab.OnCollectionIntf(actor, func(col vocab.CollectionInterface) error {
// NOTE(marius): This is a stupid way of doing pw authentication, as it will produce collisions
// for users with the same handle/pw and it will login the first in the collection.
for _, actor := range col.Collection() {
acc, err = checkPw(actor, []byte(ar.Password), storage)
if err == nil {
return nil
}
}
return errors.Newf("No actor matched the password")
})
} else {
acc, err = checkPw(actor, []byte(ar.Password), storage)
}
actorCtx["handle"] = vocab.PreferredNameOf(actor)
if err != nil || acc == nil {
if err == nil {
err = errUnauthorized
}
resp.SetError(osin.E_ACCESS_DENIED, err.Error())
s.redirectOrOutput(resp, w, r)
return
}
ar.Authorized = acc.IsLogged()
ar.UserData = acc.actor.GetLink()
}
if ar.Type == osin.AUTHORIZATION_CODE {
_ = vocab.OnActor(actor, func(p *vocab.Actor) error {
acc = new(account)
acc.FromActor(p)
ar.Authorized = acc.IsLogged()
ar.UserData = acc.actor.GetLink()
return nil
})
}
a.FinishAccessRequest(resp, r, ar)
authCtx["authorized"] = ar.Authorized
s.Logger.WithContext(actorCtx, authCtx).Infof("Token")
}
s.redirectOrOutput(resp, w, r)
}
func annotatedRsError(status int, old error, msg string, args ...any) error {
var err error
switch status {
case http.StatusForbidden:
err = errors.NewForbidden(old, msg, args...)
case http.StatusUnauthorized:
err = errors.NewUnauthorized(old, msg, args...)
case http.StatusInternalServerError:
fallthrough
default:
err = errors.Annotatef(old, msg, args...)
}
return err
}
func (s *Service) redirectOrOutput(rs *osin.Response, w http.ResponseWriter, r *http.Request) {
if rs.IsError {
ltx := lw.Ctx{
"status_code": rs.ErrorStatusCode,
}
if rs.InternalError != nil {
ltx["err"] = fmt.Sprintf("%+v", rs.InternalError)
}
for k, vv := range rs.Output {
ltx[k] = fmt.Sprintf("%+v", vv)
}
s.Logger.WithContext(ltx).Errorf(rs.ErrorId)
} else {
// Add headers
for i, k := range rs.Headers {
for _, v := range k {
w.Header().Add(i, v)
}
}
}
if rs.Type == osin.REDIRECT {
// Output redirect with parameters
u, err := rs.GetRedirectUrl()
if err != nil {
err := annotatedRsError(http.StatusInternalServerError, err, "Error getting OAuth2 redirect URL")
s.HandleError(err).ServeHTTP(w, r)
return
}
http.Redirect(w, r, u, http.StatusFound)
return
}
// set content type if the response doesn't already have one associated with it
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", "application/json")
}
w.WriteHeader(rs.StatusCode)
encoder := json.NewEncoder(w)
if err := encoder.Encode(rs.Output); err != nil {
s.HandleError(err).ServeHTTP(w, r)
return
}
}
type login struct {
title string
account vocab.Item
state string
client vocab.Item
}
func (l login) Title() string {
return l.title
}
func (l login) Account() vocab.Item {
return l.account
}
func (l login) State() string {
return l.state
}
func (l login) Client() vocab.Item {
return l.client
}
type model interface {
Title() string
}
type authModel interface {
model
Account() vocab.Item
}
var (
defaultRenderOptions = render.Options{
FileSystem: assets.Templates,
Directory: assets.TemplatesPath,
Extensions: []string{".html"},
Funcs: []template.FuncMap{
{
"HTTPErrors": errors.HttpErrors,
"nameOf": func(it vocab.Item) template.HTML {
if vocab.IsNil(it) {
return ""
}
return template.HTML(vocab.PreferredNameOf(it))
},
"iconOf": iconOf,
"IsValid": func(it vocab.Item) bool {
return !vocab.IsNil(it)
},
},
},
Delims: render.Delims{Left: "{{", Right: "}}"},
Charset: "UTF-8",
DisableCharset: false,
HTMLContentType: "text/html",
DisableHTTPErrorRendering: false,
}
renderOptions = render.HTMLOptions{
Funcs: template.FuncMap{},
}
errRenderer = render.New(defaultRenderOptions)
ren = render.New(defaultRenderOptions)
unknownActorHandle = "Unknown"
)
func iconOf(it vocab.Item) template.HTML {
if vocab.IsNil(it) {
return ""
}
var icon vocab.Item
_ = vocab.OnObject(it, func(ob *vocab.Object) error {
if !vocab.IsNil(ob.Icon) {
icon = ob.Icon
}
return nil
})
var u string
if vocab.IsIRI(icon) {
u = icon.GetLink().String()
} else {
_ = vocab.OnObject(icon, func(ob *vocab.Object) error {
u = ob.URL.GetLink().String()
return nil
})
}
if len(u) > 0 {
return template.HTML(fmt.Sprintf(`<img src="%s" />`, u))
}
return ""
}
func redirectUri(r *http.Request) func() string {
return func() string {
if r.URL == nil || r.URL.Query() == nil {
return ""
}
q := make(url.Values)
q.Set("error", osin.E_UNAUTHORIZED_CLIENT)
q.Set("error_description", "user denied authorization request")
u, _ := url.QueryUnescape(r.URL.Query().Get("redirect_uri"))
u = fmt.Sprintf("%s?%s", u, q.Encode())
return u
}
}
func (s *Service) renderTemplate(r *http.Request, w http.ResponseWriter, name string, m authModel) {
wrt := bytes.Buffer{}
renderOptions.Funcs["redirectURI"] = redirectUri(r)
err := ren.HTML(&wrt, http.StatusOK, name, m, renderOptions)
if err == nil {
_, _ = io.Copy(w, &wrt)
return
}
err = errors.Annotatef(err, "failed to render template")
s.Logger.WithContext(lw.Ctx{"template": name, "model": fmt.Sprintf("%T", m)}).Errorf("%+s", err)
status := errors.HttpStatus(err)
if status == 0 {
status = http.StatusInternalServerError
}
_ = errRenderer.HTML(w, status, "error", err)
}
func (s *Service) HandleError(e error) http.HandlerFunc {
s.Logger.Errorf("%s", e)
return func(w http.ResponseWriter, r *http.Request) {
if errors.IsNotFound(e) {
e = errNotFound
}
wrt := bytes.Buffer{}
renderOptions.Funcs["redirectURI"] = redirectUri(r)
err := errRenderer.HTML(w, errors.HttpStatus(e), "error", e, renderOptions)
if err == nil {
_, _ = io.Copy(w, &wrt)
return
}
err = errors.Annotatef(err, "failed to render template")
s.Logger.WithContext(lw.Ctx{"template": "error", "model": fmt.Sprintf("%T", e)}).Errorf("%+s", err)
status := errors.HttpStatus(err)
if status == 0 {
status = http.StatusInternalServerError
}
_ = errRenderer.HTML(w, status, "error", err, renderOptions)
}
}
func baseURL(r *http.Request) []string {
if r == nil {
return nil
}
up := "/"
// NOTE(marius): due to the fact that the Authorize server runs behind a proxy which handles the TLS termination,
// we can't rely on the request's TLS property to determine the scheme for our URL,
// so we generate two base URLs, one for each scheme.
return []string{
fmt.Sprintf("http://%s%s", r.Host, up),
fmt.Sprintf("https://%s%s", r.Host, up),
}
}
var (
errUnauthorized = errors.Unauthorizedf("Invalid username or password")
errNotFound = errors.NotFoundf("actor not found")
errStorageNotFound = errors.NotFoundf("matching storage not found")
)
type OAuth struct {
Provider string
Code string
Token string
RefreshToken string
TokenType string
Expiry time.Time
State string
}
type pwChange struct {
title string
account vocab.Item
}
func (p pwChange) Title() string {
return p.title
}
func (p pwChange) Account() vocab.Item {
return p.account
}
// ShowChangePw
func (s *Service) ShowChangePw(w http.ResponseWriter, r *http.Request) {
actor := s.loadActorFromOauth2Session(w, r)
if actor == nil {
s.HandleError(errors.NotValidf("Unable to load actor from session")).ServeHTTP(w, r)
return
}
app, _, err := s.findMatchingStorage(baseURL(r)...)
if err != nil {
s.HandleError(errNotFound).ServeHTTP(w, r)
return
}
baseIRI := app.GetLink()
if id := chi.URLParam(r, "id"); id != "" {
act, err := s.loadAccountByID(filters.ActorsType.IRI(baseIRI).AddPath(id))
if err != nil {
s.HandleError(err).ServeHTTP(w, r)
return
}
if !act.GetID().Equals(actor.GetID(), true) {
s.HandleError(errors.NotValidf("Unable to load actor from session")).ServeHTTP(w, r)
return
}
}
m := pwChange{
title: "Change password",
account: *actor,
}
s.renderTemplate(r, w, "password", m)
}
// HandleChangePw
func (s *Service) HandleChangePw(w http.ResponseWriter, r *http.Request) {
actor := s.loadActorFromOauth2Session(w, r)
if actor == nil {
s.Logger.Errorf("Unable to load actor from session")
s.HandleError(errors.NotValidf("Unable to load actor from session")).ServeHTTP(w, r)
return
}
tok := r.URL.Query().Get("s")
pw := r.PostFormValue("pw")
pwConf := r.PostFormValue("pw-confirm")
if pw != pwConf {