|
package permission |
|
|
|
import ( |
|
"context" |
|
"strings" |
|
"sync/atomic" |
|
) |
|
|
|
|
|
type Checker func(context.Context) bool |
|
|
|
func checkLimit(ctx context.Context) error { |
|
n, ok := ctx.Value(contextKeyCheckCount).(*uint64) |
|
if !ok { |
|
return newGeneric(false, "invalid auth context for check limit") |
|
} |
|
max, ok := ctx.Value(contextKeyCheckCountMax).(uint64) |
|
if !ok { |
|
return newGeneric(false, "invalid auth context for max check limit") |
|
} |
|
|
|
v := atomic.AddUint64(n, 1) |
|
if max > 0 && v > max { |
|
return newGeneric(false, "exceeded auth check limit") |
|
} |
|
|
|
return nil |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
func LimitCheckAny(ctx context.Context, checks ...Checker) error { |
|
if !All(ctx) { |
|
return newGeneric(true, "") |
|
} |
|
|
|
|
|
err := checkLimit(ctx) |
|
if err != nil { |
|
return err |
|
} |
|
|
|
if len(checks) == 0 { |
|
return nil |
|
} |
|
for _, c := range checks { |
|
if c != nil && c(ctx) { |
|
return nil |
|
} |
|
} |
|
|
|
return newGeneric(false, "") |
|
} |
|
|
|
|
|
|
|
func All(ctx context.Context) bool { |
|
if v, ok := ctx.Value(contextHasAuth).(int); ok && v == 1 { |
|
return true |
|
} |
|
|
|
return false |
|
} |
|
|
|
|
|
func Admin(ctx context.Context) bool { |
|
if System(ctx) { |
|
return true |
|
} |
|
r, ok := ctx.Value(contextKeyUserRole).(Role) |
|
if ok && r == RoleAdmin { |
|
return true |
|
} |
|
|
|
return false |
|
} |
|
|
|
|
|
func User(ctx context.Context) bool { |
|
if System(ctx) { |
|
return true |
|
} |
|
r, ok := ctx.Value(contextKeyUserRole).(Role) |
|
if ok && (r == RoleUser || r == RoleAdmin) { |
|
return true |
|
} |
|
|
|
return false |
|
} |
|
|
|
|
|
func Service(ctx context.Context) bool { |
|
return ServiceID(ctx) != "" |
|
} |
|
|
|
|
|
func System(ctx context.Context) bool { |
|
return SystemComponentName(ctx) != "" |
|
} |
|
|
|
|
|
func Team(ctx context.Context) bool { |
|
return TeamID(ctx) != "" |
|
} |
|
|
|
|
|
func MatchService(serviceID string) Checker { |
|
return func(ctx context.Context) bool { |
|
if serviceID == "" { |
|
return false |
|
} |
|
return ServiceID(ctx) == strings.ToLower(serviceID) |
|
} |
|
} |
|
|
|
|
|
func MatchTeam(teamID string) Checker { |
|
return func(ctx context.Context) bool { |
|
return TeamID(ctx) == strings.ToLower(teamID) |
|
} |
|
} |
|
|
|
|
|
func MatchUser(userID string) Checker { |
|
return func(ctx context.Context) bool { |
|
if userID == "" { |
|
return false |
|
} |
|
return UserID(ctx) == strings.ToLower(userID) |
|
} |
|
} |
|
|