zitadel/internal/api/authz/permissions.go
Fabi 351aac22f8
feat: usergrant (#489)
* fix: search usergrants only for allowed projects

* fix: check permissions

* fix: check permissions

* fix: check permissions

* Update internal/management/repository/eventsourcing/eventstore/project.go

Co-authored-by: Silvan <silvan.reusser@gmail.com>

* fix: merge request changes

* fix: variable name

Co-authored-by: Silvan <silvan.reusser@gmail.com>
2020-07-22 14:00:29 +02:00

70 lines
2.1 KiB
Go

package authz
import (
"context"
"github.com/caos/zitadel/internal/errors"
)
func getUserMethodPermissions(ctx context.Context, t *TokenVerifier, requiredPerm string, authConfig Config) (context.Context, []string, error) {
ctxData := GetCtxData(ctx)
if ctxData.IsZero() {
return nil, nil, errors.ThrowUnauthenticated(nil, "AUTH-rKLWEH", "context missing")
}
grant, err := t.ResolveGrant(ctx)
if err != nil {
return nil, nil, err
}
if grant == nil {
return context.WithValue(ctx, requestPermissionsKey, []string{}), []string{}, nil
}
requestPermissions, allPermissions := mapGrantToPermissions(requiredPerm, grant, authConfig)
ctx = context.WithValue(ctx, allPermissionsKey, allPermissions)
return context.WithValue(ctx, requestPermissionsKey, requestPermissions), requestPermissions, nil
}
func mapGrantToPermissions(requiredPerm string, grant *Grant, authConfig Config) ([]string, []string) {
requestPermissions := make([]string, 0)
allPermissions := make([]string, 0)
for _, role := range grant.Roles {
requestPermissions, allPermissions = mapRoleToPerm(requiredPerm, role, authConfig, requestPermissions, allPermissions)
}
return requestPermissions, allPermissions
}
func mapRoleToPerm(requiredPerm, actualRole string, authConfig Config, requestPermissions, allPermissions []string) ([]string, []string) {
roleName, roleContextID := SplitPermission(actualRole)
perms := authConfig.getPermissionsFromRole(roleName)
for _, p := range perms {
permWithCtx := addRoleContextIDToPerm(p, roleContextID)
if !ExistsPerm(allPermissions, permWithCtx) {
allPermissions = append(allPermissions, permWithCtx)
}
if p == requiredPerm {
if !ExistsPerm(requestPermissions, permWithCtx) {
requestPermissions = append(requestPermissions, permWithCtx)
}
}
}
return requestPermissions, allPermissions
}
func addRoleContextIDToPerm(perm, roleContextID string) string {
if roleContextID != "" {
perm = perm + ":" + roleContextID
}
return perm
}
func ExistsPerm(existing []string, perm string) bool {
for _, e := range existing {
if e == perm {
return true
}
}
return false
}