-
Notifications
You must be signed in to change notification settings - Fork 48
/
roleService.go
83 lines (67 loc) · 1.77 KB
/
roleService.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
package role
import (
"context"
"flamingo.me/flamingo/v3/core/security/application/role/provider"
"flamingo.me/flamingo/v3/core/security/domain"
"flamingo.me/flamingo/v3/framework/config"
"flamingo.me/flamingo/v3/framework/web"
)
type (
Service interface {
All(context.Context, *web.Session) []domain.Role
}
ServiceImpl struct {
providers []provider.RoleProvider
rolesHierarchy config.Map
}
)
func (s *ServiceImpl) Inject(p []provider.RoleProvider, cfg *struct {
RolesHierarchy config.Map `inject:"config:security.roles.hierarchy"`
}) {
s.providers = p
s.rolesHierarchy = cfg.RolesHierarchy
}
func (s *ServiceImpl) All(ctx context.Context, session *web.Session) []domain.Role {
rolesChan := make(chan []domain.Role)
for index := range s.providers {
go func(p provider.RoleProvider) {
rolesChan <- p.All(ctx, session)
}(s.providers[index])
}
var roles []domain.Role
for range s.providers {
fromChan := <-rolesChan
var extracted []domain.Role
for _, role := range fromChan {
extracted = append(extracted, s.extractRoles(role)...)
}
roles = append(roles, extracted...)
}
return s.removeDuplicates(roles)
}
func (s *ServiceImpl) extractRoles(role domain.Role) []domain.Role {
roles := []domain.Role{
role,
}
var roleMap map[string][]string
s.rolesHierarchy.MapInto(&roleMap)
hierarchy, ok := roleMap[role.Permission()]
if !ok {
return roles
}
for index := range hierarchy {
roles = append(roles, domain.Role(hierarchy[index]))
}
return roles
}
func (s *ServiceImpl) removeDuplicates(roles []domain.Role) []domain.Role {
roleMap := map[string]bool{}
var clean []domain.Role
for _, role := range roles {
if !roleMap[role.Permission()] {
clean = append(clean, role)
}
roleMap[role.Permission()] = true
}
return clean
}