This repository has been archived by the owner on Feb 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
identity_provider.go
321 lines (253 loc) · 6.61 KB
/
identity_provider.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
package providers
import (
"context"
"fmt"
"time"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/maxence-charriere/go-app/v8/pkg/app"
"golang.org/x/oauth2"
)
const (
oauth2TokenKey = "oauth2Token"
idTokenKey = "idToken"
userInfoKey = "userInfo"
StateQueryParameter = "state"
CodeQueryParameter = "code"
idTokenExtraKey = "id_token"
)
type IdentityProviderChildrenProps struct {
IDToken string
UserInfo oidc.UserInfo
Logout func()
Error error
Recover func()
}
type IdentityProvider struct {
app.Compo
Issuer string
ClientID string
RedirectURL string
HomeURL string
Scopes []string
StoragePrefix string
Children func(IdentityProviderChildrenProps) app.UI
oauth2Token oauth2.Token
idToken string
userInfo oidc.UserInfo
err error
}
func (c *IdentityProvider) Render() app.UI {
return c.Children(
IdentityProviderChildrenProps{
IDToken: c.idToken,
UserInfo: c.userInfo,
Logout: func() {
c.Defer(func(ctx app.Context) {
c.logout(true, ctx)
})
},
Error: c.err,
Recover: c.recover,
},
)
}
func (c *IdentityProvider) OnMount(ctx app.Context) {
// Only continue if there is no error state; this prevents endless loops
if c.err == nil {
c.dispatch(func(ctx app.Context) {
c.authorize(ctx)
})
}
}
func (c *IdentityProvider) OnNav(ctx app.Context) {
// Only continue if there is no error state; this prevents endless loops
if c.err == nil {
c.dispatch(func(ctx app.Context) {
c.authorize(ctx)
})
}
}
func (c *IdentityProvider) panic(err error) {
go func() {
c.dispatch(func(ctx app.Context) {
// Set the error
c.err = err
})
// Prevent infinite retries
time.Sleep(time.Second)
// Unset the error & enable re-trying
c.err = err
}()
}
func (c *IdentityProvider) recover() {
c.dispatch(func(ctx app.Context) {
// Clear the error
c.err = nil
// Logout
c.logout(false, ctx)
})
}
func (c *IdentityProvider) dispatch(action func(ctx app.Context)) {
c.Defer(func(ctx app.Context) {
action(ctx)
})
c.Update()
}
func (c *IdentityProvider) watch() {
for {
// Wait till token expires
if c.oauth2Token.Expiry.After(time.Now()) {
time.Sleep(c.oauth2Token.Expiry.Sub(time.Now()))
}
// Fetch new OAuth2 token
oauth2Token, err := oauth2.StaticTokenSource(&c.oauth2Token).Token()
if err != nil {
c.panic(err)
return
}
// Parse ID token
idToken, ok := oauth2Token.Extra("id_token").(string)
if !ok {
c.panic(err)
return
}
// Set the login state
c.dispatch(func(ctx app.Context) {
// Persist state in storage
if err := c.persist(*oauth2Token, idToken, c.userInfo, ctx); err != nil {
c.panic(err)
return
}
c.oauth2Token = *oauth2Token
c.idToken = idToken
})
}
}
func (c *IdentityProvider) logout(withRedirect bool, ctx app.Context) {
// Remove from storage
c.clear(ctx)
// Reload the app
if withRedirect {
ctx.Reload()
}
}
func (c *IdentityProvider) rehydrate(ctx app.Context) (oauth2.Token, string, oidc.UserInfo, error) {
// Read state from storage
oauth2Token := oauth2.Token{}
idToken := ""
userInfo := oidc.UserInfo{}
if err := ctx.LocalStorage().Get(c.getKey(oauth2TokenKey), &oauth2Token); err != nil {
return oauth2.Token{}, "", oidc.UserInfo{}, err
}
if err := ctx.LocalStorage().Get(c.getKey(idTokenKey), &idToken); err != nil {
return oauth2.Token{}, "", oidc.UserInfo{}, err
}
if err := ctx.LocalStorage().Get(c.getKey(userInfoKey), &userInfo); err != nil {
return oauth2.Token{}, "", oidc.UserInfo{}, err
}
return oauth2Token, idToken, userInfo, nil
}
func (c *IdentityProvider) persist(oauth2Token oauth2.Token, idToken string, userInfo oidc.UserInfo, ctx app.Context) error {
// Write state to storage
if err := ctx.LocalStorage().Set(c.getKey(oauth2TokenKey), oauth2Token); err != nil {
return err
}
if err := ctx.LocalStorage().Set(c.getKey(idTokenKey), idToken); err != nil {
return err
}
return ctx.LocalStorage().Set(c.getKey(userInfoKey), userInfo)
}
func (c *IdentityProvider) clear(ctx app.Context) {
// Remove from storage
ctx.LocalStorage().Del(c.getKey(oauth2TokenKey))
ctx.LocalStorage().Del(c.getKey(idTokenKey))
ctx.LocalStorage().Del(c.getKey(userInfoKey))
// Remove cookies
app.Window().Get("document").Set("cookie", "")
}
func (c *IdentityProvider) getKey(key string) string {
// Get a prefixed key
return fmt.Sprintf("%v.%v", c.StoragePrefix, key)
}
func (c *IdentityProvider) authorize(ctx app.Context) {
// Read state from storage
oauth2Token, idToken, userInfo, err := c.rehydrate(ctx)
if err != nil {
c.panic(err)
return
}
// Create the OIDC provider
provider, err := oidc.NewProvider(context.Background(), c.Issuer)
if err != nil {
c.panic(err)
return
}
// Create the OAuth2 config
config := &oauth2.Config{
ClientID: c.ClientID,
RedirectURL: c.RedirectURL,
Endpoint: provider.Endpoint(),
Scopes: append([]string{oidc.ScopeOpenID}, c.Scopes...),
}
// Log in
if oauth2Token.AccessToken == "" || userInfo.Email == "" {
// Logged out state, info neither in storage nor in URL: Redirect to login
if app.Window().URL().Query().Get(StateQueryParameter) == "" {
ctx.Navigate(config.AuthCodeURL(c.RedirectURL, oauth2.AccessTypeOffline))
return
}
// Intermediate state, info is in URL: Parse OAuth2 token
oauth2Token, err := config.Exchange(context.Background(), app.Window().URL().Query().Get(CodeQueryParameter))
if err != nil {
c.panic(err)
return
}
// Parse ID token
idToken, ok := oauth2Token.Extra(idTokenExtraKey).(string)
if !ok {
c.panic(err)
return
}
// Parse user info
userInfo, err := provider.UserInfo(context.Background(), oauth2.StaticTokenSource(oauth2Token))
if err != nil {
c.panic(err)
return
}
// Persist state in storage
if err := c.persist(*oauth2Token, idToken, *userInfo, ctx); err != nil {
c.panic(err)
return
}
// Test validity of storage
if _, _, _, err = c.rehydrate(ctx); err != nil {
c.panic(err)
return
}
// Update and navigate to home URL
c.Update()
ctx.Navigate(c.HomeURL)
return
}
// Validation state
// Create the OIDC config
oidcConfig := &oidc.Config{
ClientID: c.ClientID,
}
// Create the OIDC verifier and validate the token (i.e. check for it's expiry date)
verifier := provider.Verifier(oidcConfig)
if _, err := verifier.Verify(context.Background(), idToken); err != nil {
// Invalid token; clear and re-authorize
c.clear(ctx)
c.authorize(ctx)
return
}
// Logged in state
// Set the login state
c.oauth2Token = oauth2Token
c.idToken = idToken
c.userInfo = userInfo
// Watch and renew token once expired
go c.watch()
return
}