Add role helper functions, add project role barebone, add valid role arr

- HasAnyRoles([]string): Checks if user has *one* of the roles
- HasAllRoles([]string): Cheks if user has *all* of the roles
- HasNotRoles([]string): Checks if user has *none* of the roles
- IsValidRole(string): Checks if given string is known valid role
This commit is contained in:
Christoph Kluge
2023-01-25 16:59:16 +01:00
parent 5abd3641b2
commit 834f9d9085
5 changed files with 73 additions and 11 deletions

View File

@@ -23,8 +23,11 @@ const (
RoleSupport string = "support"
RoleApi string = "api"
RoleUser string = "user"
RoleProject string = "project"
)
var validRoles = [5]string{RoleAdmin, RoleSupport, RoleApi, RoleUser, RoleProject}
const (
AuthViaLocalPassword int8 = 0
AuthViaLDAP int8 = 1
@@ -38,6 +41,7 @@ type User struct {
Roles []string `json:"roles"`
AuthSource int8 `json:"via"`
Email string `json:"email"`
Project string `json:"project"`
Expiration time.Time
}
@@ -50,6 +54,66 @@ func (u *User) HasRole(role string) bool {
return false
}
// Role-Arrays are short: performance not impacted by nested loop
func (u *User) HasAnyRole(queryroles []string) bool {
for _, ur := range u.Roles {
for _, qr := range queryroles {
if ur == qr {
return true
}
}
}
return false
}
// Role-Arrays are short: performance not impacted by nested loop
func (u *User) HasAllRoles(queryroles []string) bool {
target := len(queryroles)
matches := 0
for _, ur := range u.Roles {
for _, qr := range queryroles {
if ur == qr {
matches += 1
break
}
}
}
if matches == target {
return true
} else {
return false
}
}
// Role-Arrays are short: performance not impacted by nested loop
func (u *User) HasNotRoles(queryroles []string) bool {
matches := 0
for _, ur := range u.Roles {
for _, qr := range queryroles {
if ur == qr {
matches += 1
break
}
}
}
if matches == 0 {
return true
} else {
return false
}
}
func IsValidRole(role string) bool {
for _, r := range validRoles {
if r == role {
return true
}
}
return false
}
func GetUser(ctx context.Context) *User {
x := ctx.Value(ContextUserKey)
if x == nil {