diff --git a/pkg/cloudid/models/cloudaccount.go b/pkg/cloudid/models/cloudaccount.go index b854bf041f..aa232b879d 100644 --- a/pkg/cloudid/models/cloudaccount.go +++ b/pkg/cloudid/models/cloudaccount.go @@ -44,6 +44,7 @@ import ( "yunion.io/x/onecloud/pkg/mcclient/modules" "yunion.io/x/onecloud/pkg/util/httputils" "yunion.io/x/onecloud/pkg/util/logclient" + "yunion.io/x/onecloud/pkg/util/stringutils2" ) // +onecloud:swagger-gen-ignore @@ -1626,7 +1627,7 @@ func (self *SCloudaccount) RegisterCloudrole(userId, spId string) (*SCloudrole, role.CloudaccountId = self.Id role.OwnerId = userId role.SAMLProviderId = spId - role.Name = user.GetName() + role.Name = stringutils2.GenerateRoleName(user.GetName()) role.Status = api.CLOUD_ROLE_STATUS_CREATING role.DomainId = self.DomainId return role, CloudroleManager.TableSpec().Insert(context.TODO(), role) diff --git a/pkg/util/stringutils2/stringutils.go b/pkg/util/stringutils2/stringutils.go index 4368fbf08a..b6bdb86b8c 100644 --- a/pkg/util/stringutils2/stringutils.go +++ b/pkg/util/stringutils2/stringutils.go @@ -18,8 +18,10 @@ import ( "crypto/md5" "encoding/hex" "fmt" + "math/rand" "strconv" "strings" + "time" "unicode" "yunion.io/x/pkg/util/osprofile" @@ -211,3 +213,32 @@ func GetCharTypeCount(str string) int { } return ret } + +// Qcloud: 1-128个英文字母、数字和+=,.@_- +// Aws: 请使用字母数字和‘+=,.@-_’字符。 最长 64 个字符 +// Common: 1-64个字符, 数字字母或 +=,.@-_ +func GenerateRoleName(roleName string) string { + ret := "" + for _, s := range roleName { + if (s >= '0' && s <= '9') || (s >= 'a' && s <= 'z') || (s >= 'A' && s <= 'Z') || strings.Contains("+=,.@-_", string(s)) { + ret += string(s) + } + } + + if len(ret) == 0 { + return func(length int) string { + bytes := []byte("23456789abcdefghijkmnpqrstuvwxyz") + result := []byte{} + r := rand.New(rand.NewSource(time.Now().UnixNano())) + for i := 0; i < length; i++ { + result = append(result, bytes[r.Intn(len(bytes))]) + } + return "role-" + string(result) + }(12) + } + + if len(ret) > 64 { + return ret[:64] + } + return ret +} diff --git a/pkg/util/stringutils2/stringutils_test.go b/pkg/util/stringutils2/stringutils_test.go index 6315d192e6..bd5c1c926d 100644 --- a/pkg/util/stringutils2/stringutils_test.go +++ b/pkg/util/stringutils2/stringutils_test.go @@ -208,3 +208,32 @@ func TestGetCharTypeCount(t *testing.T) { } } } + +func TestRoleName(t *testing.T) { + cases := []struct { + in string + want string + random bool + length int + }{ + { + in: "小琪", + random: true, + length: 17, + }, + { + in: "123^567", + want: "123567", + }, + } + for _, c := range cases { + got := GenerateRoleName(c.in) + if c.random { + if len(got) != c.length { + t.Errorf("GenerateRoleName %s random want %d length got %d(%s)", c.in, c.length, len(got), got) + } + } else if got != c.want { + t.Errorf("GenerateRoleName %s want %s got %s", c.in, c.want, got) + } + } +}