From 5a8f19589bcb0505972bbc1b002e1abe57f24f4a Mon Sep 17 00:00:00 2001 From: Ben Toogood Date: Mon, 11 May 2020 11:34:22 +0100 Subject: [PATCH] Auth account.HasRole --- auth/auth.go | 15 +++++++++++++++ auth/auth_test.go | 17 +++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 auth/auth_test.go diff --git a/auth/auth.go b/auth/auth.go index fbca70a6..d7987a07 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -72,6 +72,21 @@ type Account struct { Secret string `json:"secret"` } +// HasRole returns a boolean indicating if the account has the given role +func (a *Account) HasRole(role string) bool { + if a.Roles == nil { + return false + } + + for _, r := range a.Roles { + if r == role { + return true + } + } + + return false +} + // Token can be short or long lived type Token struct { // The token to be used for accessing resources diff --git a/auth/auth_test.go b/auth/auth_test.go new file mode 100644 index 00000000..5283e81e --- /dev/null +++ b/auth/auth_test.go @@ -0,0 +1,17 @@ +package auth + +import "testing" + +func TestHasRole(t *testing.T) { + if new(Account).HasRole("foo") { + t.Errorf("Expected the blank account to not have a role") + } + + acc := Account{Roles: []string{"foo"}} + if !acc.HasRole("foo") { + t.Errorf("Expected the account to have the foo role") + } + if acc.HasRole("bar") { + t.Errorf("Expected the account to not have the bar role") + } +}