This repository has been archived by the owner on Jun 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
role_member.go
97 lines (88 loc) · 2.04 KB
/
role_member.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
package logic
import (
"fmt"
"github.com/suzuki-shunsuke/go-set"
"github.com/suzuki-shunsuke/go-graylog"
)
const (
adminName string = "admin"
)
// RoleMembers returns members of a given role.
func (lgc *Logic) RoleMembers(name string) ([]graylog.User, int, error) {
ok, err := lgc.HasRole(name)
if err != nil {
return nil, 500, err
}
if !ok {
return nil, 404, fmt.Errorf("no role found with name %s", name)
}
users := []graylog.User{}
us, sc, err := lgc.GetUsers()
if err != nil {
return us, sc, err
}
for _, user := range us {
if user.Roles == nil {
continue
}
for roleName := range user.Roles.ToMap(false) {
if roleName == name {
users = append(users, user)
break
}
}
}
return users, 200, nil
}
// AddUserToRole adds a user to a role.
func (lgc *Logic) AddUserToRole(userName, roleName string) (int, error) {
ok, err := lgc.HasRole(roleName)
if err != nil {
return 500, err
}
if !ok {
return 404, fmt.Errorf("no role found with name %s", roleName)
}
if userName == adminName {
return 500, fmt.Errorf("cannot modify local root user, this is a bug")
}
user, sc, err := lgc.GetUser(userName)
if err != nil {
return sc, err
}
if user == nil {
return 404, fmt.Errorf("no user found with name %s", userName)
}
if user.Roles == nil {
user.Roles = set.NewStrSet(roleName)
} else {
user.Roles.Add(roleName)
}
return lgc.UpdateUser(user.NewUpdateParams())
}
// RemoveUserFromRole removes a user from a role.
func (lgc *Logic) RemoveUserFromRole(
userName, roleName string,
) (int, error) {
ok, err := lgc.HasRole(roleName)
if err != nil {
return 500, err
}
if !ok {
return 404, fmt.Errorf(`no role found with name "%s"`, roleName)
}
if userName == adminName {
return 500, fmt.Errorf("cannot modify local root user, this is a bug")
}
user, sc, err := lgc.GetUser(userName)
if err != nil {
return sc, err
}
if user == nil {
return 404, fmt.Errorf("no user found with name %s", userName)
}
if user.Roles != nil {
user.Roles.Remove(roleName)
}
return lgc.UpdateUser(user.NewUpdateParams())
}