forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
69 lines (60 loc) · 1.82 KB
/
common.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
package rbac
import (
"strings"
"github.com/pkg/errors"
v3 "github.com/rancher/types/apis/management.cattle.io/v3"
rbacv1 "k8s.io/api/rbac/v1"
)
// BuildSubjectFromRTB This function will generate
// PRTB and CRTB to the subject with user, group
// or service account
func BuildSubjectFromRTB(object interface{}) (rbacv1.Subject, error) {
var userName, groupPrincipalName, groupName, name, kind, sa, namespace string
if rtb, ok := object.(*v3.ProjectRoleTemplateBinding); ok {
userName = rtb.UserName
groupPrincipalName = rtb.GroupPrincipalName
groupName = rtb.GroupName
sa = rtb.ServiceAccount
} else if rtb, ok := object.(*v3.ClusterRoleTemplateBinding); ok {
userName = rtb.UserName
groupPrincipalName = rtb.GroupPrincipalName
groupName = rtb.GroupName
} else {
return rbacv1.Subject{}, errors.Errorf("unrecognized roleTemplateBinding type: %v", object)
}
if userName != "" {
name = userName
kind = "User"
}
if groupPrincipalName != "" {
if name != "" {
return rbacv1.Subject{}, errors.Errorf("roletemplatebinding has more than one subject fields set: %v", object)
}
name = groupPrincipalName
kind = "Group"
}
if groupName != "" {
if name != "" {
return rbacv1.Subject{}, errors.Errorf("roletemplatebinding has more than one subject fields set: %v", object)
}
name = groupName
kind = "Group"
}
if sa != "" {
parts := strings.SplitN(sa, ":", 2)
if len(parts) < 2 {
return rbacv1.Subject{}, errors.Errorf("service account %s of projectroletemplatebinding is invalid: %v", sa, object)
}
namespace = parts[0]
name = parts[1]
kind = "ServiceAccount"
}
if name == "" {
return rbacv1.Subject{}, errors.Errorf("roletemplatebinding doesn't have any subject fields set: %v", object)
}
return rbacv1.Subject{
Namespace: namespace,
Kind: kind,
Name: name,
}, nil
}