From 307a67447dd18a5331cd1856e6160a2402054265 Mon Sep 17 00:00:00 2001 From: Erik Geiser Date: Mon, 2 Jun 2025 17:02:35 +0200 Subject: [PATCH] Omit empty domain in Credential.UPN() --- credentials.go | 13 +++++++++++-- credentials_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/credentials.go b/credentials.go index 0a2a246..995eb31 100644 --- a/credentials.go +++ b/credentials.go @@ -101,9 +101,18 @@ func CredentialFromPFXBytes( return cred, nil } -// UPN is the user principal name (username@domain). +// UPN is the user principal name (username@domain). If the credential does not +// contain a domain, only the username is returned. If username and domain are +// empty, the UPN will be empty, too. func (c *Credential) UPN() string { - return c.Username + "@" + c.Domain + switch { + case c.Username == "" && c.Domain == "": + return "" + case c.Domain == "": + return c.Username + default: + return c.Username + "@" + c.Domain + } } // LogonName is the legacy logon name (domain\username). diff --git a/credentials_test.go b/credentials_test.go index 2f290bb..4214305 100644 --- a/credentials_test.go +++ b/credentials_test.go @@ -67,3 +67,41 @@ func TestLookupDC(t *testing.T) { t.Fatalf("DC address is %q instead of %q", dc.Address(), dcHostname) } } + +func TestUPN(t *testing.T) { + t.Run("user and domain", func(t *testing.T) { + expcetedUPN := "foo@bar" + upn := (&adauth.Credential{Username: "foo", Domain: "bar"}).UPN() + + if upn != expcetedUPN { + t.Errorf("UPN is %q insteaf of %q", upn, expcetedUPN) + } + }) + + t.Run("user without domain", func(t *testing.T) { + expcetedUPN := "foo" + upn := (&adauth.Credential{Username: "foo"}).UPN() + + if upn != expcetedUPN { + t.Errorf("UPN is %q insteaf of %q", upn, expcetedUPN) + } + }) + + t.Run("domain without username", func(t *testing.T) { + expcetedUPN := "@bar" + upn := (&adauth.Credential{Domain: "bar"}).UPN() + + if upn != expcetedUPN { + t.Errorf("UPN is %q insteaf of %q", upn, expcetedUPN) + } + }) + + t.Run("no username and no domain", func(t *testing.T) { + expcetedUPN := "" + upn := (&adauth.Credential{}).UPN() + + if upn != expcetedUPN { + t.Errorf("UPN is %q insteaf of %q", upn, expcetedUPN) + } + }) +}