improve ParseGroupname and ParseUsername using regex

This commit is contained in:
2026-04-27 21:52:40 +00:00
parent 7fc7584984
commit cc53d7bdea
+18 -13
View File
@@ -2,7 +2,7 @@ package proxmoxaas_common_lib
import (
"fmt"
"strings"
"regexp"
)
func (g Groupname) ToString() string {
@@ -14,19 +14,23 @@ func (u Username) ToString() string {
}
// returns an error if the groupname format was not correct
// TODO: handle group names with x-y format where y is not a registered realm
// TODO: handle group names with x-y-z-... format
func ParseGroupname(groupname string) (Groupname, error) {
g := Groupname{}
x := strings.Split(groupname, "-")
if len(x) == 1 {
// <groupid>-<realm>
m1 := regexp.MustCompilePOSIX("([[:alnum:]]+)-([[:alnum:]]+)")
// <groupid> (implied pve realm)
m2 := regexp.MustCompilePOSIX("([[:alnum:]]+)")
x1 := m1.FindStringSubmatch(groupname)
x2 := m2.FindStringSubmatch(groupname)
if len(x1) == 3 {
g.GroupID = x1[1]
g.Realm = x1[2]
return g, nil
} else if len(x2) == 2 {
g.GroupID = groupname
g.Realm = "pve"
return g, nil
} else if len(x) == 2 {
g.GroupID = x[0]
g.Realm = x[1]
return g, nil
} else {
return g, fmt.Errorf("groupid did not follow the format <groupid> or <groupid>-<realm>")
}
@@ -35,10 +39,11 @@ func ParseGroupname(groupname string) (Groupname, error) {
// returns an error if the username format was not correct
func ParseUsername(username string) (Username, error) {
u := Username{}
x := strings.Split(username, "@")
if len(x) == 2 {
u.UserID = x[0]
u.Realm = x[1]
m := regexp.MustCompilePOSIX("([[:alnum:]]+)@([[:alnum:]]+)")
x := m.FindStringSubmatch(username)
if len(x) == 3 {
u.UserID = x[1]
u.Realm = x[2]
return u, nil
} else {
return u, fmt.Errorf("userid did not follow the format <userid>@<realm>")