-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaccess.go
88 lines (75 loc) · 1.56 KB
/
access.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
package buzza
type Access byte
const (
AccessUndefined Access = 0
AccessForbidden Access = 1
AccessAllowed Access = 2
)
func (a Access) merge(b Access) Access {
switch {
case a == AccessUndefined:
return b
case b == AccessUndefined:
return a
default:
return b
}
}
type PermissionName string
const (
PermissionDownloadPro PermissionName = "download.pro"
PermissionAdminDashboard PermissionName = "admin.dashboard"
)
type RoleId string
type Role struct {
Id RoleId
Permissions map[PermissionName]bool
}
var (
RoleIdPro RoleId = "pro"
RoleIdAdmin RoleId = "admin"
)
var AllRoles map[RoleId]Role = mapRolesById(
Role{
Id: RoleIdAdmin,
Permissions: map[PermissionName]bool{
PermissionDownloadPro: true,
PermissionAdminDashboard: true,
},
},
Role{
Id: RoleIdPro,
Permissions: map[PermissionName]bool{
PermissionDownloadPro: true,
},
},
)
func mapRolesById(roles ...Role) map[RoleId]Role {
rolesMap := make(map[RoleId]Role)
for _, role := range roles {
if _, ok := rolesMap[role.Id]; ok {
panic("Duplicated role id: `" + role.Id + "`!")
}
rolesMap[role.Id] = role
}
return rolesMap
}
func (role Role) Access(name PermissionName) Access {
hasPermission, ok := role.Permissions[name]
switch {
case !ok:
return AccessUndefined
case hasPermission:
return AccessAllowed
default:
return AccessForbidden
}
}
type Roles []Role
func (roles Roles) Access(permission PermissionName) Access {
access := AccessUndefined
for _, role := range roles {
access = access.merge(role.Access(permission))
}
return access
}