control: Generalize cookie and csrf handling

This commit is contained in:
Tom Wiesing 2023-01-05 15:59:24 +01:00
parent eb17dbe33f
commit 34bdb3cf24
No known key found for this signature in database
15 changed files with 122 additions and 44 deletions

View file

@ -9,9 +9,35 @@ import (
type Routeable interface {
Component
// Routes returns the routes served by this servable
Routes() []string
// Routes returns information about the routes to be handled by this Routeable
Routes() Routes
// HandleRoute returns the handler for the requested route
HandleRoute(ctx context.Context, route string) (http.Handler, error)
// HandleRoute returns the handler for the requested path
HandleRoute(ctx context.Context, path string) (http.Handler, error)
}
// Routes represents information about a single Routeable
type Routes struct {
// Paths are the paths handled by this routeable.
// Each path is passed to HandleRoute() individually.
Paths []string
// CSRF indicates if this route should be protected by CSRF.
// CSRF protection is applied prior to any custom decorator being called.
CSRF bool
// Decorators is a function applied to the handler returned by HandleRoute.
// When nil, it is not applied.
Decorator func(http.Handler) http.Handler
}
// Decorate decorates the provided handler with the options specified in this handler.
func (routes Routes) Decorate(handler http.Handler, csrf func(http.Handler) http.Handler) http.Handler {
if routes.CSRF && csrf != nil {
handler = csrf(handler)
}
if routes.Decorator != nil {
handler = routes.Decorator(handler)
}
return handler
}