-
Notifications
You must be signed in to change notification settings - Fork 63
/
grant_request.go
562 lines (449 loc) · 12.6 KB
/
grant_request.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
package pubnub
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"strconv"
"strings"
"time"
"github.com/pubnub/go/v7/pnerr"
)
const grantPath = "/v2/auth/grant/sub-key/%s"
var emptyGrantResponse *GrantResponse
type grantBuilder struct {
opts *grantOpts
}
func newGrantBuilder(pubnub *PubNub) *grantBuilder {
return newGrantBuilderWithContext(pubnub, pubnub.ctx)
}
func newGrantBuilderWithContext(pubnub *PubNub, context Context) *grantBuilder {
builder := grantBuilder{
opts: newGrantOpts(
pubnub,
context,
),
}
return &builder
}
func (b *grantBuilder) Read(read bool) *grantBuilder {
b.opts.Read = read
return b
}
func (b *grantBuilder) Write(write bool) *grantBuilder {
b.opts.Write = write
return b
}
func (b *grantBuilder) Manage(manage bool) *grantBuilder {
b.opts.Manage = manage
return b
}
func (b *grantBuilder) Delete(del bool) *grantBuilder {
b.opts.Delete = del
return b
}
func (b *grantBuilder) Get(get bool) *grantBuilder {
b.opts.Get = get
b.opts.isGetSet = true
return b
}
func (b *grantBuilder) Update(update bool) *grantBuilder {
b.opts.Update = update
b.opts.isUpdateSet = true
return b
}
func (b *grantBuilder) Join(join bool) *grantBuilder {
b.opts.Join = join
b.opts.isJoinSet = true
return b
}
// TTL in minutes for which granted permissions are valid.
//
// Min: 1
// Max: 525600
// Default: 1440
//
// Setting value to 0 will apply the grant indefinitely (forever grant).
func (b *grantBuilder) TTL(ttl int) *grantBuilder {
b.opts.TTL = ttl
b.opts.setTTL = true
return b
}
// AuthKeys sets the AuthKeys for the Grant request.
func (b *grantBuilder) AuthKeys(authKeys []string) *grantBuilder {
b.opts.AuthKeys = authKeys
return b
}
// Channels sets the Channels for the Grant request.
func (b *grantBuilder) Channels(channels []string) *grantBuilder {
b.opts.Channels = channels
return b
}
// ChannelGroups sets the ChannelGroups for the Grant request.
func (b *grantBuilder) ChannelGroups(groups []string) *grantBuilder {
b.opts.ChannelGroups = groups
return b
}
// ChannelGroups sets the ChannelGroups for the Grant request.
func (b *grantBuilder) UUIDs(targetUUIDs []string) *grantBuilder {
b.opts.UUIDs = targetUUIDs
return b
}
// Meta sets the Meta for the Grant request.
func (b *grantBuilder) Meta(meta map[string]interface{}) *grantBuilder {
b.opts.Meta = meta
return b
}
// QueryParam accepts a map, the keys and values of the map are passed as the query string parameters of the URL called by the API.
func (b *grantBuilder) QueryParam(queryParam map[string]string) *grantBuilder {
b.opts.QueryParam = queryParam
return b
}
// Execute runs the Grant request.
func (b *grantBuilder) Execute() (*GrantResponse, StatusResponse, error) {
rawJSON, status, err := executeRequest(b.opts)
if err != nil {
return emptyGrantResponse, status, err
}
return newGrantResponse(rawJSON, status)
}
func newGrantOpts(pubnub *PubNub, ctx Context) *grantOpts {
return &grantOpts{
endpointOpts: endpointOpts{
pubnub: pubnub,
ctx: ctx,
},
}
}
type grantOpts struct {
endpointOpts
AuthKeys []string
Channels []string
ChannelGroups []string
UUIDs []string
QueryParam map[string]string
Meta map[string]interface{}
// Stringified permissions
// Setting 'true' or 'false' will apply permissions to level
Read bool
Write bool
Manage bool
Delete bool
Get bool
Update bool
Join bool
// Max: 525600
// Min: 1
// Default: 1440
// Setting 0 will apply the grant indefinitely
TTL int
// nil hacks
setTTL bool
isGetSet bool
isUpdateSet bool
isJoinSet bool
}
func (o *grantOpts) validate() error {
if o.config().PublishKey == "" {
return newValidationError(o, StrMissingPubKey)
}
if o.config().SubscribeKey == "" {
return newValidationError(o, StrMissingSubKey)
}
if o.config().SecretKey == "" {
return newValidationError(o, StrMissingSecretKey)
}
return nil
}
func (o *grantOpts) buildPath() (string, error) {
return fmt.Sprintf(grantPath, o.pubnub.Config.SubscribeKey), nil
}
func (o *grantOpts) buildQuery() (*url.Values, error) {
q := defaultQuery(o.pubnub.Config.UUID, o.pubnub.telemetryManager)
if o.Read {
q.Set("r", "1")
} else {
q.Set("r", "0")
}
if o.Write {
q.Set("w", "1")
} else {
q.Set("w", "0")
}
if o.Manage {
q.Set("m", "1")
} else {
q.Set("m", "0")
}
if o.Delete {
q.Set("d", "1")
} else {
q.Set("d", "0")
}
if o.isGetSet {
if o.Get {
q.Set("g", "1")
} else {
q.Set("g", "0")
}
}
if o.isUpdateSet {
if o.Update {
q.Set("u", "1")
} else {
q.Set("u", "0")
}
}
if o.isJoinSet {
if o.Join {
q.Set("j", "1")
} else {
q.Set("j", "0")
}
}
if len(o.AuthKeys) > 0 {
q.Set("auth", strings.Join(o.AuthKeys, ","))
}
if len(o.Channels) > 0 {
q.Set("channel", strings.Join(o.Channels, ","))
}
if len(o.ChannelGroups) > 0 {
q.Set("channel-group", strings.Join(o.ChannelGroups, ","))
}
if len(o.UUIDs) > 0 {
q.Set("target-uuid", strings.Join(o.UUIDs, ","))
}
if o.setTTL {
if o.TTL >= -1 {
q.Set("ttl", fmt.Sprintf("%d", o.TTL))
}
}
timestamp := time.Now().Unix()
q.Set("timestamp", strconv.Itoa(int(timestamp)))
SetQueryParam(q, o.QueryParam)
return q, nil
}
func (o *grantOpts) operationType() OperationType {
return PNAccessManagerGrant
}
// GrantResponse is the struct returned when the Execute function of Grant is called.
type GrantResponse struct {
Level string
SubscribeKey string
TTL int
Channels map[string]*PNPAMEntityData
ChannelGroups map[string]*PNPAMEntityData
UUIDs map[string]*PNPAMEntityData
ReadEnabled bool
WriteEnabled bool
ManageEnabled bool
DeleteEnabled bool
GetEnabled bool
UpdateEnabled bool
JoinEnabled bool
}
func newGrantResponse(jsonBytes []byte, status StatusResponse) (
*GrantResponse, StatusResponse, error) {
resp := &GrantResponse{}
var value interface{}
err := json.Unmarshal(jsonBytes, &value)
if err != nil {
e := pnerr.NewResponseParsingError("Error unmarshalling response",
ioutil.NopCloser(bytes.NewBufferString(string(jsonBytes))), err)
return emptyGrantResponse, status, e
}
constructedChannels := make(map[string]*PNPAMEntityData)
constructedGroups := make(map[string]*PNPAMEntityData)
constructedUUIDs := make(map[string]*PNPAMEntityData)
grantData, _ := value.(map[string]interface{})
payload := grantData["payload"]
parsedPayload := payload.(map[string]interface{})
auths, _ := parsedPayload["auths"].(map[string]interface{})
ttl, _ := parsedPayload["ttl"].(float64)
if val, ok := parsedPayload["channel"]; ok {
channelName := val.(string)
auths := make(map[string]*PNAccessManagerKeyData)
channelMap, _ := parsedPayload["auths"].(map[string]interface{})
entityData := &PNPAMEntityData{
Name: channelName,
}
for key, value := range channelMap {
auths[key] = createPNAccessManagerKeyData(value, entityData, false)
}
entityData.AuthKeys = auths
entityData.TTL = int(ttl)
constructedChannels[channelName] = entityData
}
if val, ok := parsedPayload["channel-groups"]; ok {
groupName, _ := val.(string)
constructedAuthKey := make(map[string]*PNAccessManagerKeyData)
entityData := &PNPAMEntityData{
Name: groupName,
}
if _, ok := val.(string); ok {
for authKeyName, value := range auths {
constructedAuthKey[authKeyName] = createPNAccessManagerKeyData(value, entityData, false)
}
entityData.AuthKeys = constructedAuthKey
constructedGroups[groupName] = entityData
}
if groupMap, ok := val.(map[string]interface{}); ok {
groupName, _ := val.(string)
constructedAuthKey := make(map[string]*PNAccessManagerKeyData)
entityData := &PNPAMEntityData{
Name: groupName,
}
for groupName, value := range groupMap {
valueMap := value.(map[string]interface{})
if keys, ok := valueMap["auths"]; ok {
parsedKeys, _ := keys.(map[string]interface{})
for keyName, value := range parsedKeys {
constructedAuthKey[keyName] = createPNAccessManagerKeyData(value, entityData, false)
}
}
createPNAccessManagerKeyData(valueMap, entityData, true)
if val, ok := parsedPayload["ttl"]; ok {
parsedVal, _ := val.(float64)
entityData.TTL = int(parsedVal)
}
entityData.AuthKeys = constructedAuthKey
constructedGroups[groupName] = entityData
}
}
}
if val, ok := parsedPayload["channels"]; ok {
channelMap, _ := val.(map[string]interface{})
for channelName, value := range channelMap {
constructedChannels[channelName] = fetchChannel(channelName, value, parsedPayload)
}
}
if val, ok := parsedPayload["uuids"]; ok {
uuids, _ := val.(map[string]interface{})
for uuid, value := range uuids {
constructedUUIDs[uuid] = fetchChannel(uuid, value, parsedPayload)
}
}
level, _ := parsedPayload["level"].(string)
subKey, _ := parsedPayload["subscribe_key"].(string)
resp.Level = level
resp.SubscribeKey = subKey
resp.Channels = constructedChannels
resp.ChannelGroups = constructedGroups
resp.UUIDs = constructedUUIDs
resp.ReadEnabled = parsePerms(parsedPayload, "r")
resp.WriteEnabled = parsePerms(parsedPayload, "w")
resp.ManageEnabled = parsePerms(parsedPayload, "m")
resp.DeleteEnabled = parsePerms(parsedPayload, "d")
resp.GetEnabled = parsePerms(parsedPayload, "g")
resp.UpdateEnabled = parsePerms(parsedPayload, "u")
resp.JoinEnabled = parsePerms(parsedPayload, "j")
if r, ok := parsedPayload["ttl"]; ok {
parsedValue, _ := r.(float64)
resp.TTL = int(parsedValue)
}
return resp, status, nil
}
func parsePerms(parsedPayload map[string]interface{}, name string) bool {
if r, ok := parsedPayload[name]; ok {
parsedValue, _ := r.(float64)
if parsedValue == float64(1) {
return true
} else {
return false
}
}
return false
}
func fetchChannel(channelName string, value interface{}, parsedPayload map[string]interface{}) *PNPAMEntityData {
auths := make(map[string]*PNAccessManagerKeyData)
entityData := &PNPAMEntityData{
Name: channelName,
}
valueMap, _ := value.(map[string]interface{})
if val, ok := valueMap["auths"]; ok {
parsedValue := val.(map[string]interface{})
for key, value := range parsedValue {
auths[key] = createPNAccessManagerKeyData(value, entityData, false)
}
}
createPNAccessManagerKeyData(value, entityData, true)
if val, ok := parsedPayload["ttl"]; ok {
parsedVal, _ := val.(float64)
entityData.TTL = int(parsedVal)
}
entityData.AuthKeys = auths
return entityData
}
func readKeyData(val interface{}, keyData *PNAccessManagerKeyData, entityData *PNPAMEntityData, writeToEntityData bool, grantType PNGrantType) {
parsedValue, _ := val.(float64)
readValue := false
if parsedValue == float64(1) {
readValue = true
}
if writeToEntityData {
switch grantType {
case PNReadEnabled:
entityData.ReadEnabled = readValue
case PNWriteEnabled:
entityData.WriteEnabled = readValue
case PNManageEnabled:
entityData.ManageEnabled = readValue
case PNDeleteEnabled:
entityData.DeleteEnabled = readValue
case PNGetEnabled:
entityData.GetEnabled = readValue
case PNUpdateEnabled:
entityData.UpdateEnabled = readValue
case PNJoinEnabled:
entityData.JoinEnabled = readValue
}
} else {
switch grantType {
case PNReadEnabled:
keyData.ReadEnabled = readValue
case PNWriteEnabled:
keyData.WriteEnabled = readValue
case PNManageEnabled:
keyData.ManageEnabled = readValue
case PNDeleteEnabled:
keyData.DeleteEnabled = readValue
case PNGetEnabled:
keyData.GetEnabled = readValue
case PNUpdateEnabled:
keyData.UpdateEnabled = readValue
case PNJoinEnabled:
keyData.JoinEnabled = readValue
}
}
}
func createPNAccessManagerKeyData(value interface{}, entityData *PNPAMEntityData, writeToEntityData bool) *PNAccessManagerKeyData {
valueMap := value.(map[string]interface{})
keyData := &PNAccessManagerKeyData{}
if val, ok := valueMap["r"]; ok {
readKeyData(val, keyData, entityData, writeToEntityData, PNReadEnabled)
}
if val, ok := valueMap["w"]; ok {
readKeyData(val, keyData, entityData, writeToEntityData, PNWriteEnabled)
}
if val, ok := valueMap["m"]; ok {
readKeyData(val, keyData, entityData, writeToEntityData, PNManageEnabled)
}
if val, ok := valueMap["d"]; ok {
readKeyData(val, keyData, entityData, writeToEntityData, PNDeleteEnabled)
}
if val, ok := valueMap["g"]; ok {
readKeyData(val, keyData, entityData, writeToEntityData, PNGetEnabled)
}
if val, ok := valueMap["u"]; ok {
readKeyData(val, keyData, entityData, writeToEntityData, PNUpdateEnabled)
}
if val, ok := valueMap["j"]; ok {
readKeyData(val, keyData, entityData, writeToEntityData, PNJoinEnabled)
}
if val, ok := valueMap["ttl"]; ok {
parsedVal, _ := val.(int)
entityData.TTL = parsedVal
}
return keyData
}