docs(backpack,beachcomber,boardwalk,bonfire,bouncer): compile README Go examples via src= (quick-261118-qsd)
- backpack: Greeter and ExampleApp_Publish replace the whole-file fence - beachcomber: Post's Searchable methods plus a new SearchIndexSchema, a Plugin.Boot that installs the gate, and the existing gate/search regions - boardwalk: new example_test.go; the mount region runs in ExampleHandler - bonfire: importPostsCommand and acmeMain (the binary's main as a function returning the exit code), run by ExampleExecute; ExampleCatalog_Has - bouncer: users/FindByID and ExampleNewJWTGuard; RefreshRoute run by TestDocsRefreshRoute on a production compass config
This commit is contained in:
@@ -30,45 +30,36 @@ Use cases:
|
|||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
```go
|
```go src=modules/backpack/example_test.go#Greeter
|
||||||
package blog
|
// Greeter is a service the acme.greeter plugin offers to other plugins.
|
||||||
|
type Greeter interface {
|
||||||
|
Greet(name string) string
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
import (
|
```go src=modules/backpack/example_test.go#ExampleApp_Publish
|
||||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
app := backpack.New(&compass.Config{})
|
||||||
"git.golem15.com/golem15/summercms/modules/compass"
|
app.SetPlugins([]string{"acme.greeter", "acme.blog"})
|
||||||
)
|
|
||||||
|
|
||||||
// Feed is a service the blog plugin offers to other plugins.
|
// acme.greeter, in its Register step: publish under the interface type.
|
||||||
type Feed interface {
|
var greeter Greeter = englishGreeter{}
|
||||||
Latest(n int) []string
|
if err := app.Publish(greeter); err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
type staticFeed struct{}
|
// acme.blog, in its Boot step: look the service up by the same type.
|
||||||
|
if app.HasPlugin("acme.greeter") {
|
||||||
func (staticFeed) Latest(n int) []string { return []string{"hello-world"} }
|
if found, ok := app.Lookup[Greeter](); ok {
|
||||||
|
fmt.Println(found.Greet("blog"))
|
||||||
func setup() error {
|
|
||||||
cfg, err := compass.Load("config")
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
app := backpack.New(cfg)
|
|
||||||
app.SetPlugins([]string{"acme.blog", "acme.search"})
|
|
||||||
|
|
||||||
// Provider side, usually in the plugin's Register step.
|
|
||||||
var feed Feed = staticFeed{}
|
|
||||||
if err := app.Publish(feed); err != nil { // published under Feed, not staticFeed
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Consumer side, usually in another plugin's Boot step.
|
|
||||||
if app.HasPlugin("acme.blog") {
|
|
||||||
if found, ok := app.Lookup[Feed](); ok {
|
|
||||||
_ = found.Latest(5)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A second Publish under the same type is refused.
|
||||||
|
fmt.Println(app.Publish(greeter) != nil)
|
||||||
|
// Output:
|
||||||
|
// Hello, blog
|
||||||
|
// true
|
||||||
```
|
```
|
||||||
|
|
||||||
Publish under an interface type when consumers should not depend on the concrete implementation; the lookup must use exactly the same type argument.
|
Publish under an interface type when consumers should not depend on the concrete implementation; the lookup must use exactly the same type argument.
|
||||||
|
|||||||
@@ -81,12 +81,18 @@ typesense:
|
|||||||
|
|
||||||
A model implements `beachcomber.Searchable` without importing beachcomber:
|
A model implements `beachcomber.Searchable` without importing beachcomber:
|
||||||
|
|
||||||
```go
|
```go src=modules/beachcomber/example_test.go#Post.SearchableAs
|
||||||
package models
|
// SearchableAs is the index name, before search.prefix.
|
||||||
|
func (Post) SearchableAs() string { return "acme_blog_posts" }
|
||||||
|
```
|
||||||
|
|
||||||
func (Post) SearchableAs() string { return "acme_blog_posts" }
|
```go src=modules/beachcomber/example_test.go#Post.ShouldBeSearchable
|
||||||
func (Post) ShouldBeSearchable() bool { return true }
|
// ShouldBeSearchable keeps drafts out of the index.
|
||||||
|
func (p *Post) ShouldBeSearchable() bool { return p.Published }
|
||||||
|
```
|
||||||
|
|
||||||
|
```go src=modules/beachcomber/example_test.go#Post.ToSearchableArray
|
||||||
|
// ToSearchableArray builds the document from the committed row.
|
||||||
func (p *Post) ToSearchableArray(ctx context.Context, db *gorm.DB) (map[string]any, error) {
|
func (p *Post) ToSearchableArray(ctx context.Context, db *gorm.DB) (map[string]any, error) {
|
||||||
return map[string]any{
|
return map[string]any{
|
||||||
"id": strconv.FormatUint(uint64(p.ID), 10),
|
"id": strconv.FormatUint(uint64(p.ID), 10),
|
||||||
@@ -94,7 +100,10 @@ func (p *Post) ToSearchableArray(ctx context.Context, db *gorm.DB) (map[string]a
|
|||||||
"title": p.Title,
|
"title": p.Title,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```go src=modules/beachcomber/example_test.go#Post.SearchIndexSchema
|
||||||
|
// SearchIndexSchema is the schema a missing index is created with.
|
||||||
func (Post) SearchIndexSchema() map[string]any {
|
func (Post) SearchIndexSchema() map[string]any {
|
||||||
return map[string]any{
|
return map[string]any{
|
||||||
"fields": []map[string]any{
|
"fields": []map[string]any{
|
||||||
@@ -106,40 +115,47 @@ func (Post) SearchIndexSchema() map[string]any {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The plugin imports the engine package for its side effect, builds the service at Boot and installs its kill-switch:
|
The application imports the engine package (for example `beachcomber/typesense`) for its side effect. The plugin builds the service at Boot and installs its kill-switch:
|
||||||
|
|
||||||
```go
|
|
||||||
package acme
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/beachcomber"
|
|
||||||
_ "git.golem15.com/golem15/summercms/modules/beachcomber/typesense"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
```go src=modules/beachcomber/example_test.go#Plugin.Boot
|
||||||
|
// Boot builds the search service and installs its kill-switch.
|
||||||
func (p *Plugin) Boot(app *backpack.App) error {
|
func (p *Plugin) Boot(app *backpack.App) error {
|
||||||
svc, err := beachcomber.From(app)
|
svc, err := beachcomber.From(app)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
svc.SetGate(beachcomber.GateFunc(func(ctx context.Context, db *gorm.DB) bool {
|
installGate(svc)
|
||||||
return acmeSearchEnabled(ctx, db) // false on any read error
|
|
||||||
}))
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
A search endpoint asks the engine for candidate ids:
|
```go src=modules/beachcomber/example_test.go#gate
|
||||||
|
svc.SetGate(beachcomber.GateFunc(func(ctx context.Context, db *gorm.DB) bool {
|
||||||
|
var enabled bool
|
||||||
|
err := db.WithContext(ctx).Raw(`SELECT search_enabled FROM acme_blog_settings WHERE id = 1`).Scan(&enabled).Error
|
||||||
|
return err == nil && enabled
|
||||||
|
}))
|
||||||
|
```
|
||||||
|
|
||||||
```go
|
A search endpoint asks the engine for candidate ids and re-checks them in SQL:
|
||||||
ids, err := svc.Engine().SearchIDs(ctx, svc.IndexName(&models.Post{}), beachcomber.Query{
|
|
||||||
|
```go src=modules/beachcomber/example_test.go#search
|
||||||
|
ids, err := svc.Engine().SearchIDs(ctx, svc.IndexName(&Post{}), beachcomber.Query{
|
||||||
Q: term,
|
Q: term,
|
||||||
QueryBy: []string{"title"},
|
QueryBy: []string{"title"},
|
||||||
FilterBy: "blog_id:=" + strconv.FormatUint(uint64(blogID), 10),
|
FilterBy: "blog_id:=" + strconv.FormatUint(uint64(blogID), 10),
|
||||||
})
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// The ids are candidates from an index that may be stale or loosely
|
||||||
|
// filtered: re-check every one in SQL before exposing a row.
|
||||||
|
var posts []Post
|
||||||
|
err = db.WithContext(ctx).
|
||||||
|
Where("id IN ? AND blog_id = ? AND published", ids, blogID).
|
||||||
|
Order("id").
|
||||||
|
Find(&posts).Error
|
||||||
|
return posts, err
|
||||||
```
|
```
|
||||||
|
|
||||||
## API reference
|
## API reference
|
||||||
|
|||||||
@@ -42,6 +42,17 @@ func (p *Post) ToSearchableArray(ctx context.Context, db *gorm.DB) (map[string]a
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SearchIndexSchema is the schema a missing index is created with.
|
||||||
|
func (Post) SearchIndexSchema() map[string]any {
|
||||||
|
return map[string]any{
|
||||||
|
"fields": []map[string]any{
|
||||||
|
{"name": "id", "type": "string"},
|
||||||
|
{"name": "blog_id", "type": "int64"},
|
||||||
|
{"name": "title", "type": "string"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// memoryEngine is a toy engine: it matches Q against the title and ignores
|
// memoryEngine is a toy engine: it matches Q against the title and ignores
|
||||||
// FilterBy, so its answers are loose candidates, as a stale index's are.
|
// FilterBy, so its answers are loose candidates, as a stale index's are.
|
||||||
type memoryEngine struct {
|
type memoryEngine struct {
|
||||||
@@ -120,6 +131,19 @@ func ExampleFrom() {
|
|||||||
// true
|
// true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Plugin is the acme.blog plugin.
|
||||||
|
type Plugin struct{}
|
||||||
|
|
||||||
|
// Boot builds the search service and installs its kill-switch.
|
||||||
|
func (p *Plugin) Boot(app *backpack.App) error {
|
||||||
|
svc, err := beachcomber.From(app)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
installGate(svc)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// installGate turns search sync on only while the blog's search setting is
|
// installGate turns search sync on only while the blog's search setting is
|
||||||
// on; a failed read counts as off.
|
// on; a failed read counts as off.
|
||||||
func installGate(svc *beachcomber.Service) {
|
func installGate(svc *beachcomber.Service) {
|
||||||
@@ -167,7 +191,10 @@ func TestDocsSearch(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
svc, err := beachcomber.From(app)
|
if err := (&Plugin{}).Boot(app); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
svc, err := beachcomber.From(app) // the service Boot built
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -175,7 +202,6 @@ func TestDocsSearch(t *testing.T) {
|
|||||||
// test installs the toy engine directly, so the global engine list the
|
// test installs the toy engine directly, so the global engine list the
|
||||||
// package's own tests check stays unchanged.
|
// package's own tests check stays unchanged.
|
||||||
beachcomber.DocsUseEngine(svc, memory)
|
beachcomber.DocsUseEngine(svc, memory)
|
||||||
installGate(svc)
|
|
||||||
ctx := t.Context()
|
ctx := t.Context()
|
||||||
indexed := func() int {
|
indexed := func() int {
|
||||||
memory.mu.Lock()
|
memory.mu.Lock()
|
||||||
@@ -255,4 +281,9 @@ func TestDocsDeclarations(t *testing.T) {
|
|||||||
if err != nil || doc["id"] != "5" || doc["blog_id"] != int64(7) {
|
if err != nil || doc["id"] != "5" || doc["blog_id"] != int64(7) {
|
||||||
t.Fatalf("ToSearchableArray = %v, %v", doc, err)
|
t.Fatalf("ToSearchableArray = %v, %v", doc, err)
|
||||||
}
|
}
|
||||||
|
var _ beachcomber.IndexSchemaProvider = Post{}
|
||||||
|
fields, _ := p.SearchIndexSchema()["fields"].([]map[string]any)
|
||||||
|
if len(fields) != 3 || fields[0]["name"] != "id" {
|
||||||
|
t.Fatalf("SearchIndexSchema fields = %v", fields)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ Use cases:
|
|||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
```go
|
```go src=modules/boardwalk/example_test.go#mount
|
||||||
notFoundAPI := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
notFoundAPI := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
w.WriteHeader(http.StatusNotFound)
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
|||||||
45
modules/boardwalk/example_test.go
Normal file
45
modules/boardwalk/example_test.go
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
package boardwalk_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/boardwalk"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mountAdmin serves the embedded admin SPA under /backend; admin API paths
|
||||||
|
// it does not know answer JSON.
|
||||||
|
func mountAdmin(mux *http.ServeMux) error {
|
||||||
|
// docs:start mount
|
||||||
|
notFoundAPI := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
_, _ = w.Write([]byte(`{"error":"not found"}`))
|
||||||
|
})
|
||||||
|
|
||||||
|
spa, err := boardwalk.Handler("/backend", notFoundAPI)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
mux.Handle("/backend/", spa)
|
||||||
|
// docs:end mount
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleHandler() {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
if err := mountAdmin(mux); err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, path := range []string{"/backend/", "/backend/posts/7", "/backend/api/missing"} {
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
|
||||||
|
fmt.Println(path, rec.Code, rec.Header().Get("Content-Type"), rec.Header().Get(boardwalk.BuildHeader) != "")
|
||||||
|
}
|
||||||
|
// Output:
|
||||||
|
// /backend/ 200 text/html; charset=utf-8 true
|
||||||
|
// /backend/posts/7 200 text/html; charset=utf-8 true
|
||||||
|
// /backend/api/missing 404 application/json true
|
||||||
|
}
|
||||||
@@ -53,18 +53,12 @@ Use cases:
|
|||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
```go
|
A command declares its arguments and flags and gets an injected console:
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
```go src=modules/bonfire/example_test.go#importPostsCommand
|
||||||
"context"
|
// importPostsCommand is the blog:import command of the acme binary.
|
||||||
"os"
|
func importPostsCommand() bonfire.Command {
|
||||||
|
return bonfire.Command{
|
||||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
importPosts := bonfire.Command{
|
|
||||||
Name: "blog:import",
|
Name: "blog:import",
|
||||||
Description: "Import posts from a feed",
|
Description: "Import posts from a feed",
|
||||||
Args: []bonfire.Arg{{Name: "url", Description: "Feed URL", Required: true}},
|
Args: []bonfire.Arg{{Name: "url", Description: "Feed URL", Required: true}},
|
||||||
@@ -84,28 +78,43 @@ func main() {
|
|||||||
})
|
})
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
args := os.Args[1:]
|
The binary's main function calls this with os.Args[1:], os.Stdout and os.Stderr and exits with the code it returns:
|
||||||
|
|
||||||
|
```go src=modules/bonfire/example_test.go#acmeMain
|
||||||
|
// acmeMain is the body of the acme binary's main function, which calls
|
||||||
|
// os.Exit(acmeMain(os.Args[1:], os.Stdout, os.Stderr)).
|
||||||
|
func acmeMain(args []string, stdout, stderr io.Writer) int {
|
||||||
g := bonfire.PeekGlobals(args)
|
g := bonfire.PeekGlobals(args)
|
||||||
root, err := bonfire.NewRoot("acme", []bonfire.Command{importPosts}, os.Stdout,
|
root, err := bonfire.NewRoot("acme", []bonfire.Command{importPostsCommand()}, stdout,
|
||||||
bonfire.WithVersion(bonfire.BuildVersion()))
|
bonfire.WithVersion(bonfire.BuildVersion()))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
os.Exit(bonfire.Fail(os.Stderr, "acme", err, g))
|
return bonfire.Fail(stderr, "acme", err, g)
|
||||||
}
|
}
|
||||||
os.Exit(bonfire.Execute(context.Background(), root, args))
|
return bonfire.Execute(context.Background(), root, args)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Running a command in-process, with empty stdin so prompts take their defaults:
|
Running a command in-process, with empty stdin so prompts take their defaults:
|
||||||
|
|
||||||
```go
|
```go src=modules/bonfire/example_test.go#ExampleCatalog_Has
|
||||||
catalog := bonfire.NewCatalog(commands)
|
ctx := context.Background()
|
||||||
|
catalog := bonfire.NewCatalog([]bonfire.Command{importPostsCommand()})
|
||||||
if catalog.Has("blog:import") {
|
if catalog.Has("blog:import") {
|
||||||
err := catalog.Call(ctx, "blog:import", []string{"--dry-run", "https://example.com/feed"}, os.Stdout)
|
err := catalog.Call(ctx, "blog:import", []string{"--dry-run", "https://example.com/feed"}, os.Stdout)
|
||||||
if errors.Is(err, bonfire.ErrUnknownCommand) {
|
fmt.Println(err)
|
||||||
// not registered in this binary
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
err := catalog.Call(ctx, "blog:export", nil, os.Stdout)
|
||||||
|
fmt.Println(errors.Is(err, bonfire.ErrUnknownCommand)) // not registered in this binary
|
||||||
|
// Output:
|
||||||
|
// [...] Importing https://example.com/feed
|
||||||
|
// Tag
|
||||||
|
// news
|
||||||
|
// ⚠ dry run: nothing written
|
||||||
|
// <nil>
|
||||||
|
// true
|
||||||
```
|
```
|
||||||
|
|
||||||
## API reference
|
## API reference
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ package bonfire_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -160,3 +162,68 @@ func ExampleCheckDocs() {
|
|||||||
}
|
}
|
||||||
// Output: blog:reindex: missing long help, examples, option --batch description
|
// Output: blog:reindex: missing long help, examples, option --batch description
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// importPostsCommand is the blog:import command of the acme binary.
|
||||||
|
func importPostsCommand() bonfire.Command {
|
||||||
|
return bonfire.Command{
|
||||||
|
Name: "blog:import",
|
||||||
|
Description: "Import posts from a feed",
|
||||||
|
Args: []bonfire.Arg{{Name: "url", Description: "Feed URL", Required: true}},
|
||||||
|
Flags: []bonfire.Flag{
|
||||||
|
{Name: "dry-run", Description: "Report without writing", Bare: true},
|
||||||
|
{Name: "tag", Description: "Tag to apply (repeatable)", Repeatable: true},
|
||||||
|
},
|
||||||
|
Run: func(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
|
||||||
|
url, _ := in.Argument("url")
|
||||||
|
dryRun := bonfire.FlagBool(in, "dry-run")
|
||||||
|
return out.Spinner("Importing "+url, func() error {
|
||||||
|
out.Table([]string{"Tag"}, [][]string{{"news"}})
|
||||||
|
if dryRun {
|
||||||
|
out.Warning("dry run: nothing written")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// acmeMain is the body of the acme binary's main function, which calls
|
||||||
|
// os.Exit(acmeMain(os.Args[1:], os.Stdout, os.Stderr)).
|
||||||
|
func acmeMain(args []string, stdout, stderr io.Writer) int {
|
||||||
|
g := bonfire.PeekGlobals(args)
|
||||||
|
root, err := bonfire.NewRoot("acme", []bonfire.Command{importPostsCommand()}, stdout,
|
||||||
|
bonfire.WithVersion(bonfire.BuildVersion()))
|
||||||
|
if err != nil {
|
||||||
|
return bonfire.Fail(stderr, "acme", err, g)
|
||||||
|
}
|
||||||
|
return bonfire.Execute(context.Background(), root, args)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleExecute() {
|
||||||
|
code := acmeMain([]string{"blog:import", "--dry-run", "https://example.com/feed"}, os.Stdout, os.Stdout)
|
||||||
|
fmt.Println("exit code:", code)
|
||||||
|
// Output:
|
||||||
|
// [...] Importing https://example.com/feed
|
||||||
|
// Tag
|
||||||
|
// news
|
||||||
|
// ⚠ dry run: nothing written
|
||||||
|
// exit code: 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleCatalog_Has() {
|
||||||
|
ctx := context.Background()
|
||||||
|
catalog := bonfire.NewCatalog([]bonfire.Command{importPostsCommand()})
|
||||||
|
if catalog.Has("blog:import") {
|
||||||
|
err := catalog.Call(ctx, "blog:import", []string{"--dry-run", "https://example.com/feed"}, os.Stdout)
|
||||||
|
fmt.Println(err)
|
||||||
|
}
|
||||||
|
err := catalog.Call(ctx, "blog:export", nil, os.Stdout)
|
||||||
|
fmt.Println(errors.Is(err, bonfire.ErrUnknownCommand)) // not registered in this binary
|
||||||
|
// Output:
|
||||||
|
// [...] Importing https://example.com/feed
|
||||||
|
// Tag
|
||||||
|
// news
|
||||||
|
// ⚠ dry run: nothing written
|
||||||
|
// <nil>
|
||||||
|
// true
|
||||||
|
}
|
||||||
|
|||||||
@@ -39,64 +39,56 @@ Use cases:
|
|||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
```go
|
```go src=modules/bouncer/example_test.go#users
|
||||||
package blog
|
// users loads the principal behind a token subject.
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
|
||||||
)
|
|
||||||
|
|
||||||
type users struct{}
|
type users struct{}
|
||||||
|
```
|
||||||
|
|
||||||
|
```go src=modules/bouncer/example_test.go#users.FindByID
|
||||||
// FindByID loads the user behind a token subject; nil means "not found".
|
// FindByID loads the user behind a token subject; nil means "not found".
|
||||||
func (users) FindByID(ctx context.Context, id uint) (*bouncer.Principal, error) {
|
func (users) FindByID(ctx context.Context, id uint) (*bouncer.Principal, error) {
|
||||||
return &bouncer.Principal{ID: id, PreferredLocale: "en"}, nil
|
return &bouncer.Principal{ID: id, PreferredLocale: "pl"}, nil
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
func Routes(secret string) (http.Handler, error) {
|
```go src=modules/bouncer/example_test.go#ExampleNewJWTGuard
|
||||||
guards := bouncer.NewRegistry()
|
guards := bouncer.NewRegistry()
|
||||||
guard := bouncer.NewJWTGuard(secret, users{}, bouncer.NewMemoryBlacklist(), "token")
|
guard := bouncer.NewJWTGuard(testSecret, users{}, bouncer.NewMemoryBlacklist(), "token")
|
||||||
if err := guards.Register("acme.blog", "jwt", guard); err != nil {
|
if err := guards.Register("acme.blog", "acme.auth", guard); err != nil {
|
||||||
return nil, err
|
fmt.Println(err)
|
||||||
}
|
return
|
||||||
auth, err := guards.Middleware("jwt")
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
|
||||||
mux.Handle("GET /api/me", auth(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
user, _ := bouncer.User(r.Context())
|
|
||||||
fmt.Fprintf(w, "user %d", user.ID)
|
|
||||||
})))
|
|
||||||
return mux, nil
|
|
||||||
}
|
}
|
||||||
|
auth, err := guards.Middleware("acme.auth")
|
||||||
func Login(secret string) (string, error) {
|
if err != nil {
|
||||||
token, _, err := bouncer.Mint(secret, "42", "https://example.com/api/login", time.Hour)
|
fmt.Println(err)
|
||||||
return token, err
|
return
|
||||||
}
|
}
|
||||||
|
me := auth(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user, _ := bouncer.User(r.Context())
|
||||||
|
fmt.Fprintf(w, "user %d, locale %s", user.ID, user.PreferredLocale)
|
||||||
|
}))
|
||||||
|
|
||||||
|
token, _, _ := bouncer.Mint(testSecret, "42", "http://127.0.0.1:8080/api/login", time.Hour)
|
||||||
|
for _, set := range []func(*http.Request){
|
||||||
|
func(r *http.Request) {},
|
||||||
|
func(r *http.Request) { r.Header.Set("Authorization", "Bearer "+token) },
|
||||||
|
func(r *http.Request) { r.AddCookie(&http.Cookie{Name: "token", Value: token}) },
|
||||||
|
} {
|
||||||
|
req := httptest.NewRequest("GET", "/api/me", nil)
|
||||||
|
set(req)
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
me.ServeHTTP(rec, req)
|
||||||
|
fmt.Println(rec.Code, strings.TrimSpace(rec.Body.String()))
|
||||||
|
}
|
||||||
|
// Output:
|
||||||
|
// 401 {"error":true,"message":"Token not provided"}
|
||||||
|
// 200 user 42, locale pl
|
||||||
|
// 200 user 42, locale pl
|
||||||
```
|
```
|
||||||
|
|
||||||
An application that keeps the token in an httpOnly cookie, for a frontend on `www.example.com` calling the API on `api.example.com`, loads the cookie config at boot and mounts the refresh handler on a POST route:
|
An application that keeps the token in an httpOnly cookie, for a frontend on `www.example.com` calling the API on `api.example.com`, loads the cookie config at boot and mounts the refresh handler on a POST route:
|
||||||
|
|
||||||
```go
|
```go src=modules/bouncer/example_test.go#RefreshRoute
|
||||||
package acme
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
|
||||||
)
|
|
||||||
|
|
||||||
// RefreshRoute rotates the cookie's token. cfg is the app config
|
// RefreshRoute rotates the cookie's token. cfg is the app config
|
||||||
// (app.Config); users, secret and bl are the guard's; refreshTTL is its
|
// (app.Config); users, secret and bl are the guard's; refreshTTL is its
|
||||||
// refresh_ttl.
|
// refresh_ttl.
|
||||||
|
|||||||
@@ -2,13 +2,16 @@ package bouncer_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"strings"
|
"strings"
|
||||||
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/compass"
|
||||||
)
|
)
|
||||||
|
|
||||||
// testSecret is a test-only signing secret. A real application reads its
|
// testSecret is a test-only signing secret. A real application reads its
|
||||||
@@ -49,6 +52,7 @@ func ExampleMint() {
|
|||||||
// users loads the principal behind a token subject.
|
// users loads the principal behind a token subject.
|
||||||
type users struct{}
|
type users struct{}
|
||||||
|
|
||||||
|
// FindByID loads the user behind a token subject; nil means "not found".
|
||||||
func (users) FindByID(ctx context.Context, id uint) (*bouncer.Principal, error) {
|
func (users) FindByID(ctx context.Context, id uint) (*bouncer.Principal, error) {
|
||||||
return &bouncer.Principal{ID: id, PreferredLocale: "pl"}, nil
|
return &bouncer.Principal{ID: id, PreferredLocale: "pl"}, nil
|
||||||
}
|
}
|
||||||
@@ -103,3 +107,89 @@ func ExampleHashPassword() {
|
|||||||
// false
|
// false
|
||||||
// true
|
// true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RefreshRoute rotates the cookie's token. cfg is the app config
|
||||||
|
// (app.Config); users, secret and bl are the guard's; refreshTTL is its
|
||||||
|
// refresh_ttl.
|
||||||
|
func RefreshRoute(cfg bouncer.CookieConfigSource, users bouncer.UserProvider, secret string, bl bouncer.BlacklistStore, refreshTTL time.Duration) (http.Handler, error) {
|
||||||
|
cookie, err := bouncer.LoadCookieConfig(cfg) // a bad auth.cookie block fails boot
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return bouncer.CookieRefreshHandler(bouncer.CookieRefreshOptions{
|
||||||
|
Cookie: cookie,
|
||||||
|
RefreshTTL: refreshTTL,
|
||||||
|
Refresh: func(ctx context.Context, token string) (string, error) {
|
||||||
|
return bouncer.RefreshAudienceFor(ctx, users, secret, token, bouncer.AudienceUser, refreshTTL, bl, 0, "https://api.example.com/api/auth/refresh")
|
||||||
|
},
|
||||||
|
Write: func(w http.ResponseWriter, r *http.Request, res bouncer.CookieResult) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(res.Status)
|
||||||
|
if res.Err != nil {
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"success": false, "error": "UNAUTHENTICATED"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"success": true})
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestDocsRefreshRoute runs RefreshRoute on a production config for a
|
||||||
|
// frontend on www.example.com and an API on api.example.com: the cookie
|
||||||
|
// rotates once, and the replaced token is refused.
|
||||||
|
func TestDocsRefreshRoute(t *testing.T) {
|
||||||
|
cfg, err := compass.Open(compass.Options{Dir: t.TempDir(), Env: "production", Environ: []string{}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for k, v := range map[string]any{"app.url": "https://api.example.com", "auth.cookie.domain": "example.com"} {
|
||||||
|
if err := cfg.Set(k, v); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
refreshTTL := 14 * 24 * time.Hour
|
||||||
|
h, err := RefreshRoute(cfg, users{}, testSecret, bouncer.NewMemoryBlacklist(), refreshTTL)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
token, _, err := bouncer.Mint(testSecret, "42", "https://api.example.com/api/auth/login", time.Hour)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
refresh := func(token string) *httptest.ResponseRecorder {
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "https://api.example.com/api/auth/refresh", nil)
|
||||||
|
req.AddCookie(&http.Cookie{Name: bouncer.DefaultCookieName, Value: token})
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec, req)
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
|
||||||
|
rec := refresh(token)
|
||||||
|
if rec.Code != http.StatusOK || strings.TrimSpace(rec.Body.String()) != `{"success":true}` {
|
||||||
|
t.Fatalf("refresh = %d %s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
cookies := rec.Result().Cookies()
|
||||||
|
if len(cookies) != 1 {
|
||||||
|
t.Fatalf("cookies = %v", cookies)
|
||||||
|
}
|
||||||
|
c := cookies[0]
|
||||||
|
if c.Name != bouncer.DefaultCookieName || c.Value == "" || c.Value == token || c.Domain != "example.com" ||
|
||||||
|
!c.Secure || !c.HttpOnly || c.SameSite != http.SameSiteLaxMode || c.MaxAge != int(refreshTTL.Seconds()) {
|
||||||
|
t.Fatalf("cookie = %+v", c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The old token was blacklisted by the rotation.
|
||||||
|
if rec := refresh(token); rec.Code != http.StatusUnauthorized ||
|
||||||
|
strings.TrimSpace(rec.Body.String()) != `{"error":"UNAUTHENTICATED","success":false}` || len(rec.Result().Cookies()) != 0 {
|
||||||
|
t.Fatalf("second refresh = %d %s %v", rec.Code, rec.Body, rec.Result().Cookies())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestDocsDeclarations checks the user provider the README shows.
|
||||||
|
func TestDocsDeclarations(t *testing.T) {
|
||||||
|
var _ bouncer.UserProvider = users{}
|
||||||
|
user, err := users{}.FindByID(t.Context(), 42)
|
||||||
|
if err != nil || user == nil || user.ID != 42 || user.PreferredLocale != "pl" {
|
||||||
|
t.Fatalf("FindByID = %+v, %v", user, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user