-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Mike Mason <[email protected]>
- Loading branch information
Showing
2 changed files
with
54 additions
and
44 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
package permissions | ||
|
||
import ( | ||
"context" | ||
|
||
"github.com/labstack/echo/v4" | ||
"go.infratographer.com/x/gidx" | ||
) | ||
|
||
var ( | ||
// CheckerCtxKey is the context key used to set the checker handling function | ||
CheckerCtxKey = checkerCtxKey{} | ||
|
||
// DefaultAllowChecker defaults to allow when checker is disabled or skipped | ||
DefaultAllowChecker Checker = func(_ context.Context, _ gidx.PrefixedID, _ string) error { | ||
return nil | ||
} | ||
|
||
// DefaultDenyChecker defaults to denied when checker is disabled or skipped | ||
DefaultDenyChecker Checker = func(_ context.Context, _ gidx.PrefixedID, _ string) error { | ||
return ErrPermissionDenied | ||
} | ||
) | ||
|
||
// Checker defines the checker function definition | ||
type Checker func(ctx context.Context, resource gidx.PrefixedID, action string) error | ||
|
||
type checkerCtxKey struct{} | ||
|
||
func setCheckerContext(c echo.Context, checker Checker) { | ||
if checker == nil { | ||
checker = DefaultDenyChecker | ||
} | ||
|
||
req := c.Request().WithContext( | ||
context.WithValue( | ||
c.Request().Context(), | ||
CheckerCtxKey, | ||
checker, | ||
), | ||
) | ||
|
||
c.SetRequest(req) | ||
} | ||
|
||
// CheckAccess runs the checker function to check if the provided resource and action are supported. | ||
func CheckAccess(ctx context.Context, resource gidx.PrefixedID, action string) error { | ||
checker, ok := ctx.Value(CheckerCtxKey).(Checker) | ||
if !ok { | ||
return ErrCheckerNotFound | ||
} | ||
|
||
return checker(ctx, resource, action) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters