go-guess/backend/internal/web/middleware/GoLooseMiddleware.go
Daniel Noulet 5449cd3d8d feat: avatar, account menu, and single sign-on from Go Loose
Signing in now starts at the sign-in screen and one button that hands the
browser to Go Loose, which returns to the welcome page. Nothing redirects to the
identity provider on its own any more: that fired on every anonymous visit and
read as a redirect loop rather than as a choice to sign in. The password form
remains only where the API reports that Go Loose login is not configured for the
host, because otherwise the application is unreachable on a bare localhost.

A person's picture is carried through from the Go Loose identity and rendered in
the account menu and on the profile page, with their initials as the fallback.
Two things make that fallback necessary rather than decorative: Go Loose retires a
picture key when a picture is replaced, so a link cached in a browser can be dead,
and most people have not uploaded one. The URL is deliberately not persisted
locally, since a stored key would keep failing after the picture changed.

The account menu is a disclosure rather than a hover menu: a real button with
aria-expanded, Escape and outside clicks closing it, and focus returning to the
trigger. It is not an ARIA menu, because its actions are a link and a button and
menuitem roles would strip the link semantics from one of them for no gain.

The account URL of the Go Loose identity is resolved on each sign-in and is read
from the live identity provider every time, which is also what makes it correct
after a picture change.

Depends on the Go Loose revision that serves avatar_url through
/connect/userinfo, so the picture URL reaches this application at all.
2026-10-05 21:50:06 +02:00

107 lines
2.9 KiB
Go

package middleware
import (
"encoding/json"
"fmt"
"log/slog"
"net/http"
"os"
"regexp"
"strings"
"sync"
"time"
"github.com/danyel/go-guess/backend/internal/config"
"github.com/danyel/go-loose/client"
)
const guessApplication = "guess"
// defaultBaseURLPattern is the Go Loose identity domain used when
// GO_LOOSE_BASE_URL is unset.
func defaultBaseURLPattern() string {
return "https://%s." + config.DefaultAuthDomain
}
// A tenant used in the Go Loose host must be one DNS label.
var safeTenantLabel = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,62})?$`)
// GoLooseMiddleware authorizes a request with Go Loose. The tenant is taken
// from the X-Tenant-Id header, not from process configuration.
//
// GO_LOOSE_BASE_URL may contain one %s placeholder for that tenant. The
// default is the development identity domain, https://%s.auth-dev.urpi.be.
// A URL without %s is used as-is.
func GoLooseMiddleware() func(http.Handler) http.Handler {
pattern := os.Getenv("GO_LOOSE_BASE_URL")
if pattern == "" {
pattern = defaultBaseURLPattern()
}
httpClient := &http.Client{Timeout: 2 * time.Second}
var (
mu sync.Mutex
clients = map[string]*client.Client{}
)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tenantID := strings.TrimSpace(r.Header.Get(client.XTenantId))
if tenantID == "" {
writeGoLooseError(w, http.StatusBadRequest, "Missing X-Tenant-Id header")
return
}
baseURL, err := goLooseBaseURL(pattern, tenantID)
if err != nil {
writeGoLooseError(w, http.StatusBadRequest, "Invalid characters in tenant ID")
return
}
access, err := goLooseClient(&mu, clients, httpClient, baseURL, tenantID)
if err != nil {
slog.Error("configure go-loose client", "error", err)
writeGoLooseError(w, http.StatusInternalServerError, "authorization unavailable")
return
}
access.Middleware(next).ServeHTTP(w, r)
})
}
}
func goLooseBaseURL(pattern, tenantID string) (string, error) {
if !strings.Contains(pattern, "%s") {
return pattern, nil
}
if !safeTenantLabel.MatchString(tenantID) {
return "", fmt.Errorf("invalid tenant %q", tenantID)
}
return fmt.Sprintf(pattern, tenantID), nil
}
func goLooseClient(
mu *sync.Mutex,
clients map[string]*client.Client,
httpClient *http.Client,
baseURL, tenantID string,
) (*client.Client, error) {
key := tenantID + "\x00" + baseURL
mu.Lock()
defer mu.Unlock()
if existing, ok := clients[key]; ok {
return existing, nil
}
created, err := client.New(client.Config{
BaseURL: baseURL,
Tenant: tenantID,
Application: guessApplication,
HTTPClient: httpClient,
})
if err != nil {
return nil, err
}
clients[key] = created
return created, nil
}
func writeGoLooseError(w http.ResponseWriter, status int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]string{"error": message})
}