Identity: Use typed version of namespace id (#87257)

* Remove different constructors and only use NewNamespaceID

* AdminUser: check typed namespace id

* Identity: Add convinient function to parse valid user id when type is either user or service account

* Annotations: Use typed namespace id instead
This commit is contained in:
Karl Persson
2024-05-08 14:03:53 +02:00
committed by GitHub
parent d83cbe4d85
commit be5ced4287
17 changed files with 52 additions and 74 deletions
+12 -22
View File
@@ -41,7 +41,7 @@ func ParseNamespace(str string) (Namespace, error) {
}
}
var AnonymousNamespaceID = MustNewNamespaceID(NamespaceAnonymous, 0)
var AnonymousNamespaceID = NewNamespaceID(NamespaceAnonymous, 0)
func ParseNamespaceID(str string) (NamespaceID, error) {
var namespaceID NamespaceID
@@ -72,27 +72,7 @@ func MustParseNamespaceID(str string) NamespaceID {
return namespaceID
}
// NewNamespaceID creates a new NamespaceID, will fail for invalid namespace.
func NewNamespaceID(namespace Namespace, id int64) (NamespaceID, error) {
return NamespaceID{
id: strconv.FormatInt(id, 10),
namespace: namespace,
}, nil
}
// MustNewNamespaceID creates a new NamespaceID, will panic for invalid namespace.
// Suitable to use in tests or when we can guarantee that we pass a correct format.
func MustNewNamespaceID(namespace Namespace, id int64) NamespaceID {
namespaceID, err := NewNamespaceID(namespace, id)
if err != nil {
panic(err)
}
return namespaceID
}
// NewNamespaceIDUnchecked creates a new NamespaceID without checking if namespace is valid.
// It us up to the caller to ensure that namespace is valid.
func NewNamespaceIDUnchecked(namespace Namespace, id int64) NamespaceID {
func NewNamespaceID(namespace Namespace, id int64) NamespaceID {
return NamespaceID{
id: strconv.FormatInt(id, 10),
namespace: namespace,
@@ -117,6 +97,16 @@ func (ni NamespaceID) ID() string {
return ni.id
}
// UserID will try to parse and int64 identifier if namespace is either user or service-account.
// For all other namespaces '0' will be returned.
func (ni NamespaceID) UserID() (int64, error) {
if ni.IsNamespace(NamespaceUser, NamespaceServiceAccount) {
return ni.ParseInt()
}
return 0, nil
}
// ParseInt will try to parse the id as an int64 identifier.
func (ni NamespaceID) ParseInt() (int64, error) {
return strconv.ParseInt(ni.id, 10, 64)
}