forked from evergreen-ci/evergreen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_role.go
85 lines (73 loc) · 2.37 KB
/
config_role.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
package evergreen
import (
"github.com/mongodb/anser/bsonutil"
"github.com/pkg/errors"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
)
// LDAPRoleMap contains mappings of LDAP groups for a user to roles. LDAP
// groups are represented by their name and roles by their unique ID in the
// roles collection.
type LDAPRoleMap []LDAPRoleMapping
// LDAPRoleMapping contains a single mapping of a LDAP group to a role ID.
type LDAPRoleMapping struct {
LDAPGroup string `bson:"ldap_group" json:"ldap_group" yaml:"ldap_group"`
RoleID string `bson:"role_id" json:"role_id" yaml:"role_id"`
}
var (
ldapRoleMappingLDAPGroupKey = bsonutil.MustHaveTag(LDAPRoleMap{}, "LDAPGroup")
ldapRoleMappingRoleIDKey = bsonutil.MustHaveTag(LDAPRoleMap{}, "RoleID")
)
// Add adds a new (or updates an existing) LDAP group to role mapping in the
// database.
func (m *LDAPRoleMap) Add(group, roleID string) error {
env := GetEnvironment()
ctx, cancel := env.Context()
defer cancel()
coll := env.DB().Collection(ConfigCollection)
s := &Settings{}
res, err := coll.UpdateOne(
ctx,
byId(s.SectionId()),
bson.M{
"$set": bson.M{
bsonutil.GetDottedKeyName(ldapRoleMapKey, "$[elem]", ldapRoleMappingRoleIDKey): roleID,
},
},
options.Update().SetArrayFilters(options.ArrayFilters{
Filters: []interface{}{
bson.M{
bsonutil.GetDottedKeyName("elem", ldapRoleMappingLDAPGroupKey): bson.M{"$eq": group},
},
},
}),
)
if err != nil || res.MatchedCount > 0 {
return errors.Wrapf(err, "error adding %s:%s to the LDAP-role map", group, roleID)
}
_, err = coll.UpdateOne(ctx, byId(s.SectionId()), bson.M{
"$push": bson.M{
ldapRoleMapKey: bson.M{
ldapRoleMappingLDAPGroupKey: group,
ldapRoleMappingRoleIDKey: roleID,
},
},
}, options.Update().SetUpsert(true))
return errors.Wrapf(err, "error adding %s:%s to the LDAP-role map", group, roleID)
}
// Remove removes a LDAP group to role mapping from the database.
func (m *LDAPRoleMap) Remove(group string) error {
env := GetEnvironment()
ctx, cancel := env.Context()
defer cancel()
coll := env.DB().Collection(ConfigCollection)
s := &Settings{}
_, err := coll.UpdateOne(ctx, byId(s.SectionId()), bson.M{
"$pull": bson.M{
ldapRoleMapKey: bson.M{
ldapRoleMappingLDAPGroupKey: group,
},
},
})
return errors.Wrapf(err, "error removing %s from the LDAP-role map", group)
}