-
Notifications
You must be signed in to change notification settings - Fork 14
/
domain.go
435 lines (326 loc) · 13.2 KB
/
domain.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
package service
import (
"context"
"html/template"
"github.com/EmissarySocial/emissary/config"
"github.com/EmissarySocial/emissary/model"
"github.com/EmissarySocial/emissary/service/providers"
"github.com/EmissarySocial/emissary/tools/domain"
"github.com/EmissarySocial/emissary/tools/random"
"github.com/benpate/data"
"github.com/benpate/data/option"
"github.com/benpate/derp"
"github.com/benpate/exp"
"github.com/benpate/rosetta/mapof"
"github.com/benpate/rosetta/schema"
"go.mongodb.org/mongo-driver/bson/primitive"
"golang.org/x/oauth2"
)
// Domain service manages all access to the singleton model.Domain in the database
type Domain struct {
collection data.Collection
configuration config.Domain
themeService *Theme
userService *User
providerService *Provider
funcMap template.FuncMap
domain model.Domain
ready bool
}
// NewDomain returns a fully initialized Domain service
func NewDomain(collection data.Collection, configuration config.Domain, themeService *Theme, userService *User, providerService *Provider, funcMap template.FuncMap) Domain {
service := Domain{
themeService: themeService,
providerService: providerService,
userService: userService,
funcMap: funcMap,
domain: model.NewDomain(),
ready: false,
}
service.Refresh(collection, configuration)
return service
}
/******************************************
* Lifecycle Methods
******************************************/
// Refresh updates any stateful data that is cached inside this service.
func (service *Domain) Refresh(collection data.Collection, configuration config.Domain) {
if collection == nil {
return
}
service.collection = collection
service.configuration = configuration
service.domain = model.NewDomain()
if err := service.LoadOrCreateDomain(); err != nil {
derp.Report(derp.Wrap(err, "service.Domain.Refresh", "Domain Not Ready: Error loading domain record"))
return
}
service.ready = true
}
// Close stops the following service watcher
func (service *Domain) Close() {
}
// Ready returns TRUE if the service is ready to use
func (service *Domain) Ready() bool {
return service.ready
}
func (service *Domain) LoadOrCreateDomain() error {
err := service.collection.Load(exp.All(), &service.domain)
// Loaded the domain successfully
if err == nil {
return nil
}
// No record present. Create a new one.
if derp.NotFound(err) {
if err := service.collection.Save(&service.domain, "Created Domain Record"); err != nil {
return derp.Wrap(err, "service.Domain.Refresh", "Error creating new domain record")
}
return nil
}
return derp.Wrap(err, "service.Domain.Refresh", "Domain Not Ready: Error loading domain record")
}
/******************************************
* Common Data Methods
******************************************/
// Load retrieves an Domain from the database (or in-memory cache)
func (service *Domain) Get() model.Domain {
return service.domain
}
// Save updates the value of this domain in the database (and in-memory cache)
func (service *Domain) Save(domain *model.Domain, note string) error {
// Clean the value before saving
if err := service.Schema().Clean(domain); err != nil {
return derp.Wrap(err, "service.Domain.Save", "Error cleaning Domain", domain)
}
// Try to save the value to the database
if err := service.collection.Save(domain, note); err != nil {
return derp.Wrap(err, "service.Domain.Save", "Error saving Domain")
}
// Update the in-memory cache
service.domain = *domain
return nil
}
/******************************************
* Generic Data Methods
******************************************/
// ObjectType returns the type of object that this service manages
func (service *Domain) ObjectType() string {
return "Domain"
}
// New returns a fully initialized model.Stream as a data.Object.
func (service *Domain) ObjectNew() data.Object {
result := model.NewDomain()
return &result
}
func (service *Domain) ObjectID(object data.Object) primitive.ObjectID {
if domain, ok := object.(*model.Domain); ok {
return domain.DomainID
}
return primitive.NilObjectID
}
func (service *Domain) ObjectQuery(result any, criteria exp.Expression, options ...option.Option) error {
return service.collection.Query(result, notDeleted(criteria), options...)
}
func (service *Domain) ObjectList(criteria exp.Expression, options ...option.Option) (data.Iterator, error) {
return nil, derp.NewBadRequestError("service.Domain.ObjectDelete", "Unsupported")
}
func (service *Domain) ObjectLoad(_ exp.Expression) (data.Object, error) {
return &service.domain, nil
}
func (service *Domain) ObjectSave(object data.Object, note string) error {
if domain, ok := object.(*model.Domain); ok {
return service.Save(domain, note)
}
return derp.NewInternalError("service.Domain.ObjectSave", "Invalid Object Type", object)
}
func (service *Domain) ObjectDelete(object data.Object, note string) error {
return derp.NewBadRequestError("service.Domain.ObjectDelete", "Unsupported")
}
func (service *Domain) ObjectUserCan(object data.Object, authorization model.Authorization, action string) error {
return derp.NewUnauthorizedError("service.Domain", "Not Authorized")
}
func (service *Domain) Schema() schema.Schema {
return schema.New(model.DomainSchema())
}
/******************************************
* Provider Methods
******************************************/
func (service *Domain) Theme() model.Theme {
return service.themeService.GetTheme(service.domain.ThemeID)
}
/******************************************
* Provider Methods
******************************************/
// ActiveClients returns all active Clients for this domain
func (service *Domain) ActiveClients() []model.Client {
// List all clients, filtering by "active" ones.
result := make([]model.Client, 0, len(service.domain.Clients))
for _, client := range service.domain.Clients {
if client.Active {
result = append(result, client)
}
}
// Success
return result
}
func (service *Domain) Client(providerID string) model.Client {
if client, ok := service.domain.Clients[providerID]; ok {
return client
}
return model.NewClient(providerID)
}
// Provider returns the external Provider that matches the given providerID
func (service *Domain) Provider(providerID string) (providers.Provider, bool) {
return service.providerService.GetProvider(providerID)
}
// ManualProvider returns the external.ManualProvider that matches the given providerID
func (service *Domain) ManualProvider(providerID string) (providers.ManualProvider, bool) {
if provider, ok := service.Provider(providerID); ok {
if manualProvider, ok := provider.(providers.ManualProvider); ok {
return manualProvider, true
}
}
return nil, false
}
// OAuthProvider returns the external.OAuthProvider that matches the given providerID
func (service *Domain) OAuthProvider(providerID string) (providers.OAuthProvider, bool) {
if provider, ok := service.Provider(providerID); ok {
if oAuthProvider, ok := provider.(providers.OAuthProvider); ok {
return oAuthProvider, true
}
}
return nil, false
}
/******************************************
* OAuth Handshake Methods
******************************************/
// OAuthCodeURL generates a new (unique) OAuth state and AuthCodeURL for the specified provider
func (service *Domain) OAuthCodeURL(providerID string) (string, error) {
// Get the provider for this provider
provider, ok := service.OAuthProvider(providerID)
if !ok {
return "", derp.NewBadRequestError("service.Domain.OAuthCodeURL", "Unknown OAuth Provider", providerID)
}
// Set a new "state" for this provider
client, err := service.NewOAuthClient(providerID)
if err != nil {
return "", derp.Wrap(err, "service.Domain.OAuthCodeURL", "Error generating new OAuth client")
}
// Generate and return the AuthCodeURL
config := provider.OAuthConfig()
config.RedirectURL = service.OAuthCallbackURL(providerID)
/* TODO: MEDIUM: add hash value for challenge_method...
codeChallengeBytes := sha256.Sum256([]byte(client.GetStringOK("code_challenge")))
codeChallenge := oauth2.SetAuthURLParam("code_challenge", random.Base64URLEncode(codeChallengeBytes[:]))
codeChallengeMethod := oauth2.SetAuthURLParam("code_challenge_method", "S256")
*/
codeChallenge := oauth2.SetAuthURLParam("code_challenge", value(client.GetStringOK("code_challenge")))
codeChallengeMethod := oauth2.SetAuthURLParam("code_challenge_method", "plain")
authCodeURL := config.AuthCodeURL(value(client.GetStringOK("state")), codeChallenge, codeChallengeMethod)
return authCodeURL, nil
}
// OAuthExchange trades a temporary OAuth code for a valid OAuth token
func (service *Domain) OAuthExchange(providerID string, state string, code string) error {
const location = "service.Domain.OAuthExchange"
// Get the provider for this provider
provider, ok := service.OAuthProvider(providerID)
if !ok {
return derp.NewBadRequestError(location, "Unknown OAuth Provider", providerID)
}
// The client must already be set up for this exchange to work.
client, ok := service.domain.Clients.Get(providerID)
if !ok {
return derp.NewBadRequestError(location, "Unknown OAuth Provider", providerID)
}
// Validate the state across requests
if newState, _ := client.Data.GetStringOK("state"); newState != state {
return derp.NewBadRequestError(location, "Invalid OAuth State", state)
}
// Try to generate the OAuth token
config := provider.OAuthConfig()
token, err := config.Exchange(context.Background(), code,
oauth2.SetAuthURLParam("code_verifier", value(client.GetStringOK("code_challenge"))),
oauth2.SetAuthURLParam("redirect_uri", service.OAuthCallbackURL(providerID)))
if err != nil {
return derp.NewInternalError(location, "Error exchanging OAuth code for token", err.Error())
}
// Try to update the client with the new token
client.Token = token
client.Data = mapof.NewAny()
client.Active = true
service.domain.SetClient(client)
if service.Save(&service.domain, "OAuth Exchange") != nil {
return derp.NewInternalError(location, "Error saving domain")
}
// Success!
return nil
}
// OAuthCallbackURL returns the specific callback URL to use for this host and provider.
func (service *Domain) OAuthCallbackURL(providerID string) string {
return domain.Protocol(service.configuration.Hostname) + service.configuration.Hostname + "/oauth/" + providerID + "/callback"
}
// NewOAuthState generates and returns a new OAuth state for the specified provider
func (service *Domain) NewOAuthClient(providerID string) (model.Client, error) {
const location = "service.Domain.NewOAuthState"
// Find or Create a client for this provider
client, _ := service.domain.GetClient(providerID)
// Try to generate a new state
newState, err := random.GenerateString(32)
if err != nil {
return model.Client{}, derp.Wrap(err, location, "Error generating random string")
}
codeChallenge, err := random.GenerateString(64)
if err != nil {
return model.Client{}, derp.Wrap(err, location, "Error generating random string")
}
// Assign the state to the client and put into the domain
client.Data["state"] = newState
client.Data["code_challenge"] = codeChallenge
service.domain.SetClient(client)
// Save the domain
if err := service.Save(&service.domain, "New OAuth State"); err != nil {
return model.Client{}, derp.Wrap(err, location, "Error saving domain")
}
return client, nil
}
// ReadOAuthState returns the OAuth state for the specified provider WITHOUT changing the current value.
// THIS SHOULD NOT BE USED TO ACCESS OAUTH TOKENS because they may be expired. Use GetOAuthToken for that.
func (service *Domain) ReadOAuthClient(providerID string) (model.Client, bool) {
return service.domain.GetClient(providerID)
}
// GetAuthToken retrieves the OAuth token for the specified provider. If the token has expired
// then it is refreshed (and saved) automatically before returning.
func (service *Domain) GetOAuthToken(providerID string) (model.Client, *oauth2.Token, error) {
// Get the provider for this OAuth provider
provider, ok := service.OAuthProvider(providerID)
if !ok {
return model.Client{}, nil, derp.NewBadRequestError("service.Domain.GetOAuthToken", "Unknown OAuth Provider", providerID)
}
// Try to load the Domain and Client data
client, ok := service.ReadOAuthClient(providerID)
if !ok {
return model.Client{}, nil, derp.NewBadRequestError("service.Domain.GetOAuthToken", "Error reading OAuth client")
}
// Retrieve the Token from the client
token := client.Token
if token == nil {
return model.Client{}, token, derp.NewBadRequestError("service.Domain.GetOAuthToken", "No OAuth token found for provider", providerID)
}
// Use TokenSource to update tokens when they expire.
config := provider.OAuthConfig()
source := config.TokenSource(context.Background(), token)
newToken, err := source.Token()
if err != nil {
return model.Client{}, token, derp.Wrap(err, "service.Domain.GetOAuthToken", "Error refreshing OAuth token")
}
// If the token has changed, save it
if token.AccessToken != newToken.AccessToken {
client.Token = newToken
service.domain.SetClient(client)
if err := service.Save(&service.domain, "Refresh OAuth Token"); err != nil {
return model.Client{}, token, derp.Wrap(err, "service.Domain.GetOAuthToken", "Error saving refreshed Token")
}
}
// Success!
return client, newToken, nil
}