-
Notifications
You must be signed in to change notification settings - Fork 4
/
principal.go
105 lines (80 loc) · 2.03 KB
/
principal.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
// Copyright 2024 Canonical Ltd.
// SPDX-License-Identifier: AGPL-3.0
package authentication
import "context"
type principalContextKey int
var PrincipalContextKey principalContextKey
type UserPrincipal struct {
Subject string `json:"sub"`
Name string `json:"name"`
Email string `json:"email"`
SessionID string `json:"sid"`
Nonce string `json:"nonce"`
RawAccessToken string `json:"-"`
RawIdToken string `json:"-"`
RawRefreshToken string `json:"-"`
}
func (u *UserPrincipal) Session() string {
return u.SessionID
}
func (u *UserPrincipal) AccessToken() string {
return u.RawAccessToken
}
func (u *UserPrincipal) RefreshToken() string {
return u.RawRefreshToken
}
func (u *UserPrincipal) IDToken() string {
return u.RawIdToken
}
func (u *UserPrincipal) Identifier() string {
return u.Email
}
type ServicePrincipal struct {
Subject string `json:"sub"`
RawAccessToken string `json:"-"`
}
func (s *ServicePrincipal) Session() string {
return ""
}
func (s *ServicePrincipal) AccessToken() string {
return s.RawAccessToken
}
func (s *ServicePrincipal) RefreshToken() string {
return ""
}
func (s *ServicePrincipal) IDToken() string {
return ""
}
func (s *ServicePrincipal) Identifier() string {
return s.Subject
}
func NewUserPrincipalFromClaims(c ReadableClaims) (*UserPrincipal, error) {
a := new(UserPrincipal)
if err := c.Claims(a); err != nil {
return nil, err
}
return a, nil
}
func NewServicePrincipalFromClaims(c ReadableClaims) (*ServicePrincipal, error) {
a := new(ServicePrincipal)
if err := c.Claims(a); err != nil {
return nil, err
}
return a, nil
}
func PrincipalContext(ctx context.Context, principal PrincipalInterface) context.Context {
parent := ctx
if ctx == nil {
parent = context.Background()
}
return context.WithValue(parent, PrincipalContextKey, principal)
}
func PrincipalFromContext(ctx context.Context) PrincipalInterface {
if ctx == nil {
return nil
}
if value, ok := ctx.Value(PrincipalContextKey).(PrincipalInterface); ok {
return value
}
return nil
}