forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
manager.go
747 lines (622 loc) · 20.6 KB
/
manager.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
package tokens
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"sort"
"time"
"github.com/rancher/norman/httperror"
"github.com/rancher/norman/types"
"github.com/rancher/rancher/pkg/auth/util"
"github.com/rancher/rancher/pkg/randomtoken"
"github.com/rancher/types/apis/core/v1"
"github.com/rancher/types/apis/management.cattle.io/v3"
clientv3 "github.com/rancher/types/client/management/v3"
"github.com/rancher/types/config"
"github.com/sirupsen/logrus"
apicorev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/tools/cache"
)
// TODO Cleanup error logging. If error is being returned, use errors.wrap to return and dont log here
const (
userPrincipalIndex = "authn.management.cattle.io/user-principal-index"
UserIDLabel = "authn.management.cattle.io/token-userId"
tokenKeyIndex = "authn.management.cattle.io/token-key-index"
secretNameEnding = "-secret"
secretNamespace = "cattle-system"
)
func NewManager(ctx context.Context, apiContext *config.ScaledContext) *Manager {
informer := apiContext.Management.Users("").Controller().Informer()
informer.AddIndexers(map[string]cache.IndexFunc{userPrincipalIndex: userPrincipalIndexer})
tokenInformer := apiContext.Management.Tokens("").Controller().Informer()
tokenInformer.AddIndexers(map[string]cache.IndexFunc{tokenKeyIndex: tokenKeyIndexer})
return &Manager{
ctx: ctx,
tokensClient: apiContext.Management.Tokens(""),
userIndexer: informer.GetIndexer(),
tokenIndexer: tokenInformer.GetIndexer(),
userAttributes: apiContext.Management.UserAttributes(""),
userAttributeLister: apiContext.Management.UserAttributes("").Controller().Lister(),
userLister: apiContext.Management.Users("").Controller().Lister(),
secrets: apiContext.Core.Secrets(""),
secretLister: apiContext.Core.Secrets("").Controller().Lister(),
}
}
type Manager struct {
ctx context.Context
tokensClient v3.TokenInterface
userAttributes v3.UserAttributeInterface
userAttributeLister v3.UserAttributeLister
userIndexer cache.Indexer
tokenIndexer cache.Indexer
userLister v3.UserLister
secrets v1.SecretInterface
secretLister v1.SecretLister
}
func userPrincipalIndexer(obj interface{}) ([]string, error) {
user, ok := obj.(*v3.User)
if !ok {
return []string{}, nil
}
return user.PrincipalIDs, nil
}
func tokenKeyIndexer(obj interface{}) ([]string, error) {
token, ok := obj.(*v3.Token)
if !ok {
return []string{}, nil
}
return []string{token.Token}, nil
}
// createDerivedToken will create a jwt token for the authenticated user
func (m *Manager) createDerivedToken(jsonInput clientv3.Token, tokenAuthValue string) (v3.Token, int, error) {
logrus.Debug("Create Derived Token Invoked")
token, _, err := m.getToken(tokenAuthValue)
if err != nil {
return v3.Token{}, 401, err
}
derivedToken := v3.Token{
UserPrincipal: token.UserPrincipal,
IsDerived: true,
TTLMillis: jsonInput.TTLMillis,
UserID: token.UserID,
AuthProvider: token.AuthProvider,
ProviderInfo: token.ProviderInfo,
Description: jsonInput.Description,
ClusterName: jsonInput.ClusterID,
}
derivedToken, err = m.createToken(&derivedToken)
return derivedToken, 0, err
}
func (m *Manager) createToken(k8sToken *v3.Token) (v3.Token, error) {
key, err := randomtoken.Generate()
if err != nil {
logrus.Errorf("Failed to generate token key: %v", err)
return v3.Token{}, fmt.Errorf("failed to generate token key")
}
labels := make(map[string]string)
labels[UserIDLabel] = k8sToken.UserID
k8sToken.APIVersion = "management.cattle.io/v3"
k8sToken.Kind = "Token"
k8sToken.Token = key
k8sToken.ObjectMeta = metav1.ObjectMeta{
GenerateName: "token-",
Labels: labels,
}
createdToken, err := m.tokensClient.Create(k8sToken)
if err != nil {
return v3.Token{}, err
}
return *createdToken, nil
}
func (m *Manager) updateToken(token *v3.Token) (*v3.Token, error) {
return m.tokensClient.Update(token)
}
func (m *Manager) getToken(tokenAuthValue string) (*v3.Token, int, error) {
tokenName, tokenKey := SplitTokenParts(tokenAuthValue)
lookupUsingClient := false
objs, err := m.tokenIndexer.ByIndex(tokenKeyIndex, tokenKey)
if err != nil {
if apierrors.IsNotFound(err) {
lookupUsingClient = true
} else {
return nil, 0, fmt.Errorf("failed to retrieve auth token from cache, error: %v", err)
}
} else if len(objs) == 0 {
lookupUsingClient = true
}
storedToken := &v3.Token{}
if lookupUsingClient {
storedToken, err = m.tokensClient.Get(tokenName, metav1.GetOptions{})
if err != nil {
return nil, 404, fmt.Errorf("failed to retrieve auth token, error: %#v", err)
}
} else {
storedToken = objs[0].(*v3.Token)
}
if storedToken.Token != tokenKey || storedToken.ObjectMeta.Name != tokenName {
return nil, 0, fmt.Errorf("Invalid auth token value")
}
if IsExpired(*storedToken) {
return storedToken, 410, fmt.Errorf("Auth Token has expired")
}
return storedToken, 0, nil
}
//GetTokens will list all(login and derived, and even expired) tokens of the authenticated user
func (m *Manager) getTokens(tokenAuthValue string) ([]v3.Token, int, error) {
logrus.Debug("LIST Tokens Invoked")
tokens := make([]v3.Token, 0)
storedToken, _, err := m.getToken(tokenAuthValue)
if err != nil {
return tokens, 401, err
}
userID := storedToken.UserID
set := labels.Set(map[string]string{UserIDLabel: userID})
tokenList, err := m.tokensClient.List(metav1.ListOptions{LabelSelector: set.AsSelector().String()})
if err != nil {
return tokens, 0, fmt.Errorf("error getting tokens for user: %v selector: %v err: %v", userID, set.AsSelector().String(), err)
}
for _, t := range tokenList.Items {
if IsExpired(t) {
t.Expired = true
}
tokens = append(tokens, t)
}
return tokens, 0, nil
}
func (m *Manager) deleteToken(tokenAuthValue string) (int, error) {
logrus.Debug("DELETE Token Invoked")
storedToken, status, err := m.getToken(tokenAuthValue)
if err != nil {
if status == 404 {
return 0, nil
} else if status != 410 {
return 401, err
}
}
return m.deleteTokenByName(storedToken.Name)
}
func (m *Manager) deleteTokenByName(tokenName string) (int, error) {
err := m.tokensClient.Delete(tokenName, &metav1.DeleteOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
return 0, nil
}
return 500, fmt.Errorf("failed to delete token")
}
logrus.Debug("Deleted Token")
return 0, nil
}
//getToken will get the token by ID
func (m *Manager) getTokenByID(tokenAuthValue string, tokenID string) (v3.Token, int, error) {
logrus.Debug("GET Token Invoked")
token := &v3.Token{}
storedToken, _, err := m.getToken(tokenAuthValue)
if err != nil {
return *token, 401, err
}
token, err = m.tokensClient.Get(tokenID, metav1.GetOptions{})
if err != nil {
return v3.Token{}, 404, err
}
if token.UserID != storedToken.UserID {
return v3.Token{}, 404, fmt.Errorf("%v not found", tokenID)
}
if IsExpired(*token) {
token.Expired = true
}
return *token, 0, nil
}
func (m *Manager) deriveToken(request *types.APIContext) error {
r := request.Request
tokenAuthValue := GetTokenAuthFromRequest(r)
if tokenAuthValue == "" {
// no cookie or auth header, cannot authenticate
return httperror.NewAPIErrorLong(http.StatusUnauthorized, util.GetHTTPErrorCode(http.StatusUnauthorized), "No valid token cookie or auth header")
}
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
return httperror.NewAPIError(httperror.InvalidBodyContent, fmt.Sprintf("%s", err))
}
jsonInput := clientv3.Token{}
err = json.Unmarshal(bytes, &jsonInput)
if err != nil {
return httperror.NewAPIError(httperror.InvalidFormat, fmt.Sprintf("%s", err))
}
var token v3.Token
var status int
// create derived token
token, status, err = m.createDerivedToken(jsonInput, tokenAuthValue)
if err != nil {
logrus.Errorf("deriveToken failed with error: %v", err)
if status == 0 {
status = http.StatusInternalServerError
}
return httperror.NewAPIErrorLong(status, util.GetHTTPErrorCode(status), fmt.Sprintf("%v", err))
}
tokenData, err := ConvertTokenResource(request.Schema, token)
if err != nil {
return err
}
tokenData["token"] = token.ObjectMeta.Name + ":" + token.Token
request.WriteResponse(http.StatusCreated, tokenData)
return nil
}
func (m *Manager) listTokens(request *types.APIContext) error {
r := request.Request
// TODO switch to X-API-UserId header
tokenAuthValue := GetTokenAuthFromRequest(r)
if tokenAuthValue == "" {
// no cookie or auth header, cannot authenticate
return httperror.NewAPIErrorLong(http.StatusUnauthorized, util.GetHTTPErrorCode(http.StatusUnauthorized), "No valid token cookie or auth header")
}
//getToken
tokens, status, err := m.getTokens(tokenAuthValue)
if err != nil {
logrus.Errorf("GetToken failed with error: %v", err)
if status == 0 {
status = http.StatusInternalServerError
}
return httperror.NewAPIErrorLong(status, util.GetHTTPErrorCode(status), fmt.Sprintf("%v", err))
}
currentAuthToken, _, err := m.getToken(tokenAuthValue)
if err != nil {
return err
}
tokensFromStore := make([]map[string]interface{}, len(tokens))
for _, token := range tokens {
token.Current = currentAuthToken.Name == token.Name && !currentAuthToken.IsDerived
tokenData, err := ConvertTokenResource(request.Schema, token)
if err != nil {
return err
}
tokensFromStore = append(tokensFromStore, tokenData)
}
request.WriteResponse(http.StatusOK, tokensFromStore)
return nil
}
func (m *Manager) logout(actionName string, action *types.Action, request *types.APIContext) error {
r := request.Request
w := request.Response
tokenAuthValue := GetTokenAuthFromRequest(r)
if tokenAuthValue == "" {
// no cookie or auth header, cannot authenticate
return httperror.NewAPIErrorLong(http.StatusUnauthorized, util.GetHTTPErrorCode(http.StatusUnauthorized), "No valid token cookie or auth header")
}
isSecure := false
if r.URL.Scheme == "https" {
isSecure = true
}
tokenCookie := &http.Cookie{
Name: CookieName,
Value: "",
Secure: isSecure,
Path: "/",
HttpOnly: true,
MaxAge: -1,
Expires: time.Date(1982, time.February, 10, 23, 0, 0, 0, time.UTC),
}
http.SetCookie(w, tokenCookie)
//getToken
status, err := m.deleteToken(tokenAuthValue)
if err != nil {
logrus.Errorf("DeleteToken failed with error: %v", err)
if status == 0 {
status = http.StatusInternalServerError
}
return httperror.NewAPIErrorLong(status, util.GetHTTPErrorCode(status), fmt.Sprintf("%v", err))
}
return nil
}
func (m *Manager) getTokenFromRequest(request *types.APIContext) error {
// TODO switch to X-API-UserId header
r := request.Request
tokenAuthValue := GetTokenAuthFromRequest(r)
if tokenAuthValue == "" {
// no cookie or auth header, cannot authenticate
return httperror.NewAPIErrorLong(http.StatusUnauthorized, util.GetHTTPErrorCode(http.StatusUnauthorized), "No valid token cookie or auth header")
}
tokenID := request.ID
currentAuthToken, _, err := m.getToken(tokenAuthValue)
if err != nil {
return err
}
//getToken
token, status, err := m.getTokenByID(tokenAuthValue, tokenID)
if err != nil {
logrus.Errorf("GetToken failed with error: %v", err)
if status == 0 {
status = http.StatusInternalServerError
} else if status == 410 {
status = http.StatusNotFound
}
return httperror.NewAPIErrorLong(status, util.GetHTTPErrorCode(status), fmt.Sprintf("%v", err))
}
token.Current = currentAuthToken.Name == token.Name && !currentAuthToken.IsDerived
tokenData, err := ConvertTokenResource(request.Schema, token)
if err != nil {
return err
}
request.WriteResponse(http.StatusOK, tokenData)
return nil
}
func (m *Manager) removeToken(request *types.APIContext) error {
// TODO switch to X-API-UserId header
r := request.Request
tokenAuthValue := GetTokenAuthFromRequest(r)
if tokenAuthValue == "" {
// no cookie or auth header, cannot authenticate
return httperror.NewAPIErrorLong(http.StatusUnauthorized, util.GetHTTPErrorCode(http.StatusUnauthorized), "No valid token cookie or auth header")
}
tokenID := request.ID
//getToken
t, status, err := m.getTokenByID(tokenAuthValue, tokenID)
if err != nil {
if status != 410 {
logrus.Errorf("DeleteToken Failed to fetch the token to delete with error: %v", err)
if status == 0 {
status = http.StatusInternalServerError
}
return httperror.NewAPIErrorLong(status, util.GetHTTPErrorCode(status), fmt.Sprintf("%v", err))
}
}
currentAuthToken, _, err := m.getToken(tokenAuthValue)
if err != nil {
return err
}
if currentAuthToken.Name == t.Name && !currentAuthToken.IsDerived {
return httperror.NewAPIErrorLong(http.StatusBadRequest, util.GetHTTPErrorCode(http.StatusBadRequest), "Cannot delete token for current session. Use logout instead")
}
if _, err := m.deleteTokenByName(t.Name); err != nil {
return err
}
request.WriteResponse(http.StatusNoContent, nil)
return nil
}
// CreateSecret saves the secret in k8s. Secret is saved under the userID-secret with
// key being the provider and data being the providers secret
func (m *Manager) CreateSecret(userID, provider, secret string) error {
_, err := m.secretLister.Get(secretNamespace, userID+secretNameEnding)
// An error either means it already exists or something bad happened
if err != nil {
if !apierrors.IsNotFound(err) {
return err
}
// The secret doesn't exist so create it
data := make(map[string]string)
data[provider] = secret
s := apicorev1.Secret{
StringData: data,
}
s.ObjectMeta = metav1.ObjectMeta{
Name: userID + secretNameEnding,
Namespace: secretNamespace,
}
_, err = m.secrets.Create(&s)
return err
}
// No error means the secret already exists and needs to be updated
return m.UpdateSecret(userID, provider, secret)
}
func (m *Manager) GetSecret(userID string, provider string, fallbackTokens []*v3.Token) (string, error) {
cachedSecret, err := m.secretLister.Get(secretNamespace, userID+secretNameEnding)
if err != nil && !apierrors.IsNotFound(err) {
return "", err
}
if (err == nil) && cachedSecret != nil && string(cachedSecret.Data[provider]) != "" {
return string(cachedSecret.Data[provider]), nil
}
for _, token := range fallbackTokens {
secret := token.ProviderInfo["access_token"]
if secret != "" {
return secret, nil
}
}
return "", err // The not found error from above
}
func (m *Manager) UpdateSecret(userID, provider, secret string) error {
cachedSecret, err := m.secretLister.Get(secretNamespace, userID+secretNameEnding)
if err != nil {
return err
}
cachedSecret = cachedSecret.DeepCopy()
cachedSecret.Data[provider] = []byte(secret)
_, err = m.secrets.Update(cachedSecret)
return err
}
func (m *Manager) EnsureAndGetUserAttribute(userID string) (*v3.UserAttribute, bool, error) {
attribs, err := m.userAttributeLister.Get("", userID)
if err != nil && !apierrors.IsNotFound(err) {
return nil, false, err
}
if attribs == nil {
attribs, err = m.userAttributes.Get(userID, metav1.GetOptions{})
if err != nil && !apierrors.IsNotFound(err) {
return nil, false, err
}
}
if attribs != nil && attribs.Name != "" {
return attribs.DeepCopy(), false, nil
}
user, err := m.userLister.Get("", userID)
if err != nil {
return nil, false, err
}
attribs = &v3.UserAttribute{
ObjectMeta: metav1.ObjectMeta{
Name: userID,
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: user.APIVersion,
Kind: user.Kind,
UID: user.UID,
Name: user.Name,
},
},
},
GroupPrincipals: map[string]v3.Principals{},
LastRefresh: "",
NeedsRefresh: false,
}
return attribs, true, nil
}
func (m *Manager) UserAttributeCreateOrUpdate(userID, provider string, groupPrincipals []v3.Principal) error {
attribs, needCreate, err := m.EnsureAndGetUserAttribute(userID)
if err != nil {
return err
}
// Exists, just update if necessary
attribs = attribs.DeepCopy()
if m.UserAttributeChanged(attribs, provider, groupPrincipals) {
attribs.GroupPrincipals[provider] = v3.Principals{Items: groupPrincipals}
if !needCreate {
_, err := m.userAttributes.Update(attribs)
if err != nil {
return err
}
}
return nil
}
if needCreate {
_, err := m.userAttributes.Create(attribs)
if err != nil {
return err
}
}
return nil
}
func (m *Manager) UserAttributeChanged(attribs *v3.UserAttribute, provider string, groupPrincipals []v3.Principal) bool {
oldSet := []string{}
newSet := []string{}
for _, principal := range attribs.GroupPrincipals[provider].Items {
oldSet = append(oldSet, principal.ObjectMeta.Name)
}
for _, principal := range groupPrincipals {
newSet = append(newSet, principal.ObjectMeta.Name)
}
sort.Strings(oldSet)
sort.Strings(newSet)
if len(oldSet) != len(newSet) {
return true
}
for i := range oldSet {
if oldSet[i] != newSet[i] {
return true
}
}
return false
}
var uaBackoff = wait.Backoff{
Duration: time.Millisecond * 100,
Factor: 2,
Jitter: .2,
Steps: 5,
}
func (m *Manager) NewLoginToken(userID string, userPrincipal v3.Principal, groupPrincipals []v3.Principal, providerToken string, ttl int64, description string) (v3.Token, error) {
provider := userPrincipal.Provider
if (provider == "github" || provider == "azuread") && providerToken != "" {
err := m.CreateSecret(userID, provider, providerToken)
if err != nil {
return v3.Token{}, fmt.Errorf("unable to create secret: %s", err)
}
}
err := wait.ExponentialBackoff(uaBackoff, func() (bool, error) {
err := m.UserAttributeCreateOrUpdate(userID, provider, groupPrincipals)
if err != nil {
logrus.Warnf("Problem creating or updating userAttribute for %v: %v", userID, err)
}
return err == nil, nil
})
if err != nil {
return v3.Token{}, fmt.Errorf("Unable to create userAttribute")
}
token := &v3.Token{
UserPrincipal: userPrincipal,
IsDerived: false,
TTLMillis: ttl,
UserID: userID,
AuthProvider: provider,
Description: description,
}
return m.createToken(token)
}
func (m *Manager) UpdateToken(token *v3.Token) (*v3.Token, error) {
return m.updateToken(token)
}
func (m *Manager) GetGroupsForTokenAuthProvider(token *v3.Token) []v3.Principal {
var groups []v3.Principal
attribs, err := m.userAttributeLister.Get("", token.UserID)
if err != nil && !apierrors.IsNotFound(err) {
logrus.Warnf("Problem getting userAttribute while getting groups for %v: %v", token.UserID, err)
// if err is not nil, then attribs will be. So, below code will handle it
}
hitProvider := false
if attribs != nil {
for provider, y := range attribs.GroupPrincipals {
if provider == token.AuthProvider {
hitProvider = true
for _, principal := range y.Items {
groups = append(groups, principal)
}
}
}
}
// fallback to legacy token groupPrincipals
if !hitProvider {
for _, principal := range token.GroupPrincipals {
groups = append(groups, principal)
}
}
return groups
}
func (m *Manager) IsMemberOf(token v3.Token, group v3.Principal) bool {
attribs, err := m.userAttributeLister.Get("", token.UserID)
if err != nil && !apierrors.IsNotFound(err) {
logrus.Warnf("Problem getting userAttribute while determining group membership for %v in %v (%v): %v", token.UserID,
group.Name, group.DisplayName, err)
// if err not nil, then attribs will be nil. So, below code will handle it
}
groups := map[string]bool{}
hitProviders := map[string]bool{}
if attribs != nil {
for provider, gps := range attribs.GroupPrincipals {
for _, principal := range gps.Items {
hitProviders[provider] = true
groups[principal.Name] = true
}
}
}
// fallback to legacy token groupPrincipals
if _, ok := hitProviders[token.AuthProvider]; !ok {
for _, principal := range token.GroupPrincipals {
groups[principal.Name] = true
}
}
return groups[group.Name]
}
func (m *Manager) CreateTokenAndSetCookie(userID string, userPrincipal v3.Principal, groupPrincipals []v3.Principal, providerToken string, ttl int, description string, request *types.APIContext) error {
token, err := m.NewLoginToken(userID, userPrincipal, groupPrincipals, providerToken, 0, description)
if err != nil {
logrus.Errorf("Failed creating token with error: %v", err)
return httperror.NewAPIErrorLong(500, "", fmt.Sprintf("Failed creating token with error: %v", err))
}
isSecure := false
if request.Request.URL.Scheme == "https" {
isSecure = true
}
tokenCookie := &http.Cookie{
Name: CookieName,
Value: token.ObjectMeta.Name + ":" + token.Token,
Secure: isSecure,
Path: "/",
HttpOnly: true,
}
http.SetCookie(request.Response, tokenCookie)
request.WriteResponse(http.StatusOK, nil)
return nil
}