-
Notifications
You must be signed in to change notification settings - Fork 10
/
permission.go
71 lines (63 loc) · 1.49 KB
/
permission.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
package rbac
import (
"encoding/json"
"fmt"
"sort"
"sync"
)
// Permission defines rbac permission
type Permission struct {
ID string
Description string
sync.Map // key action, val nil
}
type jsPermission struct {
ID string `json:"id"`
Description string `json:"description"`
Actions []Action `json:"actions"`
}
func newPermission(ID, description string, actions ...Action) *Permission {
perm := &Permission{ID: ID, Description: description}
for _, a := range actions {
if a == CRUD {
perm.Store(Create, nil)
perm.Store(Read, nil)
perm.Store(Update, nil)
perm.Store(Delete, nil)
} else {
perm.Store(a, nil)
}
}
return perm
}
// String returns as string
func (p *Permission) String() string {
return fmt.Sprintf("Permission{ID: %s, Description: %s}", p.ID, p.Description)
}
// Actions returns list of Actions
func (p *Permission) Actions() []Action {
res := []Action{}
p.Range(func(k, v interface{}) bool {
res = append(res, k.(Action))
return true
})
return res
}
// ActionsStrSlice returns list of Actions as sorted string slice
func (p *Permission) ActionsStrSlice() []string {
res := []string{}
p.Range(func(k, v interface{}) bool {
res = append(res, string(k.(Action)))
return true
})
sort.Strings(res)
return res
}
// MarshalJSON serializes a Permission to JSON
func (p *Permission) MarshalJSON() ([]byte, error) {
return json.Marshal(jsPermission{
ID: p.ID,
Description: p.Description,
Actions: p.Actions(),
})
}