Skip to content

Commit 20ac4b7

Browse files
authored
add method to judge if account is admin (#78)
* add method to judge if account is admin
1 parent 41f1988 commit 20ac4b7

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

rbac/account.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,3 +80,16 @@ type AuthUser struct {
8080
Username string `json:"name,omitempty"`
8181
Password string `json:"password,omitempty"`
8282
}
83+
84+
func (a *Account) HasAdminRole() bool {
85+
if a.Role == RoleAdmin {
86+
return true
87+
}
88+
89+
for _, r := range a.Roles {
90+
if r == RoleAdmin {
91+
return true
92+
}
93+
}
94+
return false
95+
}

rbac/account_test.go

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@
1717

1818
package rbac
1919

20-
import "testing"
20+
import (
21+
"testing"
22+
)
2123

2224
func TestAccount_Check(t *testing.T) {
2325
type fields struct {
@@ -73,3 +75,34 @@ func TestAccount_Check(t *testing.T) {
7375
}
7476
}
7577
}
78+
79+
func TestAccount_HasAdminRole(t *testing.T) {
80+
tests := []struct {
81+
name string
82+
a *Account
83+
want bool
84+
}{
85+
{
86+
name: "compatible with old",
87+
a: &Account{Role: RoleAdmin},
88+
want: true,
89+
},
90+
{
91+
name: "has admin",
92+
a: &Account{Roles: []string{RoleAdmin, RoleDeveloper}},
93+
want: true,
94+
},
95+
{
96+
name: "not admin",
97+
a: &Account{Roles: []string{RoleDeveloper}},
98+
want: false,
99+
},
100+
}
101+
for _, tt := range tests {
102+
t.Run(tt.name, func(t *testing.T) {
103+
if got := tt.a.HasAdminRole(); got != tt.want {
104+
t.Errorf("Account.HasAdminRole() = %v, want %v", got, tt.want)
105+
}
106+
})
107+
}
108+
}

0 commit comments

Comments
 (0)