forked from Dri0m/flashpoint-submission-system
/
auth.go
1153 lines (1020 loc) · 30.4 KB
/
auth.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 transport
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"math/rand"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/FlashpointProject/flashpoint-submission-system/clients"
"github.com/FlashpointProject/flashpoint-submission-system/constants"
"github.com/FlashpointProject/flashpoint-submission-system/logging"
"github.com/FlashpointProject/flashpoint-submission-system/service"
"github.com/FlashpointProject/flashpoint-submission-system/types"
"github.com/FlashpointProject/flashpoint-submission-system/utils"
"github.com/gofrs/uuid"
"github.com/gorilla/mux"
"golang.org/x/crypto/bcrypt"
)
type discordUserResponse struct {
ID string `json:"id"`
Username string `json:"username"`
Avatar string `json:"avatar"`
Discriminator string `json:"discriminator"`
PublicFlags int64 `json:"public_flags"`
Flags int64 `json:"flags"`
Locale string `json:"locale"`
MFAEnabled bool `json:"mfa_enabled"`
GlobalName *string `json:"global_name,omitempty"`
}
type StateKeeper struct {
sync.Mutex
states map[string]time.Time
expirationSeconds uint64
}
type State struct {
Nonce string `json:"nonce"`
Dest string `json:"dest"`
}
var authScopes = []types.AuthScope{
{
Name: types.AuthScopeIdentity,
Description: "Read your username, avatar, Flashpoint discord server roles, and FPFSS notification settings",
},
{
Name: types.AuthScopeProfileEdit,
Description: "Edit your notification and submission subscription settings",
},
{
Name: types.AuthScopeProfileAppsRead,
Description: "Read capabilities of your profile's client applications",
},
{
Name: types.AuthScopeSubmissionRead,
Description: "Read basic submission information (comments, metadata)",
},
{
Name: types.AuthScopeSubmissionReadFiles,
Description: "Read and download submission files",
},
{
Name: types.AuthScopeSubmissionEdit,
Description: "Edit submission information",
},
{
Name: types.AuthScopeSubmissionUpload,
Description: "Upload new submission files",
},
{
Name: types.AuthScopeFlashfreezeRead,
Description: "Read basic flashfreeze information (archive metadata)",
},
{
Name: types.AuthScopeFlashfreezeReadFiles,
Description: "Read and download flashfreeze files / archive directories",
},
{
Name: types.AuthScopeFlashfreezeUpload,
Description: "Upload new flashfreeze files",
},
{
Name: types.AuthScopeGameDataRead,
Description: "Read Game Data info / file indexes",
},
{
Name: types.AuthScopeGameDataEdit,
Description: "Edit Game Data info",
},
{
Name: types.AuthScopeGameRead,
Description: "Read Game metadata",
},
{
Name: types.AuthScopeGameEdit,
Description: "Edit Game metadata",
},
}
// Generate generates state and returns base64-encoded form
func (sk *StateKeeper) Generate(dest string) (string, error) {
sk.Clean()
u, err := uuid.NewV4()
if err != nil {
return "", err
}
s := &State{
Nonce: u.String(),
Dest: dest,
}
sk.Lock()
sk.states[s.Nonce] = time.Now()
sk.Unlock()
j, err := json.Marshal(s)
if err != nil {
return "", err
}
b := base64.URLEncoding.EncodeToString(j)
return b, nil
}
// Consume consumes base64-encoded state and returns destination URL
func (sk *StateKeeper) Consume(b string) (string, bool) {
sk.Clean()
sk.Lock()
defer sk.Unlock()
j, err := base64.URLEncoding.DecodeString(b)
if err != nil {
return "", false
}
s := &State{}
err = json.Unmarshal(j, s)
if err != nil {
return "", false
}
_, ok := sk.states[s.Nonce]
if ok {
delete(sk.states, s.Nonce)
}
return s.Dest, ok
}
func (sk *StateKeeper) Clean() {
sk.Lock()
defer sk.Unlock()
for k, v := range sk.states {
if v.After(v.Add(time.Duration(sk.expirationSeconds))) {
delete(sk.states, k)
}
}
}
type OauthState struct {
RedirectURI string `json:"redirect_uri"`
Scope string `json:"scope"`
ClientID string `json:"client_id"`
State string `json:"state"`
}
var stateKeeper = StateKeeper{
states: make(map[string]time.Time),
expirationSeconds: 30,
}
func (a *App) HandleDiscordAuth(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
dest := r.FormValue("dest")
if dest == "" {
dest = "/web/profile"
}
state, err := stateKeeper.Generate(dest)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to generate state", http.StatusInternalServerError))
return
}
http.Redirect(w, r, a.Conf.OauthConf.AuthCodeURL(state), http.StatusTemporaryRedirect)
}
func (a *App) HandleDiscordCallback(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// verify state
dest, ok := stateKeeper.Consume(r.FormValue("state"))
if !ok {
writeError(ctx, w, perr("state does not match", http.StatusBadRequest))
return
}
// obtain token
token, err := a.Conf.OauthConf.Exchange(context.Background(), r.FormValue("code"))
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to obtain discord auth token", http.StatusInternalServerError))
return
}
// obtain user data
resp, err := a.Conf.OauthConf.Client(context.Background(), token).Get("https://discordapp.com/api/users/@me")
if err != nil || resp.StatusCode != 200 {
writeError(ctx, w, perr("failed to obtain discord user data", http.StatusInternalServerError))
return
}
defer resp.Body.Close()
var discordUserResp discordUserResponse
err = json.NewDecoder(resp.Body).Decode(&discordUserResp)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to parse discord response", http.StatusInternalServerError))
return
}
uid, err := strconv.ParseInt(discordUserResp.ID, 10, 64)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to parse discord response", http.StatusInternalServerError))
return
}
username := discordUserResp.Username
if discordUserResp.GlobalName != nil && *discordUserResp.GlobalName != "" {
username = *discordUserResp.GlobalName
}
discordUser := &types.DiscordUser{
ID: uid,
Username: username,
Avatar: discordUserResp.Avatar,
Discriminator: discordUserResp.Discriminator,
PublicFlags: discordUserResp.PublicFlags,
Flags: discordUserResp.Flags,
Locale: discordUserResp.Locale,
MFAEnabled: discordUserResp.MFAEnabled,
}
// Check if internal or external, based on redirect_uri host
ipAddr := logging.RequestGetRemoteAddress(r)
// Logging into FPFSS itself
authToken, err := a.Service.SaveUser(ctx, discordUser, types.AuthScopeAll, "FPFSS", ipAddr)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, dberr(err))
return
}
if err := a.CC.SetSecureCookie(w, utils.Cookies.Login, service.MapAuthToken(authToken), (int)(a.Conf.SessionExpirationSeconds)); err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to set cookie", http.StatusInternalServerError))
return
}
if len(dest) == 0 || !isReturnURLValid(dest) {
http.Redirect(w, r, "/web/profile", http.StatusFound)
return
}
http.Redirect(w, r, dest, http.StatusFound)
}
func (a *App) HandleOauthAuthorize(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
err := r.ParseForm()
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to parse form", http.StatusBadRequest))
return
}
// Validate client application
client_id := r.Form.Get("client_id")
if client_id == "" {
writeError(ctx, w, perr("missing client_id", http.StatusBadRequest))
return
}
var client *types.ClientApplication
for _, app := range clients.ClientApps {
if app.ClientId == client_id {
client = &app
break
}
}
if client == nil {
writeError(ctx, w, perr("invalid client_id", http.StatusBadRequest))
return
}
// Validate scope
scope := r.Form.Get("scope")
if scope == "" {
scope = types.AuthScopeIdentity
}
var validScopes []string
for _, scopeStr := range strings.Split(scope, " ") {
for _, allowedClientScope := range client.Scopes {
if scopeStr == allowedClientScope {
validScopes = append(validScopes, scopeStr)
}
}
}
// Validate redirect uri
redirect_uri := r.Form.Get("redirect_uri")
if redirect_uri == "" {
writeError(ctx, w, perr("missing redirect_uri", http.StatusBadRequest))
return
}
valid := false
for _, allowedRedirectURI := range client.RedirectURIs {
if redirect_uri == allowedRedirectURI {
valid = true
break
}
}
if !valid {
writeError(ctx, w, perr("invalid redirect_uri", http.StatusBadRequest))
return
}
if r.Method == http.MethodPost {
// User has authorized app, generate a code and redirect
state := r.Form.Get("state")
u, err := url.Parse(redirect_uri)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("invalid redirect_uri", http.StatusBadRequest))
return
}
q := u.Query()
// Generate code
code, err := a.AuthCodeStorage.NewToken(utils.UserID(ctx), client.ClientId, redirect_uri, strings.Join(validScopes, " "), logging.RequestGetRemoteAddress(r))
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to create auth code", http.StatusInternalServerError))
return
}
q.Add("code", code.Code)
q.Add("state", state)
u.RawQuery = q.Encode()
w.Write([]byte(u.String()))
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
return
}
// Get auth page data
bpd, err := a.Service.GetBasePageData(ctx)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failure getting page data", http.StatusInternalServerError))
return
}
var states = types.DeviceAuthStates{
Pending: types.DeviceFlowPending,
Denied: types.DeviceFlowErrorDenied,
Expired: types.DeviceFlowErrorExpired,
Complete: types.DeviceFlowComplete,
}
var scopesList []types.AuthScope
for _, scope := range validScopes {
for _, authScope := range authScopes {
if scope == authScope.Name {
scopesList = append(scopesList, authScope)
}
}
}
pageData := types.DeviceAuthPageData{
BasePageData: *bpd,
// Reuse
Token: &types.DeviceFlowToken{
ClientApplication: client,
Scope: strings.Join(validScopes, " "),
FlowState: types.DeviceFlowPending,
},
States: states,
Scopes: scopesList,
}
a.RenderTemplates(ctx, w, r, pageData,
"templates/oauth-authorize.gohtml")
}
func (a *App) HandleLogout(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
const msg = "unable to log out, please clear your cookies"
cookieMap, err := a.CC.GetSecureCookie(r, utils.Cookies.Login)
if err != nil && !errors.Is(err, http.ErrNoCookie) {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr(msg, http.StatusInternalServerError))
return
}
token, err := service.ParseAuthToken(cookieMap) // TODO move this into the Logout method
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr(msg, http.StatusInternalServerError))
return
}
if err := a.Service.Logout(ctx, token.Secret); err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr(msg, http.StatusInternalServerError))
return
}
utils.UnsetCookie(w, utils.Cookies.Login)
http.Redirect(w, r, "/web", http.StatusFound)
}
func (a *App) HandlePollDeviceAuth(w http.ResponseWriter, ctx context.Context, deviceCode string, clientID string) {
// Get device auth token from storage
dfToken := a.DFStorage.GetUserAuthToken(deviceCode, clientID)
if dfToken == nil {
writeError(ctx, w, perr("no tokens found", http.StatusBadRequest))
return
}
switch dfToken.FlowState {
case types.DeviceFlowComplete:
if dfToken.AuthToken == nil {
writeError(ctx, w, perr("auth token already claimed", http.StatusInternalServerError))
return
}
// Encode the auth token
authJson, err := json.Marshal(dfToken.AuthToken)
if err != nil {
writeError(ctx, w, perr("failure marshalling token", http.StatusInternalServerError))
return
}
encodedData := base64.StdEncoding.EncodeToString(authJson)
jsonData := types.DeviceFlowPollResponse{
Token: encodedData,
}
writeResponse(ctx, w, jsonData, http.StatusOK)
return
case types.DeviceFlowPending:
jsonData := types.DeviceFlowPollResponse{
Error: "authorization_pending",
}
writeResponse(ctx, w, jsonData, http.StatusOK)
return
case types.DeviceFlowErrorDenied:
jsonData := types.DeviceFlowPollResponse{
Error: "access_denied",
}
writeResponse(ctx, w, jsonData, http.StatusOK)
return
case types.DeviceFlowErrorExpired:
jsonData := types.DeviceFlowPollResponse{
Error: "expired_token",
}
writeResponse(ctx, w, jsonData, http.StatusOK)
return
}
}
func (a *App) HandleOauthDevice(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method == http.MethodGet {
// User confirmation page
query := r.URL.Query()
code := query.Get("user_code")
// Get device auth token from storage
token, err := a.DFStorage.Get(code)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr(err.Error(), http.StatusBadRequest))
return
}
// Load scopes
var scopesList []types.AuthScope
for _, scope := range strings.Split(token.Scope, " ") {
for _, authScope := range authScopes {
if scope == authScope.Name {
scopesList = append(scopesList, authScope)
}
}
}
bpd, err := a.Service.GetBasePageData(ctx)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failure getting page data", http.StatusInternalServerError))
return
}
var states = types.DeviceAuthStates{
Pending: types.DeviceFlowPending,
Denied: types.DeviceFlowErrorDenied,
Expired: types.DeviceFlowErrorExpired,
Complete: types.DeviceFlowComplete,
}
pageData := types.DeviceAuthPageData{
BasePageData: *bpd,
Token: token,
States: states,
Scopes: scopesList,
}
a.RenderTemplates(ctx, w, r, pageData,
"templates/oauth-device-auth.gohtml")
return
}
if r.Method == http.MethodPost {
// Client asking for a new device code
err := r.ParseForm()
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to parse form", http.StatusBadRequest))
return
}
// Validate client application
client_id := r.Form.Get("client_id")
if client_id == "" {
writeError(ctx, w, perr("invalid_client", http.StatusBadRequest))
return
}
var client *types.ClientApplication
for _, app := range clients.ClientApps {
if app.ClientId == client_id {
client = &app
break
}
}
if client == nil {
writeError(ctx, w, perr("invalid_client", http.StatusBadRequest))
return
}
// Validate scope
scope := r.Form.Get("scope")
if scope != "" {
// Filter out invalid scopes
var validScopes []string
for _, scopeStr := range strings.Split(scope, " ") {
for _, allowedClientScope := range client.Scopes {
if scopeStr == allowedClientScope {
validScopes = append(validScopes, scopeStr)
}
}
}
scope = strings.Join(validScopes, " ")
if scope == "" {
// No valid scopes found, but scope given, give advice
scopeNames := make([]string, len(authScopes))
for i, authScope := range authScopes {
scopeNames[i] = authScope.Name
}
writeError(ctx, w, perr("invalid scope: Must be of ["+strings.Join(scopeNames, ", ")+"]", http.StatusBadRequest))
return
}
} else {
scope = types.AuthScopeIdentity
}
// Issue token
token, err := a.DFStorage.NewToken(scope, client)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to create token", http.StatusInternalServerError))
return
}
writeResponse(ctx, w, token, http.StatusOK)
return
}
}
func GetClientId(r *http.Request) (*types.ClientApplication, bool) {
// Validate client application
client_id := r.Form.Get("client_id")
if client_id == "" {
return nil, false
}
var client *types.ClientApplication
for _, app := range clients.ClientApps {
if app.ClientId == client_id {
client = &app
break
}
}
if client == nil {
return nil, false
}
return client, true
}
func (a *App) GetServerUser(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
params := mux.Vars(r)
uidStr := params[constants.ResourceKeyUserID]
uid, err := strconv.ParseInt(uidStr, 10, 64)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("invalid user id", http.StatusBadRequest))
return
}
user, err := a.Service.GetServerUser(ctx, uid)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to get user server info", http.StatusInternalServerError))
return
}
writeResponse(ctx, w, user, http.StatusOK)
}
func (a *App) HandleOauthDeviceResponse(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
query := r.URL.Query()
code := query.Get("user_code")
// Get device auth token from storage
token, err := a.DFStorage.Get(code)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr(err.Error(), http.StatusBadRequest))
return
}
action := query.Get("action")
if action == "approve" {
// Create a new auth token
uid := utils.UserID(ctx)
ipAddr := logging.RequestGetRemoteAddress(r)
authToken, err := a.Service.GenAuthToken(ctx, uid, token.Scope, token.ClientApplication.ClientId, ipAddr)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to create new auth token", http.StatusInternalServerError))
return
}
// Save inside device auth
token.FlowState = types.DeviceFlowComplete
token.AuthToken = authToken
err = a.DFStorage.Save(token)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to save device token", http.StatusInternalServerError))
return
}
} else if action == "deny" {
token.FlowState = types.DeviceFlowErrorDenied
err := a.DFStorage.Save(token)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to save token", http.StatusInternalServerError))
return
}
} else {
writeError(ctx, w, perr("invalid action, must be 'approve' or 'deny'", http.StatusBadRequest))
return
}
}
func (a *App) HandleOauthToken(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
err := r.ParseForm()
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to parse form", http.StatusBadRequest))
return
}
ipAddr := logging.RequestGetRemoteAddress(r)
grant_type := r.Form.Get("grant_type")
switch grant_type {
case "authorization_code":
{
code := r.Form.Get("code")
if code == "" {
writeError(ctx, w, perr("invalid_request", http.StatusBadRequest))
return
}
token, err := a.AuthCodeStorage.Get(code)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr(err.Error(), http.StatusBadRequest))
return
}
authToken, err := a.Service.GenAuthToken(ctx, token.UserID, token.Scope, token.ClientID, token.IPAddr)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to create new auth token", http.StatusInternalServerError))
return
}
authJson, err := json.Marshal(authToken)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to marshal token", http.StatusInternalServerError))
return
}
encodedData := base64.StdEncoding.EncodeToString(authJson)
token.State = types.AuthCodeComplete
err = a.AuthCodeStorage.Save(token)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to save token", http.StatusInternalServerError))
return
}
authTokenResponse := &types.AuthTokenResponse{
AccessToken: encodedData,
TokenType: "Bearer",
ExpiresIn: a.Conf.SessionExpirationSeconds,
}
respData, err := json.Marshal(authTokenResponse)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to marshal token", http.StatusInternalServerError))
return
}
w.Write(respData)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
return
}
case "client_credentials":
{
client_id, client_secret, ok := r.BasicAuth()
if !ok {
writeError(ctx, w, perr("invalid_client", http.StatusBadRequest))
return
}
var client *types.ClientApplication
for _, app := range clients.ClientApps {
if app.ClientId == client_id {
client = &app
break
}
}
if client == nil {
writeError(ctx, w, perr("invalid_client", http.StatusBadRequest))
return
}
stored_secret, err := a.Service.GetClientSecret(ctx, client.ClientId)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to get client secret from storage", http.StatusInternalServerError))
return
}
if client_secret == "" {
writeError(ctx, w, perr("invalid_client", http.StatusBadRequest))
return
}
if !matchClientSecret(client_secret, stored_secret) {
writeError(ctx, w, perr("unauthorized_client", http.StatusBadRequest))
return
}
// Validate scope
scope := r.Form.Get("scope")
if scope != "" {
// Filter out invalid scopes
var validScopes []string
for _, scopeStr := range strings.Split(scope, " ") {
for _, allowedClientScope := range client.ClientCredsScopes {
if scopeStr == allowedClientScope {
validScopes = append(validScopes, scopeStr)
}
}
}
scope = strings.Join(validScopes, " ")
if scope == "" {
// No valid scopes found, but scope given, give advice
scopeNames := make([]string, len(authScopes))
for i, authScope := range authScopes {
scopeNames[i] = authScope.Name
}
}
} else {
scope = types.AuthScopeIdentity
}
authToken, err := a.Service.GenAuthToken(ctx, client.UserID, scope, client.ClientId, ipAddr)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to create new auth token", http.StatusInternalServerError))
return
}
authJson, err := json.Marshal(authToken)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to marshal token", http.StatusInternalServerError))
return
}
encodedData := base64.StdEncoding.EncodeToString(authJson)
authTokenResponse := &types.AuthTokenResponse{
AccessToken: encodedData,
TokenType: "Bearer",
ExpiresIn: a.Conf.SessionExpirationSeconds,
}
respData, err := json.Marshal(authTokenResponse)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to marshal token", http.StatusInternalServerError))
return
}
w.Write(respData)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
return
}
case "urn:ietf:params:oauth:grant-type:device_code":
{
// Validate client application
client, valid := GetClientId(r)
if !valid {
writeError(ctx, w, perr("invalid_client", http.StatusBadRequest))
return
}
deviceCode := r.Form.Get("device_code")
if deviceCode == "" {
writeError(ctx, w, perr("invalid_request", http.StatusBadRequest))
return
}
// Device code given, must be polling
a.HandlePollDeviceAuth(w, ctx, deviceCode, client.ClientId)
return
}
default:
{
writeError(ctx, w, perr("invalid_grant", http.StatusBadRequest))
return
}
}
}
func (a *App) HandleApproveDevice(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
query := r.URL.Query()
code := query.Get("user_code")
// Get device auth token from storage
token, err := a.DFStorage.Get(code)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr(err.Error(), http.StatusBadRequest))
return
}
if r.Method == http.MethodPost {
// POST User has responded
action := query.Get("action")
if action == "approve" {
// Create a new auth token
uid := utils.UserID(ctx)
ipAddr := logging.RequestGetRemoteAddress(r)
authToken, err := a.Service.GenAuthToken(ctx, uid, token.Scope, token.ClientApplication.ClientId, ipAddr)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to create new auth token", http.StatusInternalServerError))
return
}
// Save inside device auth
token.FlowState = types.DeviceFlowComplete
token.AuthToken = authToken
err = a.DFStorage.Save(token)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to save device token", http.StatusInternalServerError))
return
}
} else if action == "deny" {
token.FlowState = types.DeviceFlowErrorDenied
err := a.DFStorage.Save(token)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failed to save token", http.StatusInternalServerError))
return
}
} else {
writeError(ctx, w, perr("invalid action, must be 'approve' or 'deny'", http.StatusBadRequest))
return
}
// POST Action complete continue to show result same as GET
}
// Load scopes
var scopesList []types.AuthScope
for _, scope := range strings.Split(token.Scope, " ") {
for _, authScope := range authScopes {
if scope == authScope.Name {
scopesList = append(scopesList, authScope)
}
}
}
bpd, err := a.Service.GetBasePageData(ctx)
if err != nil {
utils.LogCtx(ctx).Error(err)
writeError(ctx, w, perr("failure getting page data", http.StatusInternalServerError))
return
}
var states = types.DeviceAuthStates{
Pending: types.DeviceFlowPending,
Denied: types.DeviceFlowErrorDenied,
Expired: types.DeviceFlowErrorExpired,
Complete: types.DeviceFlowComplete,
}
pageData := types.DeviceAuthPageData{
BasePageData: *bpd,
Token: token,
States: states,
Scopes: scopesList,
}
a.RenderTemplates(ctx, w, r, pageData,
"templates/device_auth.gohtml")
}
const deviceCodeCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
const userCodeCharset = "BCDFGHJKLMNPQRSTVWXZ"
type DeviceFlowUserAuthToken struct {
AuthToken string
DeviceCode string
}
type AuthCodeStorage struct {
tokens map[string]*types.AuthCodeToken
}
type DeviceFlowStorage struct {
tokens map[string]*types.DeviceFlowToken
authTokens map[int64]*[]DeviceFlowUserAuthToken
verificationUrl string
}
func NewDeviceFlowStorage(baseUrl string) *DeviceFlowStorage {
return &DeviceFlowStorage{
tokens: make(map[string]*types.DeviceFlowToken),
authTokens: make(map[int64]*[]DeviceFlowUserAuthToken),
verificationUrl: strings.TrimRight(baseUrl, "/") + "/auth/device",
}
}
func (s *DeviceFlowStorage) GetUserAuthToken(deviceCode string, clientID string) *types.DeviceFlowToken {
var dfToken types.DeviceFlowToken
for i, token := range s.tokens {
if token.DeviceCode == deviceCode && token.ClientApplication.ClientId == clientID {
dfToken = *token
// Remove from server now it has been claimed
s.tokens[i].AuthToken = nil
}
}
return &dfToken
}
func (s *DeviceFlowStorage) SaveUserAuthToken(uid int64, token string, deviceCode string) {