Documentation
¶
Overview ¶
Package authz decides what an authenticated user may do: gates (named abilities) and policies (abilities on a model type). Decisions fail closed: an ability or policy that was never registered denies.
gate := authz.New(func(ctx context.Context) (*models.User, error) {
return auth.UserFrom[*models.User](ctx, "web")
})
gate.Define("edit-settings", func(ctx context.Context, u *models.User) bool { return u.Role == "admin" })
gate.Register(authz.For[*models.Post](policies.PostPolicy{}))
r.Services().Authorizer = gate
if err := c.Authorize("update", post); err != nil { return err } // 403 / 404
Index ¶
- Variables
- type Gate
- func (g *Gate[U]) Allows(ctx context.Context, u U, ability string, subject any) bool
- func (g *Gate[U]) Authorize(ctx context.Context, ability string, subject any) error
- func (g *Gate[U]) Before(fn func(ctx context.Context, u U, ability string) *Result)
- func (g *Gate[U]) Check(ctx context.Context, u U, ability string, subject any) (Result, error)
- func (g *Gate[U]) Define(ability string, fn func(ctx context.Context, u U) bool)
- func (g *Gate[U]) DefineResult(ability string, fn func(ctx context.Context, u U) Result)
- func (g *Gate[U]) Register(policies ...Policy) error
- type Policy
- type Result
Constants ¶
This section is empty.
Variables ¶
var ErrForbidden = &errs.HTTPError{Status: http.StatusForbidden, Message: "This action is unauthorized."}
ErrForbidden is the default denial (403).
var ErrNoUser = &errs.HTTPError{Status: http.StatusUnauthorized, Message: "Unauthenticated."}
ErrNoUser is returned (401) when the user resolver finds nobody.
Functions ¶
This section is empty.
Types ¶
type Gate ¶
type Gate[U any] struct { // contains filtered or unexported fields }
Gate holds abilities and policies for users of type U.
func New ¶
New returns a gate; user resolves the current user from the request context (e.g. auth.UserFrom).
func (*Gate[U]) Authorize ¶
Authorize implements web.Authorizer: it resolves the current user from ctx and returns nil, ErrNoUser (401), a 403 or a 404. Unregistered abilities and policies deny (fail closed) and are reported in the returned error's cause for logs.
func (*Gate[U]) DefineResult ¶
DefineResult registers a named ability returning a Result (for 404s or custom messages).
type Policy ¶
type Policy struct {
// contains filtered or unexported fields
}
Policy is a policy bound to a subject type, created by For.
type Result ¶
type Result struct {
// contains filtered or unexported fields
}
Result is an authorization decision.
func DenyAsNotFound ¶
func DenyAsNotFound() Result
DenyAsNotFound refuses with 404, hiding that the resource exists.