35 lines
1.1 KiB
Go
35 lines
1.1 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
apierrors "git.yuntuo.hk/k2safe/go-omni/errors"
|
|
"git.yuntuo.hk/k2safe/go-omni/httpx"
|
|
)
|
|
|
|
type Policy interface {
|
|
Authorize(context.Context, Principal, string, string) error
|
|
}
|
|
type PolicyFunc func(context.Context, Principal, string, string) error
|
|
|
|
func (f PolicyFunc) Authorize(ctx context.Context, p Principal, action, resource string) error {
|
|
return f(ctx, p, action, resource)
|
|
}
|
|
func RequirePermission(policy Policy, action string, resource func(*httpx.Context) string) httpx.Middleware {
|
|
return func(next httpx.Handler) httpx.Handler {
|
|
return func(c *httpx.Context) error {
|
|
p, ok := FromContext(c)
|
|
if !ok {
|
|
return apierrors.Unauthorized("UNAUTHENTICATED", "authentication required")
|
|
}
|
|
if policy == nil || action == "" || resource == nil {
|
|
return apierrors.Internal(errors.New("auth: incomplete permission policy"))
|
|
}
|
|
if err := policy.Authorize(c.Context(), p, action, resource(c)); err != nil {
|
|
return apierrors.Forbidden("FORBIDDEN", "permission denied").WithCause(err)
|
|
}
|
|
return next(c)
|
|
}
|
|
}
|
|
}
|