feat: multi-tenancy, login, per-org SSO and i18n (M2) #46
No files matched your search
@@ -5,3 +5,11 @@ UPTIME_CHECKER_REGION=local
|
||||
# Sentinel instead of a single redis (docker compose --profile sentinel up -d)
|
||||
# UPTIME_REDIS_SENTINEL_MASTER=uptime
|
||||
# UPTIME_REDIS_SENTINEL_ADDRS=127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381
|
||||
|
||||
# Generate with: echo "k1:$(head -c32 /dev/urandom | base64)"
|
||||
UPTIME_SECRET_KEYS=dev:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
|
||||
|
||||
UPTIME_PUBLIC_URL=http://localhost:8080
|
||||
# Lets organizations use IdPs on private networks (e.g. an internal Keycloak).
|
||||
# auto = allowed for UPTIME_EDITION=selfhosted, denied for cloud.
|
||||
UPTIME_SSO_ALLOW_PRIVATE_NETWORKS=auto
|
||||
@@ -0,0 +1,48 @@
|
||||
version: "2"
|
||||
|
||||
run:
|
||||
tests: true
|
||||
|
||||
linters:
|
||||
# staticcheck and unused are left out until honnef.co/go/tools supports
|
||||
# the Go 1.27 standard library; they panic during analysis otherwise.
|
||||
default: none
|
||||
enable:
|
||||
- errcheck
|
||||
- govet
|
||||
- ineffassign
|
||||
- revive
|
||||
- errorlint
|
||||
- gocritic
|
||||
- misspell
|
||||
- unconvert
|
||||
- usestdlibvars
|
||||
settings:
|
||||
revive:
|
||||
rules:
|
||||
- name: exported
|
||||
arguments: [checkPrivateReceivers, sayRepetitiveInsteadOfStutters]
|
||||
- name: package-comments
|
||||
- name: var-naming
|
||||
- name: receiver-naming
|
||||
- name: error-strings
|
||||
- name: error-naming
|
||||
- name: indent-error-flow
|
||||
- name: context-as-argument
|
||||
- name: unexported-return
|
||||
- name: blank-imports
|
||||
exclusions:
|
||||
generated: strict
|
||||
rules:
|
||||
- path: _test\.go
|
||||
linters: [revive]
|
||||
text: "exported"
|
||||
|
||||
formatters:
|
||||
enable:
|
||||
- gofmt
|
||||
- goimports
|
||||
settings:
|
||||
goimports:
|
||||
local-prefixes:
|
||||
- git.zb-server.de/ZB-Server/uptimesebi
|
||||
+25
-8
@@ -1,35 +1,40 @@
|
||||
// Command api serves the management API and console. It also owns schema
|
||||
// migrations: run "api migrate up" before rolling out a new release.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/api"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/migrations"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/platform"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/sealed"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log := platform.NewLogger("api")
|
||||
if err := run(log, os.Args[1:]); err != nil {
|
||||
log, level := platform.NewLogger("api")
|
||||
// Route the standard log package and dependencies through the same handler.
|
||||
slog.SetDefault(log)
|
||||
if err := run(log, level, os.Args[1:]); err != nil {
|
||||
log.Error("exit", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(log *slog.Logger, args []string) error {
|
||||
func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
|
||||
cfg, err := config.Load[config.API]()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
platform.SetLogLevel(cfg.LogLevel)
|
||||
level.Set(cfg.LogLevel)
|
||||
ctx, stop := platform.SignalContext()
|
||||
defer stop()
|
||||
|
||||
@@ -40,17 +45,29 @@ func run(log *slog.Logger, args []string) error {
|
||||
return errors.New("usage: api [serve | migrate up|down|status]")
|
||||
}
|
||||
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
keys, err := sealed.Parse(cfg.SecretKeys)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
deps, err := platform.Connect(ctx, cfg.Common, log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer deps.Close()
|
||||
|
||||
catalog, err := i18n.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
srv := api.New(cfg, api.Deps{Log: log, DB: tenant.New(deps.DB), Redis: deps.Redis, Keys: keys, Catalog: catalog})
|
||||
health := platform.NewHealth(deps.Probes())
|
||||
r := platform.NewRouter(log)
|
||||
health.Register(r)
|
||||
r.StaticFS("/static", web.Static())
|
||||
r.GET("/", func(c *gin.Context) { web.Render(c, http.StatusOK, web.Index()) })
|
||||
srv.Mount(r)
|
||||
|
||||
return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout)
|
||||
}
|
||||
|
||||
+8
-4
@@ -1,3 +1,5 @@
|
||||
// Command checker executes uptime checks for one region and pulls data from
|
||||
// external sources. Any number of instances per region may run.
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -9,19 +11,21 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
log := platform.NewLogger("checker")
|
||||
if err := run(log); err != nil {
|
||||
log, level := platform.NewLogger("checker")
|
||||
// Route the standard log package and dependencies through the same handler.
|
||||
slog.SetDefault(log)
|
||||
if err := run(log, level); err != nil {
|
||||
log.Error("exit", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(log *slog.Logger) error {
|
||||
func run(log *slog.Logger, level *slog.LevelVar) error {
|
||||
cfg, err := config.Load[config.Checker]()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
platform.SetLogLevel(cfg.LogLevel)
|
||||
level.Set(cfg.LogLevel)
|
||||
ctx, stop := platform.SignalContext()
|
||||
defer stop()
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// Command statuspage serves public status pages, including on customer
|
||||
// domains.
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -11,19 +13,21 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
log := platform.NewLogger("statuspage")
|
||||
if err := run(log); err != nil {
|
||||
log, level := platform.NewLogger("statuspage")
|
||||
// Route the standard log package and dependencies through the same handler.
|
||||
slog.SetDefault(log)
|
||||
if err := run(log, level); err != nil {
|
||||
log.Error("exit", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(log *slog.Logger) error {
|
||||
func run(log *slog.Logger, level *slog.LevelVar) error {
|
||||
cfg, err := config.Load[config.StatusPage]()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
platform.SetLogLevel(cfg.LogLevel)
|
||||
level.Set(cfg.LogLevel)
|
||||
ctx, stop := platform.SignalContext()
|
||||
defer stop()
|
||||
|
||||
|
||||
+5
-5
@@ -4,13 +4,13 @@ services:
|
||||
timescaledb:
|
||||
image: timescale/timescaledb:2.30.1-pg16
|
||||
environment:
|
||||
POSTGRES_USER: uptime
|
||||
POSTGRES_PASSWORD: uptime
|
||||
POSTGRES_DB: uptime
|
||||
POSTGRES_PASSWORD: postgres
|
||||
ports: ["5432:5432"]
|
||||
volumes: [pgdata:/var/lib/postgresql/data]
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
- ./deploy/dev/postgres-init.sql:/docker-entrypoint-initdb.d/10-uptime.sql:ro
|
||||
healthcheck:
|
||||
test: ["CMD", "pg_isready", "-U", "uptime"]
|
||||
test: ["CMD", "pg_isready", "-U", "uptime", "-d", "uptime"]
|
||||
interval: 2s
|
||||
retries: 30
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Superusers bypass row-level security even with FORCE, so the application
|
||||
-- must connect as an ordinary role for tenant isolation to be enforced.
|
||||
CREATE ROLE uptime LOGIN PASSWORD 'uptime';
|
||||
CREATE DATABASE uptime OWNER uptime;
|
||||
\connect uptime
|
||||
CREATE EXTENSION IF NOT EXISTS timescaledb;
|
||||
CREATE EXTENSION IF NOT EXISTS citext;
|
||||
@@ -5,16 +5,25 @@ go 1.27.1
|
||||
require (
|
||||
github.com/a-h/templ v0.3.1118
|
||||
github.com/caarlos0/env/v11 v11.4.2
|
||||
github.com/coreos/go-oidc/v3 v3.21.0
|
||||
github.com/gin-gonic/gin v1.12.0
|
||||
github.com/go-jose/go-jose/v4 v4.1.4
|
||||
github.com/go-playground/validator/v10 v10.30.6
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.13.0
|
||||
github.com/nicksnyder/go-i18n/v2 v2.7.0
|
||||
github.com/pquerna/otp v1.5.0
|
||||
github.com/pressly/goose/v3 v3.30.1
|
||||
github.com/redis/go-redis/v9 v9.23.0
|
||||
golang.org/x/crypto v0.59.0
|
||||
golang.org/x/oauth2 v0.38.0
|
||||
golang.org/x/text v0.44.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/a-h/parse v0.0.42 // indirect
|
||||
github.com/andybalholm/brotli v1.3.0 // indirect
|
||||
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect
|
||||
github.com/bytedance/gopkg v0.1.3 // indirect
|
||||
github.com/bytedance/sonic v1.15.0 // indirect
|
||||
github.com/bytedance/sonic/loader v0.5.0 // indirect
|
||||
@@ -24,11 +33,10 @@ require (
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
github.com/fatih/color v1.19.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.10.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.16 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.30.1 // indirect
|
||||
github.com/go-playground/locales v0.14.2 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.2 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/goccy/go-yaml v1.19.2 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
@@ -36,7 +44,7 @@ require (
|
||||
github.com/jackc/puddle/v2 v2.2.3 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/leodido/go-urn v1.5.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.16 // indirect
|
||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||
github.com/mfridman/interpolate v0.2.0 // indirect
|
||||
@@ -53,12 +61,10 @@ require (
|
||||
go.uber.org/atomic v1.12.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
golang.org/x/arch v0.22.0 // indirect
|
||||
golang.org/x/crypto v0.58.0 // indirect
|
||||
golang.org/x/mod v0.43.0 // indirect
|
||||
golang.org/x/net v0.62.0 // indirect
|
||||
golang.org/x/sync v0.25.0 // indirect
|
||||
golang.org/x/sys v0.50.0 // indirect
|
||||
golang.org/x/text v0.44.0 // indirect
|
||||
golang.org/x/tools v0.52.0 // indirect
|
||||
google.golang.org/protobuf v1.36.12 // indirect
|
||||
)
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
|
||||
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/a-h/parse v0.0.42 h1:OUb8soeTG5+mRWieRyS/OyNU7Xl0+4wr4kPKKPa/WUQ=
|
||||
github.com/a-h/parse v0.0.42/go.mod h1:X9OHJ1IjgakwZoDSoHYhdtKKD0zXZ2agpoIztPAA95w=
|
||||
github.com/a-h/templ v0.3.1118 h1:rZv90g1xVb7ieNz4j5WK6yQePZfsg7j7fVvP8qVmeJI=
|
||||
github.com/a-h/templ v0.3.1118/go.mod h1:ttKggixbDULrwkJzfEO5fa4IPGTKiRt3qP09zjPuCS4=
|
||||
github.com/andybalholm/brotli v1.3.0 h1:IdkhjSe/+34U+fP7FSR2Q6Poj1hnHUa2GoWmzXJd6qY=
|
||||
github.com/andybalholm/brotli v1.3.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI=
|
||||
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
@@ -24,6 +28,8 @@ github.com/cli/browser v1.3.0 h1:LejqCrpWr+1pRqmEPDGnTZOjsMe7sehifLynZJuqJpo=
|
||||
github.com/cli/browser v1.3.0/go.mod h1:HH8s+fOAxjhQoBUAsKuPCbqUuxZDhQ2/aD+SzsEfBTk=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM=
|
||||
github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
@@ -33,20 +39,22 @@ github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
|
||||
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
|
||||
github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
|
||||
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E=
|
||||
github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4=
|
||||
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
||||
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
|
||||
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
|
||||
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
|
||||
github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY=
|
||||
github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU=
|
||||
github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk=
|
||||
github.com/go-playground/validator/v10 v10.30.6 h1:E+mymlPNRzAMNz1FShrRvLeGWcprF5w305eLLgWieuo=
|
||||
github.com/go-playground/validator/v10 v10.30.6/go.mod h1:jPLL8SKCXGe/g87QmEyNw3NO28nmGt5GCnZnufm7rj4=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
|
||||
@@ -68,8 +76,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
|
||||
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
|
||||
github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiAt84A=
|
||||
github.com/mattn/go-colorable v0.1.16/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||
@@ -85,9 +93,13 @@ github.com/natefinch/atomic v1.0.1 h1:ZPYKxkqQOx3KZ+RsbnP/YsgvxWQPGxjC0oBt2AhwV0
|
||||
github.com/natefinch/atomic v1.0.1/go.mod h1:N/D/ELrljoqDyT3rZrsUmtsuzvHkeB/wWjHV22AZRbM=
|
||||
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
|
||||
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
|
||||
github.com/nicksnyder/go-i18n/v2 v2.7.0 h1:oiVQUmuCeNggvm/fUVb6/R0aP82BDVphZnmVHwut+J0=
|
||||
github.com/nicksnyder/go-i18n/v2 v2.7.0/go.mod h1:ZMYiWg8ndQSGNk4zbzbyJjrrVjQjuQ8pERFrnBik+c8=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pquerna/otp v1.5.0 h1:NMMR+WrmaqXU4EzdGJEE1aUUI0AMRzsp96fFFWNPwxs=
|
||||
github.com/pquerna/otp v1.5.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg=
|
||||
github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE=
|
||||
github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
@@ -132,12 +144,14 @@ go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
|
||||
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
|
||||
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
|
||||
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
||||
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
||||
golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg=
|
||||
golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY=
|
||||
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
|
||||
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
golang.org/x/oauth2 v0.38.0 h1:uW7XQbcu1eoiQS7uMJvLOjPMl04bTbmY1VeRPxvbspI=
|
||||
golang.org/x/oauth2 v0.38.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
|
||||
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
const (
|
||||
mfaCookie = "__Host-mfa"
|
||||
mfaTTL = 5 * time.Minute
|
||||
)
|
||||
|
||||
type signupRequest struct {
|
||||
Email string `json:"email" binding:"required,email,max=320"`
|
||||
Password string `json:"password" binding:"required,max=1024"`
|
||||
DisplayName string `json:"display_name" binding:"max=200"`
|
||||
OrgName string `json:"org_name" binding:"required,max=200"`
|
||||
OrgSlug string `json:"org_slug" binding:"required,max=63"`
|
||||
}
|
||||
|
||||
func (s *Server) signup(c *gin.Context) {
|
||||
var req signupRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
if !s.limit(c, "signup:"+c.ClientIP(), 10, time.Hour) {
|
||||
return
|
||||
}
|
||||
if allowed, err := s.signupAllowed(ctx); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
} else if !allowed {
|
||||
fail(c, http.StatusForbidden, "signup_closed")
|
||||
return
|
||||
}
|
||||
hash, err := auth.HashPassword(req.Password)
|
||||
if errors.Is(err, auth.ErrPasswordTooShort) {
|
||||
fail(c, http.StatusUnprocessableEntity, "password_too_short", "Min", auth.MinPasswordLength)
|
||||
return
|
||||
} else if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
orgID := uuid.New()
|
||||
var user store.User
|
||||
err = s.db.Tx(ctx, tenant.Org(orgID, uuid.Nil), func(q *store.Queries) error {
|
||||
var err error
|
||||
user, err = q.CreateUser(ctx, store.CreateUserParams{
|
||||
Email: normalizeEmail(req.Email),
|
||||
DisplayName: strings.TrimSpace(req.DisplayName),
|
||||
PasswordHash: &hash,
|
||||
Locale: ptr(i18n.Lang(ctx)),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: orgID, Slug: strings.ToLower(req.OrgSlug), Name: strings.TrimSpace(req.OrgName)}); err != nil {
|
||||
return err
|
||||
}
|
||||
return q.AddMembership(ctx, store.AddMembershipParams{OrgID: orgID, UserID: user.ID, IsOwner: true})
|
||||
})
|
||||
switch {
|
||||
case isUniqueViolation(err, "users_email_key"):
|
||||
fail(c, http.StatusConflict, "email_taken")
|
||||
return
|
||||
case isUniqueViolation(err, "orgs_slug_key"):
|
||||
fail(c, http.StatusConflict, "slug_taken")
|
||||
return
|
||||
case isCheckViolation(err):
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_slug")
|
||||
return
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
s.startSession(c, user.ID, orgID, i18n.Lang(ctx))
|
||||
}
|
||||
|
||||
func (s *Server) signupAllowed(ctx context.Context) (bool, error) {
|
||||
switch s.cfg.Signup {
|
||||
case config.SignupOpen:
|
||||
return true, nil
|
||||
case config.SignupFirstUser:
|
||||
var exists bool
|
||||
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
var err error
|
||||
exists, err = q.AnyUserExists(ctx)
|
||||
return err
|
||||
})
|
||||
return !exists, err
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
type loginRequest struct {
|
||||
Email string `json:"email" binding:"required,max=320"`
|
||||
Password string `json:"password" binding:"required,max=1024"`
|
||||
}
|
||||
|
||||
func (s *Server) login(c *gin.Context) {
|
||||
var req loginRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
email := normalizeEmail(req.Email)
|
||||
if !s.limit(c, "login:ip:"+c.ClientIP(), 30, 15*time.Minute) || !s.limit(c, "login:email:"+email, 10, 15*time.Minute) {
|
||||
return
|
||||
}
|
||||
|
||||
var user store.User
|
||||
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
var err error
|
||||
user, err = q.GetUserByEmail(ctx, email)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && user.PasswordHash == nil) {
|
||||
auth.BurnPasswordCheck(req.Password)
|
||||
invalidCredentials(c)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
ok, rehash, err := auth.VerifyPassword(*user.PasswordHash, req.Password)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !ok || user.DisabledAt != nil {
|
||||
invalidCredentials(c)
|
||||
return
|
||||
}
|
||||
if rehash {
|
||||
s.rehashPassword(ctx, user.ID, req.Password)
|
||||
}
|
||||
|
||||
if user.TotpSecret != nil {
|
||||
token := auth.RandomToken()
|
||||
if err := s.rdb.Set(ctx, mfaKey(token), user.ID.String(), mfaTTL).Err(); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
setCookie(c, mfaCookie, token, int(mfaTTL.Seconds()))
|
||||
c.JSON(http.StatusOK, gin.H{"status": "totp_required"})
|
||||
return
|
||||
}
|
||||
s.finishLogin(c, user.ID)
|
||||
}
|
||||
|
||||
// secondFactorRequest carries a TOTP code or a recovery code.
|
||||
type secondFactorRequest struct {
|
||||
Code string `json:"code" binding:"required,max=32"`
|
||||
}
|
||||
|
||||
type totpRequest struct {
|
||||
Code string `json:"code" binding:"required,len=6,numeric"`
|
||||
}
|
||||
|
||||
func (s *Server) loginTOTP(c *gin.Context) {
|
||||
var req secondFactorRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
token, _ := c.Cookie(mfaCookie)
|
||||
if token == "" {
|
||||
fail(c, http.StatusUnauthorized, "mfa_expired")
|
||||
return
|
||||
}
|
||||
if !s.limit(c, "mfa:"+mfaKey(token), 5, mfaTTL) {
|
||||
return
|
||||
}
|
||||
raw, err := s.rdb.Get(ctx, mfaKey(token)).Result()
|
||||
if err != nil {
|
||||
fail(c, http.StatusUnauthorized, "mfa_expired")
|
||||
return
|
||||
}
|
||||
userID, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
ok, err := s.verifySecondFactor(ctx, userID, req.Code)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
fail(c, http.StatusUnauthorized, "invalid_code")
|
||||
return
|
||||
}
|
||||
_ = s.rdb.Del(ctx, mfaKey(token)).Err()
|
||||
setCookie(c, mfaCookie, "", -1)
|
||||
s.finishLogin(c, userID)
|
||||
}
|
||||
|
||||
func (s *Server) finishLogin(c *gin.Context, userID uuid.UUID) {
|
||||
ctx := c.Request.Context()
|
||||
var (
|
||||
user store.User
|
||||
orgs []store.ListUserOrgsRow
|
||||
)
|
||||
err := s.db.Tx(ctx, tenant.User(userID), func(q *store.Queries) error {
|
||||
var err error
|
||||
if user, err = q.GetUser(ctx, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
orgs, err = q.ListUserOrgs(ctx, userID)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
var org uuid.UUID
|
||||
if len(orgs) > 0 {
|
||||
org = orgs[0].ID
|
||||
}
|
||||
s.startSession(c, userID, org, deref(user.Locale))
|
||||
}
|
||||
|
||||
func (s *Server) startSession(c *gin.Context, userID, orgID uuid.UUID, locale string) {
|
||||
if old := auth.Current(c); old != nil {
|
||||
_ = s.sessions.Delete(c.Request.Context(), old)
|
||||
}
|
||||
sess, err := s.sessions.Create(c.Request.Context(), userID, orgID, locale)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
auth.SetCookie(c, sess, int(s.cfg.SessionAbsolute.Seconds()))
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok", "csrf_token": sess.CSRF})
|
||||
}
|
||||
|
||||
func (s *Server) logout(c *gin.Context) {
|
||||
if sess := auth.Current(c); sess != nil {
|
||||
if err := s.sessions.Delete(c.Request.Context(), sess); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
auth.ClearCookie(c)
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) rehashPassword(ctx context.Context, user uuid.UUID, pw string) {
|
||||
hash, err := auth.HashPassword(pw)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
return q.SetPasswordHash(ctx, store.SetPasswordHashParams{ID: user, PasswordHash: &hash})
|
||||
})
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "password rehash failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) limit(c *gin.Context, key string, n int, window time.Duration) bool {
|
||||
ok, err := s.limiter.Allow(c.Request.Context(), key, n, window)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return false
|
||||
}
|
||||
if !ok {
|
||||
c.Header("Retry-After", "60")
|
||||
fail(c, http.StatusTooManyRequests, "rate_limited")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func mfaKey(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return "login_mfa:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func normalizeEmail(e string) string { return strings.ToLower(strings.TrimSpace(e)) }
|
||||
|
||||
func invalidCredentials(c *gin.Context) {
|
||||
fail(c, http.StatusUnauthorized, "invalid_credentials")
|
||||
}
|
||||
|
||||
func isUniqueViolation(err error, constraint string) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == constraint
|
||||
}
|
||||
|
||||
func isCheckViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23514"
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"image/png"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/pquerna/otp"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
const totpSetupTTL = 10 * time.Minute
|
||||
|
||||
type orgView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Slug string `json:"slug"`
|
||||
Name string `json:"name"`
|
||||
IsOwner bool `json:"is_owner"`
|
||||
RequireTOTP bool `json:"require_totp"`
|
||||
}
|
||||
|
||||
type meView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Email string `json:"email"`
|
||||
DisplayName string `json:"display_name"`
|
||||
TOTP bool `json:"totp_enabled"`
|
||||
ActiveOrg uuid.UUID `json:"active_org"`
|
||||
Orgs []orgView `json:"orgs"`
|
||||
// Set when an org the user belongs to enforces TOTP and the user has none.
|
||||
TOTPEnrollmentRequired bool `json:"totp_enrollment_required"`
|
||||
RecoveryCodesLeft int `json:"recovery_codes_left"`
|
||||
}
|
||||
|
||||
func (s *Server) loadMe(ctx context.Context, sess *auth.Session) (meView, error) {
|
||||
var me meView
|
||||
err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
|
||||
u, err := q.GetUser(ctx, sess.UserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
left, err := q.CountUnusedRecoveryCodes(ctx, sess.UserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
orgs, err := q.ListUserOrgs(ctx, sess.UserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
me = meView{ID: u.ID, Email: u.Email, DisplayName: u.DisplayName, TOTP: u.TotpSecret != nil, ActiveOrg: sess.OrgID, Orgs: []orgView{}, RecoveryCodesLeft: int(left)}
|
||||
for _, o := range orgs {
|
||||
me.Orgs = append(me.Orgs, orgView{ID: o.ID, Slug: o.Slug, Name: o.Name, IsOwner: o.IsOwner, RequireTOTP: o.RequireTotp})
|
||||
if o.RequireTotp && !me.TOTP {
|
||||
me.TOTPEnrollmentRequired = true
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return me, err
|
||||
}
|
||||
|
||||
func (s *Server) me(c *gin.Context) {
|
||||
me, err := s.loadMe(c.Request.Context(), auth.Current(c))
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, me)
|
||||
}
|
||||
|
||||
type switchOrgRequest struct {
|
||||
OrgID uuid.UUID `json:"org_id" binding:"required"`
|
||||
}
|
||||
|
||||
func (s *Server) switchOrg(c *gin.Context) {
|
||||
var req switchOrgRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
sess := auth.Current(c)
|
||||
me, err := s.loadMe(c.Request.Context(), sess)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
for _, o := range me.Orgs {
|
||||
if o.ID == req.OrgID {
|
||||
if err := s.sessions.SwitchOrg(c.Request.Context(), sess, o.ID); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
}
|
||||
fail(c, http.StatusNotFound, "org_not_found")
|
||||
}
|
||||
|
||||
func totpSetupKey(user uuid.UUID) string { return "totp_setup:" + user.String() }
|
||||
|
||||
func (s *Server) totpSetup(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
me, err := s.loadMe(ctx, auth.Current(c))
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if me.TOTP {
|
||||
fail(c, http.StatusConflict, "totp_already_enabled")
|
||||
return
|
||||
}
|
||||
key, err := auth.NewTOTPKey(me.Email)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if err := s.rdb.Set(ctx, totpSetupKey(me.ID), key.Secret(), totpSetupTTL).Err(); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
qr, err := qrDataURI(key)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"secret": key.Secret(), "otpauth_url": key.URL(), "qr": qr})
|
||||
}
|
||||
|
||||
func (s *Server) totpEnable(c *gin.Context) {
|
||||
var req totpRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
sess := auth.Current(c)
|
||||
secret, err := s.rdb.Get(ctx, totpSetupKey(sess.UserID)).Result()
|
||||
if err != nil {
|
||||
fail(c, http.StatusConflict, "totp_setup_expired")
|
||||
return
|
||||
}
|
||||
if !s.limit(c, "totp_enable:"+sess.UserID.String(), 10, totpSetupTTL) {
|
||||
return
|
||||
}
|
||||
ok, err := s.totp.Verify(ctx, sess.UserID, secret, req.Code)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_code")
|
||||
return
|
||||
}
|
||||
sealedSecret := s.keys.Seal([]byte(secret), sess.UserID[:])
|
||||
codes := auth.NewRecoveryCodes()
|
||||
err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
|
||||
if err := q.EnableTOTP(ctx, store.EnableTOTPParams{ID: sess.UserID, TotpSecret: sealedSecret}); err != nil {
|
||||
return err
|
||||
}
|
||||
return replaceRecoveryCodes(ctx, q, sess.UserID, codes)
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
_ = s.rdb.Del(ctx, totpSetupKey(sess.UserID)).Err()
|
||||
c.JSON(http.StatusOK, gin.H{"recovery_codes": codes})
|
||||
}
|
||||
|
||||
func replaceRecoveryCodes(ctx context.Context, q *store.Queries, user uuid.UUID, codes []string) error {
|
||||
if err := q.DeleteRecoveryCodes(ctx, user); err != nil {
|
||||
return err
|
||||
}
|
||||
rows := make([]store.InsertRecoveryCodesParams, len(codes))
|
||||
for i, c := range codes {
|
||||
rows[i] = store.InsertRecoveryCodesParams{UserID: user, CodeHash: auth.HashRecoveryCode(auth.NormalizeRecoveryCode(c))}
|
||||
}
|
||||
_, err := q.InsertRecoveryCodes(ctx, rows)
|
||||
return err
|
||||
}
|
||||
|
||||
// reauthRequest confirms a sensitive change with the password and a second
|
||||
// factor, so a hijacked session alone cannot weaken the account.
|
||||
type reauthRequest struct {
|
||||
Password string `json:"password" binding:"required,max=1024"`
|
||||
Code string `json:"code" binding:"required,max=32"`
|
||||
}
|
||||
|
||||
// reauthenticate checks req for the session user and writes the error
|
||||
// response itself when it fails.
|
||||
func (s *Server) reauthenticate(c *gin.Context, req reauthRequest) bool {
|
||||
ctx := c.Request.Context()
|
||||
sess := auth.Current(c)
|
||||
if !s.limit(c, "reauth:"+sess.UserID.String(), 5, 15*time.Minute) {
|
||||
return false
|
||||
}
|
||||
var user store.User
|
||||
err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
|
||||
var err error
|
||||
user, err = q.GetUser(ctx, sess.UserID)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return false
|
||||
}
|
||||
if user.PasswordHash == nil {
|
||||
fail(c, http.StatusConflict, "no_password")
|
||||
return false
|
||||
}
|
||||
if ok, _, err := auth.VerifyPassword(*user.PasswordHash, req.Password); err != nil || !ok {
|
||||
invalidCredentials(c)
|
||||
return false
|
||||
}
|
||||
ok, err := s.verifySecondFactor(ctx, sess.UserID, req.Code)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return false
|
||||
}
|
||||
if !ok {
|
||||
fail(c, http.StatusUnauthorized, "invalid_code")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) totpDisable(c *gin.Context) {
|
||||
var req reauthRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
sess := auth.Current(c)
|
||||
me, err := s.loadMe(ctx, sess)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
for _, o := range me.Orgs {
|
||||
if o.RequireTOTP {
|
||||
fail(c, http.StatusConflict, "totp_required_by_org")
|
||||
return
|
||||
}
|
||||
}
|
||||
if !s.reauthenticate(c, req) {
|
||||
return
|
||||
}
|
||||
err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
|
||||
if err := q.DisableTOTP(ctx, sess.UserID); err != nil {
|
||||
return err
|
||||
}
|
||||
return q.DeleteRecoveryCodes(ctx, sess.UserID)
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) regenerateRecoveryCodes(c *gin.Context) {
|
||||
var req reauthRequest
|
||||
if !bind(c, &req) || !s.reauthenticate(c, req) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
sess := auth.Current(c)
|
||||
codes := auth.NewRecoveryCodes()
|
||||
err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
|
||||
return replaceRecoveryCodes(ctx, q, sess.UserID, codes)
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"recovery_codes": codes})
|
||||
}
|
||||
|
||||
var errNoTOTP = errors.New("api: user has no totp")
|
||||
|
||||
// verifySecondFactor accepts a current TOTP code or an unused recovery code,
|
||||
// which is consumed.
|
||||
func (s *Server) verifySecondFactor(ctx context.Context, userID uuid.UUID, code string) (bool, error) {
|
||||
if rc := auth.NormalizeRecoveryCode(code); rc != "" {
|
||||
var n int64
|
||||
err := s.db.Tx(ctx, tenant.User(userID), func(q *store.Queries) error {
|
||||
var err error
|
||||
n, err = q.UseRecoveryCode(ctx, store.UseRecoveryCodeParams{UserID: userID, CodeHash: auth.HashRecoveryCode(rc)})
|
||||
return err
|
||||
})
|
||||
return n == 1, err
|
||||
}
|
||||
var user store.User
|
||||
err := s.db.Tx(ctx, tenant.User(userID), func(q *store.Queries) error {
|
||||
var err error
|
||||
user, err = q.GetUser(ctx, userID)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if user.TotpSecret == nil {
|
||||
return false, errNoTOTP
|
||||
}
|
||||
secret, err := s.keys.Open(user.TotpSecret, userID[:])
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return s.totp.Verify(ctx, userID, string(secret), code)
|
||||
}
|
||||
|
||||
func qrDataURI(key *otp.Key) (string, error) {
|
||||
img, err := key.Image(240, 240)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, img); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes()), nil
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
func (s *Server) registerPages(r gin.IRouter) {
|
||||
r.GET("/login", s.loginPage)
|
||||
r.GET("/signup", s.signupPage)
|
||||
r.GET("/", s.page("console.monitors.title", web.Dashboard))
|
||||
r.GET("/settings/security", s.securityPage)
|
||||
r.GET("/settings/sso", s.ssoSettingsPage)
|
||||
}
|
||||
|
||||
// flashErrors lists the codes a redirect may ask a page to display. Anything
|
||||
// else in the query string is ignored so links cannot inject messages.
|
||||
var flashErrors = map[ssoError]bool{
|
||||
"sso_unavailable": true, "sso_provider_error": true, "sso_expired": true,
|
||||
"sso_denied": true, "sso_not_member": true, "sso_not_provisioned": true,
|
||||
"sso_link_required": true, "sso_identity_taken": true, "invalid_credentials": true,
|
||||
}
|
||||
|
||||
func (s *Server) pageFor(c *gin.Context, titleID string) web.Page {
|
||||
p := web.Page{TitleID: titleID, Languages: s.catalog.Supported()}
|
||||
if sess := auth.Current(c); sess != nil {
|
||||
p.CSRF = sess.CSRF
|
||||
}
|
||||
if code := ssoError(c.Query("sso_error")); flashErrors[code] {
|
||||
p.ErrorID = "error." + string(code)
|
||||
}
|
||||
if c.Query("sso") == "linked" {
|
||||
p.NoticeID = "security.sso.linked"
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (s *Server) loginPage(c *gin.Context) {
|
||||
if auth.Current(c) != nil {
|
||||
c.Redirect(http.StatusSeeOther, "/")
|
||||
return
|
||||
}
|
||||
allowed, err := s.signupAllowed(c.Request.Context())
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.Login(s.pageFor(c, "auth.login.title"), allowed))
|
||||
}
|
||||
|
||||
func (s *Server) signupPage(c *gin.Context) {
|
||||
allowed, err := s.signupAllowed(c.Request.Context())
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !allowed {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
return
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.Signup(s.pageFor(c, "auth.signup.title")))
|
||||
}
|
||||
|
||||
func (s *Server) page(titleID string, view func(web.Page, web.Me) templ.Component) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
return
|
||||
}
|
||||
me, err := s.loadMe(c.Request.Context(), sess)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
web.Render(c, http.StatusOK, view(s.pageFor(c, titleID), toWebMe(me)))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) securityPage(c *gin.Context) {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
me, err := s.loadMe(ctx, sess)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
var (
|
||||
identities []web.Identity
|
||||
canLink bool
|
||||
)
|
||||
if sess.OrgID != uuid.Nil {
|
||||
err = s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error {
|
||||
rows, err := q.ListUserIdentitiesInOrg(ctx, sess.UserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, r := range rows {
|
||||
identities = append(identities, web.Identity{Provider: r.ProviderName, Email: deref(r.Email)})
|
||||
}
|
||||
providers, err := q.ListEnabledSSOProviders(ctx)
|
||||
canLink = len(providers) > 0
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.Security(s.pageFor(c, "security.title"), toWebMe(me), identities, canLink))
|
||||
}
|
||||
|
||||
func (s *Server) ssoSettingsPage(c *gin.Context) {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
me, err := s.loadMe(ctx, sess)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
wm := toWebMe(me)
|
||||
if !wm.IsOwner {
|
||||
c.Redirect(http.StatusSeeOther, "/")
|
||||
return
|
||||
}
|
||||
var rows []store.SsoProvider
|
||||
err = s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error {
|
||||
rows, err = q.ListSSOProviders(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
view := web.SSOSettings{
|
||||
RedirectURL: s.sso.RedirectURL(),
|
||||
LoginURL: s.cfg.PublicURL + "/sso/" + wm.ActiveSlug,
|
||||
}
|
||||
for _, r := range rows {
|
||||
view.Providers = append(view.Providers, web.SSOProvider{
|
||||
ID: r.ID.String(), Name: r.Name, Issuer: r.Issuer, ClientID: r.ClientID,
|
||||
HasSecret: r.ClientSecret != nil, AllowedDomains: strings.Join(r.AllowedDomains, ", "),
|
||||
AutoProvision: r.AutoProvision, Enabled: r.Enabled,
|
||||
})
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.SSOSettingsPage(s.pageFor(c, "sso.settings.title"), wm, view))
|
||||
}
|
||||
|
||||
func toWebMe(m meView) web.Me {
|
||||
out := web.Me{
|
||||
Email: m.Email,
|
||||
DisplayName: m.DisplayName,
|
||||
TOTP: m.TOTP,
|
||||
ActiveOrg: m.ActiveOrg.String(),
|
||||
TOTPMissing: m.TOTPEnrollmentRequired,
|
||||
RecoveryCodesLeft: m.RecoveryCodesLeft,
|
||||
}
|
||||
for _, o := range m.Orgs {
|
||||
out.Orgs = append(out.Orgs, web.Org{ID: o.ID.String(), Name: o.Name, Slug: o.Slug, IsOwner: o.IsOwner})
|
||||
if o.ID == m.ActiveOrg {
|
||||
out.IsOwner = o.IsOwner
|
||||
out.ActiveSlug = o.Slug
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pquerna/otp/totp"
|
||||
)
|
||||
|
||||
// enableTOTP turns on TOTP for b and returns the secret and recovery codes.
|
||||
func (b *browser) enableTOTP() (string, []string) {
|
||||
b.t.Helper()
|
||||
st, setup := b.do("POST", "/api/v1/me/totp/setup", nil)
|
||||
if st != http.StatusOK {
|
||||
b.t.Fatalf("totp setup = %d %v", st, setup)
|
||||
}
|
||||
secret := setup["secret"].(string)
|
||||
code, _ := totp.GenerateCode(secret, time.Now())
|
||||
st, body := b.do("POST", "/api/v1/me/totp/enable", map[string]any{"code": code})
|
||||
if st != http.StatusOK {
|
||||
b.t.Fatalf("totp enable = %d %v", st, body)
|
||||
}
|
||||
var codes []string
|
||||
for _, c := range body["recovery_codes"].([]any) {
|
||||
codes = append(codes, c.(string))
|
||||
}
|
||||
return secret, codes
|
||||
}
|
||||
|
||||
func TestRecoveryCodes(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
email := uniq("r") + "@example.test"
|
||||
owner := e.browser(t)
|
||||
owner.signup(email, uniq("rec-"))
|
||||
_, codes := owner.enableTOTP()
|
||||
if len(codes) != 10 {
|
||||
t.Fatalf("enable returned %d recovery codes, want 10", len(codes))
|
||||
}
|
||||
|
||||
login := func(code string) (int, map[string]any) {
|
||||
b := e.browser(t)
|
||||
if st, body := b.do("POST", "/api/v1/auth/login", map[string]any{"email": email, "password": "correct horse battery"}); body["status"] != "totp_required" {
|
||||
t.Fatalf("login = %d %v, want totp_required", st, body)
|
||||
}
|
||||
return b.do("POST", "/api/v1/auth/login/totp", map[string]any{"code": code})
|
||||
}
|
||||
|
||||
if st, body := login(codes[0]); st != http.StatusOK {
|
||||
t.Fatalf("login with recovery code = %d %v, want 200", st, body)
|
||||
}
|
||||
if st, _ := login(codes[0]); st != http.StatusUnauthorized {
|
||||
t.Errorf("login with used recovery code = %d, want 401", st)
|
||||
}
|
||||
if st, _ := login(" " + upper(codes[1][:5]) + " " + codes[1][6:]); st != http.StatusOK {
|
||||
t.Errorf("login with reformatted recovery code = %d, want 200", st)
|
||||
}
|
||||
if _, me := owner.do("GET", "/api/v1/me", nil); me["recovery_codes_left"] != float64(8) {
|
||||
t.Errorf("recovery_codes_left = %v, want 8", me["recovery_codes_left"])
|
||||
}
|
||||
|
||||
st, body := owner.do("POST", "/api/v1/me/totp/recovery-codes", map[string]any{"password": "correct horse battery", "code": codes[2]})
|
||||
if st != http.StatusOK || len(body["recovery_codes"].([]any)) != 10 {
|
||||
t.Fatalf("regenerate = %d %v, want 200 with 10 codes", st, body)
|
||||
}
|
||||
if st, _ := login(codes[3]); st != http.StatusUnauthorized {
|
||||
t.Errorf("login with code from replaced set = %d, want 401", st)
|
||||
}
|
||||
if st, _ := login(body["recovery_codes"].([]any)[0].(string)); st != http.StatusOK {
|
||||
t.Errorf("login with code from new set = %d, want 200", st)
|
||||
}
|
||||
|
||||
st, _ = owner.do("POST", "/api/v1/me/totp/recovery-codes", map[string]any{"password": "wrong password!!", "code": codes[4]})
|
||||
if st != http.StatusUnauthorized {
|
||||
t.Errorf("regenerate with wrong password = %d, want 401", st)
|
||||
}
|
||||
}
|
||||
|
||||
func upper(s string) string {
|
||||
b := []byte(s)
|
||||
for i, c := range b {
|
||||
if c >= 'a' && c <= 'z' {
|
||||
b[i] = c - 32
|
||||
}
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
// Package api serves the management JSON API under /api/v1 and the
|
||||
// server-rendered console pages that call it.
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/sealed"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/sso"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
const localeCookie = "lang"
|
||||
|
||||
// Server holds the dependencies shared by all handlers.
|
||||
type Server struct {
|
||||
cfg config.API
|
||||
log *slog.Logger
|
||||
db *tenant.DB
|
||||
rdb redis.UniversalClient
|
||||
keys *sealed.Keyring
|
||||
catalog *i18n.Catalog
|
||||
sessions *auth.Sessions
|
||||
limiter *auth.Limiter
|
||||
totp *auth.TOTPVerifier
|
||||
sso *sso.Client
|
||||
}
|
||||
|
||||
// Deps are the external resources a Server needs.
|
||||
type Deps struct {
|
||||
Log *slog.Logger
|
||||
DB *tenant.DB
|
||||
Redis redis.UniversalClient
|
||||
Keys *sealed.Keyring
|
||||
Catalog *i18n.Catalog
|
||||
}
|
||||
|
||||
// New returns a Server. It does not register any routes; see Mount.
|
||||
func New(cfg config.API, d Deps) *Server {
|
||||
allowPrivate := cfg.SSOAllowPrivate()
|
||||
return &Server{
|
||||
cfg: cfg,
|
||||
log: d.Log,
|
||||
db: d.DB,
|
||||
rdb: d.Redis,
|
||||
keys: d.Keys,
|
||||
catalog: d.Catalog,
|
||||
sessions: auth.NewSessions(d.Redis, cfg.SessionIdle, cfg.SessionAbsolute),
|
||||
limiter: auth.NewLimiter(d.Redis),
|
||||
totp: auth.NewTOTPVerifier(d.Redis),
|
||||
sso: sso.New(sso.SafeHTTPClient(allowPrivate), cfg.PublicURL+"/sso/callback", allowPrivate),
|
||||
}
|
||||
}
|
||||
|
||||
// Mount installs session loading, locale resolution and CSRF protection and
|
||||
// registers the JSON API and the console pages below them.
|
||||
func (s *Server) Mount(r gin.IRouter) {
|
||||
g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF())
|
||||
|
||||
v1 := g.Group("/api/v1")
|
||||
v1.POST("/locale", s.setLocale)
|
||||
|
||||
a := v1.Group("/auth")
|
||||
a.POST("/signup", s.signup)
|
||||
a.POST("/login", s.login)
|
||||
a.POST("/login/totp", s.loginTOTP)
|
||||
a.POST("/logout", s.logout)
|
||||
|
||||
me := v1.Group("/me", auth.Require())
|
||||
me.GET("", s.me)
|
||||
me.POST("/org", s.switchOrg)
|
||||
me.POST("/totp/setup", s.totpSetup)
|
||||
me.POST("/totp/enable", s.totpEnable)
|
||||
me.POST("/totp/disable", s.totpDisable)
|
||||
me.POST("/totp/recovery-codes", s.regenerateRecoveryCodes)
|
||||
|
||||
org := v1.Group("/org", auth.Require(), s.requireOwner())
|
||||
org.GET("/sso", s.listSSOProviders)
|
||||
org.POST("/sso", s.createSSOProvider)
|
||||
org.PUT("/sso/:id", s.updateSSOProvider)
|
||||
org.DELETE("/sso/:id", s.deleteSSOProvider)
|
||||
|
||||
g.GET("/sso", s.ssoLookup)
|
||||
g.GET("/sso/callback", s.ssoCallback)
|
||||
g.GET("/sso/:slug", s.ssoChoose)
|
||||
g.GET("/sso/:slug/:provider", s.ssoStartProvider)
|
||||
|
||||
s.registerPages(g)
|
||||
}
|
||||
|
||||
// localize resolves the language from, in order: the signed-in user's
|
||||
// setting, the lang cookie, and Accept-Language.
|
||||
func (s *Server) localize() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var pref string
|
||||
if sess := auth.Current(c); sess != nil {
|
||||
pref = sess.Locale
|
||||
}
|
||||
cookie, _ := c.Cookie(localeCookie)
|
||||
l := s.catalog.Match(pref, cookie, c.GetHeader("Accept-Language"))
|
||||
c.Request = c.Request.WithContext(i18n.NewContext(c.Request.Context(), l))
|
||||
c.Header("Content-Language", l.Lang())
|
||||
c.Header("Vary", "Accept-Language, Cookie")
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
type localeRequest struct {
|
||||
Locale string `json:"locale" binding:"required,max=10"`
|
||||
}
|
||||
|
||||
func (s *Server) setLocale(c *gin.Context) {
|
||||
var req localeRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
if !s.catalog.IsSupported(req.Locale) {
|
||||
fail(c, http.StatusUnprocessableEntity, "unsupported_locale")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
if sess := auth.Current(c); sess != nil {
|
||||
err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
|
||||
return q.SetUserLocale(ctx, store.SetUserLocaleParams{ID: sess.UserID, Locale: &req.Locale})
|
||||
})
|
||||
if err == nil {
|
||||
err = s.sessions.SetLocale(ctx, sess, req.Locale)
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
setCookie(c, localeCookie, req.Locale, 365*24*3600)
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
type apiError struct {
|
||||
Error string `json:"error"`
|
||||
Message string `json:"message"`
|
||||
Fields map[string]string `json:"fields,omitempty"`
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
}
|
||||
|
||||
// fail aborts with a machine-readable code and a message translated from
|
||||
// the catalog entry "error.<code>". kv fills placeholders in that message.
|
||||
func fail(c *gin.Context, status int, code string, kv ...any) {
|
||||
ctx := c.Request.Context()
|
||||
c.AbortWithStatusJSON(status, apiError{
|
||||
Error: code,
|
||||
Message: i18n.T(ctx, "error."+code, kv...),
|
||||
RequestID: requestid.FromContext(ctx),
|
||||
})
|
||||
}
|
||||
|
||||
func internalError(c *gin.Context, err error) {
|
||||
_ = c.Error(err)
|
||||
fail(c, http.StatusInternalServerError, "internal")
|
||||
}
|
||||
|
||||
func bind(c *gin.Context, dst any) bool {
|
||||
err := c.ShouldBindJSON(dst)
|
||||
if err == nil {
|
||||
return true
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
e := apiError{Error: "invalid_input", Message: i18n.T(ctx, "error.invalid_input"), RequestID: requestid.FromContext(ctx)}
|
||||
var ve validator.ValidationErrors
|
||||
if errors.As(err, &ve) {
|
||||
e.Fields = map[string]string{}
|
||||
for _, f := range ve {
|
||||
e.Fields[f.Field()] = f.Tag()
|
||||
}
|
||||
}
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, e)
|
||||
return false
|
||||
}
|
||||
|
||||
func setCookie(c *gin.Context, name, value string, maxAge int) {
|
||||
http.SetCookie(c.Writer, &http.Cookie{
|
||||
Name: name, Value: value, Path: "/", MaxAge: maxAge,
|
||||
Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
}
|
||||
|
||||
func ptr[T any](v T) *T { return &v }
|
||||
|
||||
func deref[T any](p *T) T {
|
||||
var zero T
|
||||
if p == nil {
|
||||
return zero
|
||||
}
|
||||
return *p
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/sso"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
const (
|
||||
ssoCookie = "__Host-sso"
|
||||
ssoFlowTTL = 10 * time.Minute
|
||||
)
|
||||
|
||||
// ssoFlow is kept in Redis between the redirect to the IdP and the callback.
|
||||
type ssoFlow struct {
|
||||
Provider uuid.UUID `json:"provider"`
|
||||
Org uuid.UUID `json:"org"`
|
||||
Nonce string `json:"nonce"`
|
||||
Verifier string `json:"verifier"`
|
||||
// LinkUser is set when a signed-in user connects this IdP to their
|
||||
// existing account instead of signing in.
|
||||
LinkUser uuid.UUID `json:"link_user,omitempty"`
|
||||
}
|
||||
|
||||
// ssoError aborts a browser flow by redirecting with a code the target page
|
||||
// translates. Unlike JSON errors, the user has navigated away from our page.
|
||||
type ssoError string
|
||||
|
||||
func ssoFlowKey(state string) string {
|
||||
sum := sha256.Sum256([]byte(state))
|
||||
return "sso_flow:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (s *Server) ssoProvider(row store.SsoProvider) (sso.Provider, error) {
|
||||
p := sso.Provider{Issuer: row.Issuer, ClientID: row.ClientID, Scopes: row.Scopes}
|
||||
if row.ClientSecret != nil {
|
||||
secret, err := s.keys.Open(row.ClientSecret, row.ID[:])
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
p.ClientSecret = string(secret)
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// ssoLookup redirects the login page's slug form to the org's SSO URL.
|
||||
func (s *Server) ssoLookup(c *gin.Context) {
|
||||
slug := strings.ToLower(strings.TrimSpace(c.Query("org")))
|
||||
if slug == "" {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
return
|
||||
}
|
||||
c.Redirect(http.StatusSeeOther, "/sso/"+url.PathEscape(slug))
|
||||
}
|
||||
|
||||
// ssoChoose starts the flow if the org has exactly one enabled provider and
|
||||
// otherwise lets the user pick.
|
||||
func (s *Server) ssoChoose(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
if !s.limitPage(c, "sso:ip:"+c.ClientIP(), 30, time.Minute) {
|
||||
return
|
||||
}
|
||||
org, err := s.orgIDBySlug(ctx, c.Param("slug"))
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
var providers []store.ListEnabledSSOProvidersRow
|
||||
if org != uuid.Nil {
|
||||
err = s.db.Tx(ctx, tenant.Org(org, uuid.Nil), func(q *store.Queries) error {
|
||||
providers, err = q.ListEnabledSSOProviders(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
switch len(providers) {
|
||||
case 0:
|
||||
s.ssoAbort(c, uuid.Nil, "sso_unavailable")
|
||||
case 1:
|
||||
s.ssoStart(c, org, providers[0].ID)
|
||||
default:
|
||||
opts := make([]web.SSOOption, len(providers))
|
||||
for i, p := range providers {
|
||||
opts[i] = web.SSOOption{Name: p.Name, URL: "/sso/" + url.PathEscape(c.Param("slug")) + "/" + p.ID.String() + linkSuffix(c)}
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.SSOChooser(s.pageFor(c, "sso.choose.title"), opts))
|
||||
}
|
||||
}
|
||||
|
||||
func linkSuffix(c *gin.Context) string {
|
||||
if c.Query("link") == "1" {
|
||||
return "?link=1"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *Server) ssoStartProvider(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
if !s.limitPage(c, "sso:ip:"+c.ClientIP(), 30, time.Minute) {
|
||||
return
|
||||
}
|
||||
org, err := s.orgIDBySlug(ctx, c.Param("slug"))
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
id, err := uuid.Parse(c.Param("provider"))
|
||||
if err != nil || org == uuid.Nil {
|
||||
s.ssoAbort(c, uuid.Nil, "sso_unavailable")
|
||||
return
|
||||
}
|
||||
s.ssoStart(c, org, id)
|
||||
}
|
||||
|
||||
func (s *Server) ssoStart(c *gin.Context, org, providerID uuid.UUID) {
|
||||
ctx := c.Request.Context()
|
||||
var linkUser uuid.UUID
|
||||
if c.Query("link") == "1" {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil {
|
||||
c.Redirect(http.StatusSeeOther, "/login")
|
||||
return
|
||||
}
|
||||
linkUser = sess.UserID
|
||||
}
|
||||
var row store.SsoProvider
|
||||
err := s.db.Tx(ctx, tenant.Org(org, uuid.Nil), func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.GetSSOProvider(ctx, providerID)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && !row.Enabled) {
|
||||
s.ssoAbort(c, linkUser, "sso_unavailable")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
p, err := s.ssoProvider(row)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
flow := sso.NewFlow(auth.RandomToken)
|
||||
authURL, err := s.sso.AuthURL(ctx, p, flow)
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "sso discovery failed", "provider", providerID, "error", err)
|
||||
s.ssoAbort(c, linkUser, "sso_provider_error")
|
||||
return
|
||||
}
|
||||
state, _ := json.Marshal(ssoFlow{Provider: row.ID, Org: org, Nonce: flow.Nonce, Verifier: flow.Verifier, LinkUser: linkUser})
|
||||
if err := s.rdb.Set(ctx, ssoFlowKey(flow.State), state, ssoFlowTTL).Err(); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
// Binding the state to this browser stops an attacker from completing
|
||||
// their own flow in a victim's browser (login CSRF).
|
||||
setCookie(c, ssoCookie, flow.State, int(ssoFlowTTL.Seconds()))
|
||||
c.Redirect(http.StatusFound, authURL)
|
||||
}
|
||||
|
||||
func (s *Server) ssoCallback(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
state := c.Query("state")
|
||||
cookie, _ := c.Cookie(ssoCookie)
|
||||
setCookie(c, ssoCookie, "", -1)
|
||||
if state == "" || cookie != state {
|
||||
s.ssoAbort(c, uuid.Nil, "sso_expired")
|
||||
return
|
||||
}
|
||||
raw, err := s.rdb.GetDel(ctx, ssoFlowKey(state)).Bytes()
|
||||
if err != nil {
|
||||
s.ssoAbort(c, uuid.Nil, "sso_expired")
|
||||
return
|
||||
}
|
||||
var f ssoFlow
|
||||
if err := json.Unmarshal(raw, &f); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if c.Query("error") != "" {
|
||||
s.ssoAbort(c, f.LinkUser, "sso_denied")
|
||||
return
|
||||
}
|
||||
|
||||
var row store.SsoProvider
|
||||
err = s.db.Tx(ctx, tenant.Org(f.Org, uuid.Nil), func(q *store.Queries) error {
|
||||
row, err = q.GetSSOProvider(ctx, f.Provider)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && !row.Enabled) {
|
||||
s.ssoAbort(c, f.LinkUser, "sso_unavailable")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
p, err := s.ssoProvider(row)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
claims, err := s.sso.Exchange(ctx, p, sso.Flow{State: state, Nonce: f.Nonce, Verifier: f.Verifier}, c.Query("code"))
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "sso exchange failed", "provider", row.ID, "error", err)
|
||||
s.ssoAbort(c, f.LinkUser, "sso_provider_error")
|
||||
return
|
||||
}
|
||||
|
||||
if f.LinkUser != uuid.Nil {
|
||||
s.ssoLink(c, row, f.LinkUser, claims)
|
||||
return
|
||||
}
|
||||
userID, code, err := s.ssoResolveUser(ctx, row, claims)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if code != "" {
|
||||
s.ssoAbort(c, uuid.Nil, code)
|
||||
return
|
||||
}
|
||||
var user store.User
|
||||
err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
user, err = q.GetUser(ctx, userID)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if user.DisabledAt != nil {
|
||||
s.ssoAbort(c, uuid.Nil, "invalid_credentials")
|
||||
return
|
||||
}
|
||||
if old := auth.Current(c); old != nil {
|
||||
_ = s.sessions.Delete(ctx, old)
|
||||
}
|
||||
locale := deref(user.Locale)
|
||||
if locale == "" {
|
||||
locale = i18n.Lang(ctx)
|
||||
}
|
||||
sess, err := s.sessions.Create(ctx, userID, row.OrgID, locale)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
auth.SetCookie(c, sess, int(s.cfg.SessionAbsolute.Seconds()))
|
||||
c.Redirect(http.StatusSeeOther, "/")
|
||||
}
|
||||
|
||||
// ssoResolveUser maps an IdP identity to a user. It returns a non-empty
|
||||
// error code when sign-in must be refused.
|
||||
//
|
||||
// Existing accounts are only ever reached through a stored identity. A
|
||||
// matching email is not enough: the org controls its IdP and could assert
|
||||
// the address of a user who also belongs to other orgs.
|
||||
func (s *Server) ssoResolveUser(ctx context.Context, row store.SsoProvider, cl sso.Claims) (uuid.UUID, ssoError, error) {
|
||||
var (
|
||||
userID uuid.UUID
|
||||
code ssoError
|
||||
)
|
||||
email := normalizeEmail(cl.Email)
|
||||
err := s.db.Tx(ctx, tenant.Org(row.OrgID, uuid.Nil), func(q *store.Queries) error {
|
||||
ident, err := q.GetIdentity(ctx, store.GetIdentityParams{ProviderID: row.ID, Subject: cl.Subject})
|
||||
switch {
|
||||
case err == nil:
|
||||
member, err := q.IsMember(ctx, store.IsMemberParams{OrgID: row.OrgID, UserID: ident.UserID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
code = "sso_not_member"
|
||||
return nil
|
||||
}
|
||||
userID = ident.UserID
|
||||
return q.TouchIdentity(ctx, store.TouchIdentityParams{ProviderID: row.ID, Subject: cl.Subject, Email: nonEmpty(email)})
|
||||
case !errors.Is(err, pgx.ErrNoRows):
|
||||
return err
|
||||
}
|
||||
|
||||
if !row.AutoProvision || email == "" || !cl.EmailVerified || !domainAllowed(email, row.AllowedDomains) {
|
||||
code = "sso_not_provisioned"
|
||||
return nil
|
||||
}
|
||||
if _, err := q.GetUserByEmail(ctx, email); err == nil {
|
||||
code = "sso_link_required"
|
||||
return nil
|
||||
} else if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
u, err := q.CreateUser(ctx, store.CreateUserParams{
|
||||
Email: email,
|
||||
DisplayName: truncate(strings.TrimSpace(cl.Name), 200),
|
||||
Locale: ptr(i18n.Lang(ctx)),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: row.OrgID, UserID: u.ID}); err != nil {
|
||||
return err
|
||||
}
|
||||
userID = u.ID
|
||||
return q.CreateIdentity(ctx, store.CreateIdentityParams{ProviderID: row.ID, Subject: cl.Subject, OrgID: row.OrgID, UserID: u.ID, Email: nonEmpty(email)})
|
||||
})
|
||||
return userID, code, err
|
||||
}
|
||||
|
||||
func (s *Server) ssoLink(c *gin.Context, row store.SsoProvider, userID uuid.UUID, cl sso.Claims) {
|
||||
ctx := c.Request.Context()
|
||||
sess := auth.Current(c)
|
||||
if sess == nil || sess.UserID != userID {
|
||||
s.ssoAbort(c, uuid.Nil, "sso_expired")
|
||||
return
|
||||
}
|
||||
var code ssoError
|
||||
err := s.db.Tx(ctx, tenant.Org(row.OrgID, userID), func(q *store.Queries) error {
|
||||
member, err := q.IsMember(ctx, store.IsMemberParams{OrgID: row.OrgID, UserID: userID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
code = "sso_not_member"
|
||||
return nil
|
||||
}
|
||||
ident, err := q.GetIdentity(ctx, store.GetIdentityParams{ProviderID: row.ID, Subject: cl.Subject})
|
||||
switch {
|
||||
case err == nil && ident.UserID == userID:
|
||||
return nil
|
||||
case err == nil:
|
||||
code = "sso_identity_taken"
|
||||
return nil
|
||||
case !errors.Is(err, pgx.ErrNoRows):
|
||||
return err
|
||||
}
|
||||
return q.CreateIdentity(ctx, store.CreateIdentityParams{
|
||||
ProviderID: row.ID, Subject: cl.Subject, OrgID: row.OrgID, UserID: userID, Email: nonEmpty(normalizeEmail(cl.Email)),
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if code != "" {
|
||||
s.ssoAbort(c, userID, code)
|
||||
return
|
||||
}
|
||||
c.Redirect(http.StatusSeeOther, "/settings/security?sso=linked")
|
||||
}
|
||||
|
||||
// ssoAbort sends the browser back to where the flow started with an error
|
||||
// code the page renders in the user's language.
|
||||
func (s *Server) ssoAbort(c *gin.Context, linkUser uuid.UUID, code ssoError) {
|
||||
target := "/login"
|
||||
if linkUser != uuid.Nil {
|
||||
target = "/settings/security"
|
||||
}
|
||||
c.Redirect(http.StatusSeeOther, target+"?sso_error="+url.QueryEscape(string(code)))
|
||||
}
|
||||
|
||||
func (s *Server) orgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error) {
|
||||
var id uuid.UUID
|
||||
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
var err error
|
||||
id, err = q.OrgIDBySlug(ctx, strings.ToLower(slug))
|
||||
return err
|
||||
})
|
||||
return id, err
|
||||
}
|
||||
|
||||
func (s *Server) limitPage(c *gin.Context, key string, n int, window time.Duration) bool {
|
||||
ok, err := s.limiter.Allow(c.Request.Context(), key, n, window)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return false
|
||||
}
|
||||
if !ok {
|
||||
c.Header("Retry-After", "60")
|
||||
c.AbortWithStatus(http.StatusTooManyRequests)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func domainAllowed(email string, allowed []string) bool {
|
||||
if len(allowed) == 0 {
|
||||
return true
|
||||
}
|
||||
at := strings.LastIndexByte(email, '@')
|
||||
if at < 0 {
|
||||
return false
|
||||
}
|
||||
domain := email[at+1:]
|
||||
for _, d := range allowed {
|
||||
if domain == d {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func nonEmpty(s string) *string {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return &s
|
||||
}
|
||||
|
||||
func truncate(s string, n int) string {
|
||||
if r := []rune(s); len(r) > n {
|
||||
return string(r[:n])
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/sso"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
const ctxOrgKey = "api.org"
|
||||
|
||||
// requireOwner admits only the owner of the session's active org. It is a
|
||||
// stand-in until role-based permissions exist (#6).
|
||||
func (s *Server) requireOwner() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
sess := auth.Current(c)
|
||||
if sess == nil || sess.OrgID == uuid.Nil {
|
||||
fail(c, http.StatusForbidden, "forbidden")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var m store.Membership
|
||||
err := s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error {
|
||||
var err error
|
||||
m, err = q.GetMembership(ctx, store.GetMembershipParams{OrgID: sess.OrgID, UserID: sess.UserID})
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && !m.IsOwner) {
|
||||
fail(c, http.StatusForbidden, "forbidden")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.Set(ctxOrgKey, sess.OrgID)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func orgOf(c *gin.Context) uuid.UUID { return c.MustGet(ctxOrgKey).(uuid.UUID) }
|
||||
|
||||
type ssoProviderView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Issuer string `json:"issuer"`
|
||||
ClientID string `json:"client_id"`
|
||||
HasClientSecret bool `json:"has_client_secret"`
|
||||
Scopes []string `json:"scopes"`
|
||||
AllowedDomains []string `json:"allowed_domains"`
|
||||
AutoProvision bool `json:"auto_provision"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
func viewSSOProvider(p store.SsoProvider) ssoProviderView {
|
||||
return ssoProviderView{
|
||||
ID: p.ID, Name: p.Name, Issuer: p.Issuer, ClientID: p.ClientID,
|
||||
HasClientSecret: p.ClientSecret != nil, Scopes: p.Scopes,
|
||||
AllowedDomains: p.AllowedDomains, AutoProvision: p.AutoProvision, Enabled: p.Enabled,
|
||||
}
|
||||
}
|
||||
|
||||
type ssoProviderRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
Issuer string `json:"issuer" binding:"required,max=500"`
|
||||
ClientID string `json:"client_id" binding:"required,max=500"`
|
||||
// Empty on update keeps the stored secret; it is never returned.
|
||||
ClientSecret string `json:"client_secret" binding:"max=2000"`
|
||||
Scopes []string `json:"scopes" binding:"max=20,dive,max=100"`
|
||||
AllowedDomains []string `json:"allowed_domains" binding:"max=50,dive,max=253"`
|
||||
AutoProvision bool `json:"auto_provision"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
|
||||
var domainRE = regexp.MustCompile(`^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$`)
|
||||
|
||||
// normalize cleans the request and returns an error code for invalid input.
|
||||
func (r *ssoProviderRequest) normalize() string {
|
||||
r.Name = strings.TrimSpace(r.Name)
|
||||
r.Issuer = strings.TrimSuffix(strings.TrimSpace(r.Issuer), "/")
|
||||
r.ClientID = strings.TrimSpace(r.ClientID)
|
||||
if r.Name == "" || r.ClientID == "" {
|
||||
return "invalid_input"
|
||||
}
|
||||
scopes := []string{"openid"}
|
||||
for _, sc := range r.Scopes {
|
||||
if sc = strings.TrimSpace(sc); sc != "" && !slices.Contains(scopes, sc) {
|
||||
scopes = append(scopes, sc)
|
||||
}
|
||||
}
|
||||
if len(r.Scopes) == 0 {
|
||||
scopes = append(scopes, "email", "profile")
|
||||
}
|
||||
r.Scopes = scopes
|
||||
domains := []string{}
|
||||
for _, d := range r.AllowedDomains {
|
||||
d = strings.TrimPrefix(strings.ToLower(strings.TrimSpace(d)), "@")
|
||||
if d == "" {
|
||||
continue
|
||||
}
|
||||
if !domainRE.MatchString(d) {
|
||||
return "invalid_domain"
|
||||
}
|
||||
if !slices.Contains(domains, d) {
|
||||
domains = append(domains, d)
|
||||
}
|
||||
}
|
||||
r.AllowedDomains = domains
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *Server) listSSOProviders(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.SsoProvider
|
||||
err := s.db.Tx(ctx, tenant.Org(orgOf(c), auth.Current(c).UserID), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListSSOProviders(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]ssoProviderView, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = viewSSOProvider(r)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"providers": out, "redirect_url": s.sso.RedirectURL()})
|
||||
}
|
||||
|
||||
func (s *Server) validateSSORequest(c *gin.Context, req *ssoProviderRequest) bool {
|
||||
if code := req.normalize(); code != "" {
|
||||
fail(c, http.StatusUnprocessableEntity, code)
|
||||
return false
|
||||
}
|
||||
if err := s.sso.ValidateIssuer(c.Request.Context(), req.Issuer); err != nil {
|
||||
code := "sso_discovery_failed"
|
||||
switch {
|
||||
case errors.Is(err, sso.ErrInvalidIssuer):
|
||||
code = "sso_invalid_issuer"
|
||||
case errors.Is(err, sso.ErrForbiddenAddress):
|
||||
code = "sso_forbidden_address"
|
||||
}
|
||||
fail(c, http.StatusUnprocessableEntity, code)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) createSSOProvider(c *gin.Context) {
|
||||
var req ssoProviderRequest
|
||||
if !bind(c, &req) || !s.validateSSORequest(c, &req) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
id := uuid.New()
|
||||
var secret []byte
|
||||
if req.ClientSecret != "" {
|
||||
secret = s.keys.Seal([]byte(req.ClientSecret), id[:])
|
||||
}
|
||||
var row store.SsoProvider
|
||||
err := s.db.Tx(ctx, tenant.Org(orgOf(c), auth.Current(c).UserID), func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.CreateSSOProvider(ctx, store.CreateSSOProviderParams{
|
||||
ID: id, OrgID: orgOf(c), Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID,
|
||||
ClientSecret: secret, Scopes: req.Scopes, AllowedDomains: req.AllowedDomains,
|
||||
AutoProvision: req.AutoProvision, Enabled: req.Enabled == nil || *req.Enabled,
|
||||
})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, viewSSOProvider(row))
|
||||
}
|
||||
|
||||
func (s *Server) updateSSOProvider(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
var req ssoProviderRequest
|
||||
if !bind(c, &req) || !s.validateSSORequest(c, &req) {
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var secret []byte
|
||||
if req.ClientSecret != "" {
|
||||
secret = s.keys.Seal([]byte(req.ClientSecret), id[:])
|
||||
}
|
||||
var row store.SsoProvider
|
||||
err = s.db.Tx(ctx, tenant.Org(orgOf(c), auth.Current(c).UserID), func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.UpdateSSOProvider(ctx, store.UpdateSSOProviderParams{
|
||||
ID: id, Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID, ClientSecret: secret,
|
||||
Scopes: req.Scopes, AllowedDomains: req.AllowedDomains, AutoProvision: req.AutoProvision,
|
||||
Enabled: req.Enabled == nil || *req.Enabled,
|
||||
})
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, viewSSOProvider(row))
|
||||
}
|
||||
|
||||
func (s *Server) deleteSSOProvider(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var n int64
|
||||
err = s.db.Tx(ctx, tenant.Org(orgOf(c), auth.Current(c).UserID), func(q *store.Queries) error {
|
||||
var err error
|
||||
n, err = q.DeleteSSOProvider(ctx, id)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/api"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/migrations"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/platform"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/sealed"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/sso/ssotest"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
type env struct {
|
||||
srv *httptest.Server
|
||||
dbPool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func newEnv(t *testing.T) *env {
|
||||
t.Helper()
|
||||
dsn, redisURL := os.Getenv("UPTIME_TEST_DATABASE_URL"), os.Getenv("UPTIME_TEST_REDIS_URL")
|
||||
if dsn == "" || redisURL == "" {
|
||||
t.Skip("UPTIME_TEST_DATABASE_URL and UPTIME_TEST_REDIS_URL must be set")
|
||||
}
|
||||
ctx := context.Background()
|
||||
if _, err := migrations.Up(ctx, dsn); err != nil {
|
||||
t.Fatalf("migrations.Up() failed: %v", err)
|
||||
}
|
||||
pool, err := pgxpool.New(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
opts, err := redis.ParseURL(redisURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rdb := redis.NewClient(opts)
|
||||
t.Cleanup(func() { _ = rdb.Close() })
|
||||
// UPTIME_TEST_REDIS_URL must name a database reserved for tests; clearing
|
||||
// it resets rate limits left over from earlier runs.
|
||||
if err := rdb.FlushDB(ctx).Err(); err != nil {
|
||||
t.Fatalf("FLUSHDB failed: %v", err)
|
||||
}
|
||||
|
||||
key := make([]byte, 32)
|
||||
_, _ = rand.Read(key)
|
||||
keys, err := sealed.Parse("t:" + base64.StdEncoding.EncodeToString(key))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
catalog, err := i18n.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
|
||||
e := &env{dbPool: pool}
|
||||
r := platform.NewRouter(log)
|
||||
e.srv = httptest.NewUnstartedServer(r)
|
||||
e.srv.StartTLS()
|
||||
t.Cleanup(e.srv.Close)
|
||||
|
||||
cfg := config.API{
|
||||
Common: config.Common{Edition: config.EditionSelfHosted},
|
||||
Signup: config.SignupOpen,
|
||||
SessionIdle: time.Hour,
|
||||
SessionAbsolute: 24 * time.Hour,
|
||||
PublicURL: e.srv.URL,
|
||||
SSOPrivateNetworks: "true",
|
||||
}
|
||||
api.New(cfg, api.Deps{Log: log, DB: tenant.New(pool), Redis: rdb, Keys: keys, Catalog: catalog}).Mount(r)
|
||||
return e
|
||||
}
|
||||
|
||||
// browser is a cookie-keeping client that follows redirects like a browser.
|
||||
type browser struct {
|
||||
t *testing.T
|
||||
base string
|
||||
hc *http.Client
|
||||
csrf string
|
||||
}
|
||||
|
||||
func (e *env) browser(t *testing.T) *browser {
|
||||
jar, _ := cookiejar.New(nil)
|
||||
// Client() returns a shared instance; copy it so each browser has its own jar.
|
||||
hc := *e.srv.Client()
|
||||
hc.Jar = jar
|
||||
return &browser{t: t, base: e.srv.URL, hc: &hc}
|
||||
}
|
||||
|
||||
func (b *browser) do(method, path string, body any) (int, map[string]any) {
|
||||
b.t.Helper()
|
||||
var rd io.Reader
|
||||
if body != nil {
|
||||
raw, _ := json.Marshal(body)
|
||||
rd = bytes.NewReader(raw)
|
||||
}
|
||||
req, _ := http.NewRequest(method, b.base+path, rd)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if b.csrf != "" {
|
||||
req.Header.Set("X-CSRF-Token", b.csrf)
|
||||
}
|
||||
resp, err := b.hc.Do(req)
|
||||
if err != nil {
|
||||
b.t.Fatalf("%s %s failed: %v", method, path, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
var out map[string]any
|
||||
_ = json.NewDecoder(resp.Body).Decode(&out)
|
||||
if tok, ok := out["csrf_token"].(string); ok {
|
||||
b.csrf = tok
|
||||
}
|
||||
return resp.StatusCode, out
|
||||
}
|
||||
|
||||
// visit follows redirects and returns the final URL.
|
||||
func (b *browser) visit(path string) *url.URL {
|
||||
b.t.Helper()
|
||||
resp, err := b.hc.Get(b.base + path)
|
||||
if err != nil {
|
||||
b.t.Fatalf("GET %s failed: %v", path, err)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
return resp.Request.URL
|
||||
}
|
||||
|
||||
func uniq(prefix string) string { return prefix + strings.ReplaceAll(uuid.NewString()[:8], "-", "") }
|
||||
|
||||
func (b *browser) signup(email, slug string) {
|
||||
b.t.Helper()
|
||||
st, body := b.do("POST", "/api/v1/auth/signup", map[string]any{
|
||||
"email": email, "password": "correct horse battery", "org_name": slug, "org_slug": slug,
|
||||
})
|
||||
if st != http.StatusOK {
|
||||
b.t.Fatalf("signup(%s) = %d %v, want 200", email, st, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSO(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
idp := ssotest.New(t)
|
||||
slug := uniq("sso-")
|
||||
domain := uniq("d") + ".test"
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("owner@"+domain, slug)
|
||||
|
||||
st, body := owner.do("POST", "/api/v1/org/sso", map[string]any{
|
||||
"name": "Corp IdP", "issuer": idp.Issuer(), "client_id": idp.ClientID, "client_secret": idp.Secret,
|
||||
"allowed_domains": []string{domain}, "auto_provision": true,
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create provider = %d %v, want 201", st, body)
|
||||
}
|
||||
if body["has_client_secret"] != true || body["client_secret"] != nil {
|
||||
t.Errorf("create provider response = %v, want has_client_secret and no secret", body)
|
||||
}
|
||||
|
||||
t.Run("other org cannot see provider", func(t *testing.T) {
|
||||
other := e.browser(t)
|
||||
other.signup("x@"+uniq("o")+".test", uniq("other-"))
|
||||
st, body := other.do("GET", "/api/v1/org/sso", nil)
|
||||
if st != http.StatusOK || len(body["providers"].([]any)) != 0 {
|
||||
t.Errorf("GET /api/v1/org/sso as other org = %d %v, want 200 with no providers", st, body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("auto provisioning", func(t *testing.T) {
|
||||
idp.SetUser(ssotest.User{Subject: uniq("s"), Email: "new@" + domain, EmailVerified: true, Name: "New"})
|
||||
u := e.browser(t)
|
||||
if got := u.visit("/sso/" + slug); got.Path != "/" || got.Query().Get("sso_error") != "" {
|
||||
t.Fatalf("SSO login landed on %s, want /", got)
|
||||
}
|
||||
st, me := u.do("GET", "/api/v1/me", nil)
|
||||
if st != http.StatusOK || me["email"] != "new@"+domain {
|
||||
t.Errorf("GET /api/v1/me = %d %v, want new@%s", st, me, domain)
|
||||
}
|
||||
st, _ = u.do("GET", "/api/v1/org/sso", nil)
|
||||
if st != http.StatusForbidden {
|
||||
t.Errorf("GET /api/v1/org/sso as member = %d, want 403", st)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unverified email is not provisioned", func(t *testing.T) {
|
||||
idp.SetUser(ssotest.User{Subject: uniq("s"), Email: "unverified@" + domain, EmailVerified: false})
|
||||
if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_not_provisioned" {
|
||||
t.Errorf("SSO login landed on %s, want sso_error=sso_not_provisioned", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("foreign domain is not provisioned", func(t *testing.T) {
|
||||
idp.SetUser(ssotest.User{Subject: uniq("s"), Email: "x@elsewhere.test", EmailVerified: true})
|
||||
if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_not_provisioned" {
|
||||
t.Errorf("SSO login landed on %s, want sso_error=sso_not_provisioned", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("existing email requires explicit linking", func(t *testing.T) {
|
||||
subject := uniq("s")
|
||||
idp.SetUser(ssotest.User{Subject: subject, Email: "owner@" + domain, EmailVerified: true})
|
||||
if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_link_required" {
|
||||
t.Fatalf("SSO login landed on %s, want sso_error=sso_link_required", got)
|
||||
}
|
||||
|
||||
if got := owner.visit("/sso/" + slug + "?link=1"); got.Path != "/settings/security" || got.Query().Get("sso") != "linked" {
|
||||
t.Fatalf("link flow landed on %s, want /settings/security?sso=linked", got)
|
||||
}
|
||||
fresh := e.browser(t)
|
||||
if got := fresh.visit("/sso/" + slug); got.Path != "/" {
|
||||
t.Fatalf("SSO login after linking landed on %s, want /", got)
|
||||
}
|
||||
if _, me := fresh.do("GET", "/api/v1/me", nil); me["email"] != "owner@"+domain {
|
||||
t.Errorf("GET /api/v1/me after linked login = %v, want owner", me)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("callback without browser binding is rejected", func(t *testing.T) {
|
||||
attacker := e.browser(t)
|
||||
attacker.hc.CheckRedirect = func(req *http.Request, _ []*http.Request) error {
|
||||
if strings.HasPrefix(req.URL.Path, "/sso/callback") {
|
||||
return http.ErrUseLastResponse
|
||||
}
|
||||
return nil
|
||||
}
|
||||
resp, err := attacker.hc.Get(attacker.base + "/sso/" + slug)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
callback := resp.Header.Get("Location")
|
||||
if got := e.browser(t).visit(strings.TrimPrefix(callback, attacker.base)); got.Query().Get("sso_error") != "sso_expired" {
|
||||
t.Errorf("replaying callback in another browser landed on %s, want sso_error=sso_expired", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("disabled provider", func(t *testing.T) {
|
||||
_, list := owner.do("GET", "/api/v1/org/sso", nil)
|
||||
p := list["providers"].([]any)[0].(map[string]any)
|
||||
st, body := owner.do("PUT", "/api/v1/org/sso/"+p["id"].(string), map[string]any{
|
||||
"name": p["name"], "issuer": p["issuer"], "client_id": p["client_id"], "enabled": false,
|
||||
})
|
||||
if st != http.StatusOK || body["has_client_secret"] != true {
|
||||
t.Fatalf("PUT provider = %d %v, want 200 keeping the secret", st, body)
|
||||
}
|
||||
if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_unavailable" {
|
||||
t.Errorf("SSO login with disabled provider landed on %s, want sso_error=sso_unavailable", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSSOProviderValidation(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("v")+".test", uniq("val-"))
|
||||
tests := []struct {
|
||||
name string
|
||||
body map[string]any
|
||||
want string
|
||||
}{
|
||||
{"bad scheme", map[string]any{"name": "x", "issuer": "ftp://idp.test", "client_id": "c"}, "sso_invalid_issuer"},
|
||||
{"unreachable", map[string]any{"name": "x", "issuer": "http://127.0.0.1:1", "client_id": "c"}, "sso_discovery_failed"},
|
||||
{"bad domain", map[string]any{"name": "x", "issuer": "https://idp.test", "client_id": "c", "allowed_domains": []string{"not a domain"}}, "invalid_domain"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
st, body := owner.do("POST", "/api/v1/org/sso", tt.body)
|
||||
if st != http.StatusUnprocessableEntity || body["error"] != tt.want {
|
||||
t.Errorf("POST /api/v1/org/sso = %d %v, want 422 %s", st, body["error"], tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Names shared with the browser side.
|
||||
const (
|
||||
CookieName = "__Host-session"
|
||||
CSRFHeader = "X-CSRF-Token"
|
||||
CSRFField = "_csrf"
|
||||
ctxKey = "auth.session"
|
||||
)
|
||||
|
||||
// SetCookie sends the session cookie. The __Host- prefix makes browsers
|
||||
// reject it unless it is Secure, host-only and scoped to /.
|
||||
func SetCookie(c *gin.Context, sess *Session, maxAge int) {
|
||||
http.SetCookie(c.Writer, &http.Cookie{
|
||||
Name: CookieName,
|
||||
Value: sess.Token,
|
||||
Path: "/",
|
||||
MaxAge: maxAge,
|
||||
Secure: true,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
}
|
||||
|
||||
// ClearCookie removes the session cookie.
|
||||
func ClearCookie(c *gin.Context) {
|
||||
http.SetCookie(c.Writer, &http.Cookie{Name: CookieName, Value: "", Path: "/", MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
|
||||
}
|
||||
|
||||
// Load attaches the session if one exists. It never rejects; use Require for that.
|
||||
func (s *Sessions) Load() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
token, err := c.Cookie(CookieName)
|
||||
if err != nil {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
sess, err := s.Get(c.Request.Context(), token)
|
||||
switch {
|
||||
case errors.Is(err, ErrNoSession):
|
||||
ClearCookie(c)
|
||||
case err != nil:
|
||||
_ = c.Error(err)
|
||||
c.AbortWithStatus(http.StatusServiceUnavailable)
|
||||
return
|
||||
default:
|
||||
c.Set(ctxKey, sess)
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// Require aborts with 401 unless Load attached a session.
|
||||
func Require() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if Current(c) == nil {
|
||||
c.AbortWithStatus(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// CSRF uses the synchronizer token stored in the session. SameSite=Lax alone
|
||||
// does not cover same-site subdomains such as customer status pages.
|
||||
func CSRF() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
switch c.Request.Method {
|
||||
case http.MethodGet, http.MethodHead, http.MethodOptions:
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
// Covers requests without a session (login CSRF) as well.
|
||||
if !sameOrigin(c.Request) {
|
||||
c.AbortWithStatus(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
sess := Current(c)
|
||||
if sess == nil {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
token := c.GetHeader(CSRFHeader)
|
||||
if token == "" {
|
||||
token = c.PostForm(CSRFField)
|
||||
}
|
||||
if !sess.CheckCSRF(token) {
|
||||
c.AbortWithStatus(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func sameOrigin(r *http.Request) bool {
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin == "" || origin == "null" {
|
||||
return origin == ""
|
||||
}
|
||||
u, err := url.Parse(origin)
|
||||
return err == nil && u.Host == r.Host
|
||||
}
|
||||
|
||||
// Current returns the session attached by Load, or nil.
|
||||
func Current(c *gin.Context) *Session {
|
||||
v, ok := c.Get(ctxKey)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return v.(*Session)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestCSRF(t *testing.T) {
|
||||
sess := &Session{CSRF: "good"}
|
||||
tests := []struct {
|
||||
name string
|
||||
sess *Session
|
||||
method string
|
||||
header string
|
||||
origin string
|
||||
form string
|
||||
want int
|
||||
}{
|
||||
{name: "safe method", sess: sess, method: http.MethodGet, want: http.StatusNoContent},
|
||||
{name: "missing token", sess: sess, method: http.MethodPost, want: http.StatusForbidden},
|
||||
{name: "wrong token", sess: sess, method: http.MethodPost, header: "bad", want: http.StatusForbidden},
|
||||
{name: "header token", sess: sess, method: http.MethodPost, header: "good", want: http.StatusNoContent},
|
||||
{name: "form token", sess: sess, method: http.MethodPost, form: "_csrf=good", want: http.StatusNoContent},
|
||||
{name: "no session", method: http.MethodPost, want: http.StatusNoContent},
|
||||
{name: "same origin", method: http.MethodPost, origin: "http://example.com", want: http.StatusNoContent},
|
||||
{name: "foreign origin without session", method: http.MethodPost, origin: "https://evil.test", want: http.StatusForbidden},
|
||||
{name: "foreign origin with token", sess: sess, method: http.MethodPost, header: "good", origin: "https://evil.test", want: http.StatusForbidden},
|
||||
{name: "opaque origin", method: http.MethodPost, origin: "null", want: http.StatusForbidden},
|
||||
}
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) {
|
||||
if tt.sess != nil {
|
||||
c.Set(ctxKey, tt.sess)
|
||||
}
|
||||
}, CSRF())
|
||||
r.Any("/x", func(c *gin.Context) { c.Status(http.StatusNoContent) })
|
||||
|
||||
req := httptest.NewRequest(tt.method, "/x", strings.NewReader(tt.form))
|
||||
if tt.form != "" {
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
if tt.origin != "" {
|
||||
req.Header.Set("Origin", tt.origin)
|
||||
}
|
||||
if tt.header != "" {
|
||||
req.Header.Set(CSRFHeader, tt.header)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != tt.want {
|
||||
t.Errorf("%s /x = %d, want %d", tt.method, w.Code, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
type argonParams struct {
|
||||
memory uint32
|
||||
time uint32
|
||||
threads uint8
|
||||
keyLen uint32
|
||||
}
|
||||
|
||||
// defaultParams is the OWASP baseline for argon2id. Raising it makes
|
||||
// VerifyPassword request a rehash of older hashes on their next login.
|
||||
var defaultParams = argonParams{memory: 19 * 1024, time: 2, threads: 1, keyLen: 32}
|
||||
|
||||
// MinPasswordLength follows NIST SP 800-63B; no composition rules apply.
|
||||
const MinPasswordLength = 12
|
||||
|
||||
// ErrPasswordTooShort is returned by HashPassword.
|
||||
var ErrPasswordTooShort = fmt.Errorf("auth: password must have at least %d characters", MinPasswordLength)
|
||||
|
||||
// HashPassword returns an argon2id hash in PHC string format.
|
||||
func HashPassword(pw string) (string, error) {
|
||||
if len([]rune(pw)) < MinPasswordLength {
|
||||
return "", ErrPasswordTooShort
|
||||
}
|
||||
return hashPassword(pw, defaultParams), nil
|
||||
}
|
||||
|
||||
func hashPassword(pw string, p argonParams) string {
|
||||
salt := make([]byte, 16)
|
||||
_, _ = rand.Read(salt)
|
||||
hash := argon2.IDKey([]byte(pw), salt, p.time, p.memory, p.threads, p.keyLen)
|
||||
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, p.memory, p.time, p.threads,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(hash))
|
||||
}
|
||||
|
||||
// VerifyPassword reports whether pw matches and whether the stored hash uses
|
||||
// outdated parameters and should be replaced on this successful login.
|
||||
func VerifyPassword(encoded, pw string) (ok, rehash bool, err error) {
|
||||
p, salt, want, err := decodeHash(encoded)
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
got := argon2.IDKey([]byte(pw), salt, p.time, p.memory, p.threads, uint32(len(want)))
|
||||
ok = subtle.ConstantTimeCompare(got, want) == 1
|
||||
return ok, ok && p != defaultParams, nil
|
||||
}
|
||||
|
||||
var dummyHash = sync.OnceValue(func() string { return hashPassword("timing-equalizer", defaultParams) })
|
||||
|
||||
// BurnPasswordCheck spends the time of a real verification. Call it when the
|
||||
// account does not exist so response times do not reveal that.
|
||||
func BurnPasswordCheck(pw string) { _, _, _ = VerifyPassword(dummyHash(), pw) }
|
||||
|
||||
func decodeHash(s string) (argonParams, []byte, []byte, error) {
|
||||
var p argonParams
|
||||
parts := strings.Split(s, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return p, nil, nil, errors.New("auth: unsupported password hash")
|
||||
}
|
||||
var v int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &v); err != nil || v != argon2.Version {
|
||||
return p, nil, nil, errors.New("auth: unsupported argon2 version")
|
||||
}
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.memory, &p.time, &p.threads); err != nil {
|
||||
return p, nil, nil, errors.New("auth: malformed password hash")
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return p, nil, nil, errors.New("auth: malformed password hash")
|
||||
}
|
||||
hash, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return p, nil, nil, errors.New("auth: malformed password hash")
|
||||
}
|
||||
p.keyLen = uint32(len(hash))
|
||||
return p, salt, hash, nil
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHashPassword(t *testing.T) {
|
||||
const pw = "correct horse battery"
|
||||
h, err := HashPassword(pw)
|
||||
if err != nil {
|
||||
t.Fatalf("HashPassword(%q) failed: %v", pw, err)
|
||||
}
|
||||
ok, rehash, err := VerifyPassword(h, pw)
|
||||
if err != nil || !ok || rehash {
|
||||
t.Errorf("VerifyPassword(h, %q) = %v, %v, %v; want true, false, nil", pw, ok, rehash, err)
|
||||
}
|
||||
if ok, _, _ := VerifyPassword(h, pw+"x"); ok {
|
||||
t.Errorf("VerifyPassword(h, %q) = true, want false", pw+"x")
|
||||
}
|
||||
if _, err := HashPassword("short"); !errors.Is(err, ErrPasswordTooShort) {
|
||||
t.Errorf("HashPassword(%q) error = %v, want %v", "short", err, ErrPasswordTooShort)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyPasswordRequestsRehashForOldParams(t *testing.T) {
|
||||
const pw = "correct horse battery"
|
||||
weak := argonParams{memory: 8 * 1024, time: 1, threads: 1, keyLen: 32}
|
||||
ok, rehash, err := VerifyPassword(hashPassword(pw, weak), pw)
|
||||
if err != nil || !ok || !rehash {
|
||||
t.Errorf("VerifyPassword(weak hash) = %v, %v, %v; want true, true, nil", ok, rehash, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyPasswordRejectsForeignFormats(t *testing.T) {
|
||||
for _, h := range []string{"", "$2a$10$abc", strings.Replace(dummyHash(), "argon2id", "argon2i", 1)} {
|
||||
if _, _, err := VerifyPassword(h, "x"); err == nil {
|
||||
t.Errorf("VerifyPassword(%q, _) error = nil, want error", h)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// Limiter counts attempts per key in fixed windows stored in Redis.
|
||||
type Limiter struct {
|
||||
rdb redis.UniversalClient
|
||||
}
|
||||
|
||||
// NewLimiter returns a Limiter backed by rdb.
|
||||
func NewLimiter(rdb redis.UniversalClient) *Limiter { return &Limiter{rdb: rdb} }
|
||||
|
||||
var incrWithTTL = redis.NewScript(`
|
||||
local n = redis.call("INCR", KEYS[1])
|
||||
if n == 1 then redis.call("PEXPIRE", KEYS[1], ARGV[1]) end
|
||||
return n`)
|
||||
|
||||
// Allow counts one attempt in a fixed window shared by all replicas.
|
||||
func (l *Limiter) Allow(ctx context.Context, key string, limit int, window time.Duration) (bool, error) {
|
||||
n, err := incrWithTTL.Run(ctx, l.rdb, []string{"rl:" + key}, window.Milliseconds()).Int()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return n <= limit, nil
|
||||
}
|
||||
|
||||
// Reset clears the counter for key, e.g. after a successful login.
|
||||
func (l *Limiter) Reset(ctx context.Context, key string) error {
|
||||
return l.rdb.Del(ctx, "rl:"+key).Err()
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// RecoveryCodeCount is how many codes a user receives per set.
|
||||
const RecoveryCodeCount = 10
|
||||
|
||||
// recoveryAlphabet omits characters that are easily confused on paper
|
||||
// (0/o, 1/l/i).
|
||||
const recoveryAlphabet = "abcdefghjkmnpqrstuvwxyz23456789"
|
||||
|
||||
const recoveryLen = 10
|
||||
|
||||
// NewRecoveryCodes returns RecoveryCodeCount codes formatted as
|
||||
// "xxxxx-xxxxx", about 49 bits each.
|
||||
func NewRecoveryCodes() []string {
|
||||
codes := make([]string, RecoveryCodeCount)
|
||||
for i := range codes {
|
||||
b := make([]byte, recoveryLen)
|
||||
for j := range b {
|
||||
b[j] = recoveryAlphabet[randIndex(len(recoveryAlphabet))]
|
||||
}
|
||||
codes[i] = string(b[:recoveryLen/2]) + "-" + string(b[recoveryLen/2:])
|
||||
}
|
||||
return codes
|
||||
}
|
||||
|
||||
// randIndex returns a uniform index below n using rejection sampling.
|
||||
func randIndex(n int) int {
|
||||
limit := 256 - 256%n
|
||||
var b [1]byte
|
||||
for {
|
||||
_, _ = rand.Read(b[:])
|
||||
if int(b[0]) < limit {
|
||||
return int(b[0]) % n
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NormalizeRecoveryCode strips separators and case so users can type codes
|
||||
// the way they wrote them down. It returns "" if the input cannot be a code.
|
||||
func NormalizeRecoveryCode(s string) string {
|
||||
s = strings.Map(func(r rune) rune {
|
||||
switch r {
|
||||
case '-', ' ':
|
||||
return -1
|
||||
}
|
||||
return r
|
||||
}, strings.ToLower(strings.TrimSpace(s)))
|
||||
if len(s) != recoveryLen {
|
||||
return ""
|
||||
}
|
||||
for _, r := range s {
|
||||
if !strings.ContainsRune(recoveryAlphabet, r) {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// HashRecoveryCode hashes a normalized code. The codes carry enough entropy
|
||||
// that a fast hash suffices; attempts are rate limited.
|
||||
func HashRecoveryCode(normalized string) []byte {
|
||||
sum := sha256.Sum256([]byte(normalized))
|
||||
return sum[:]
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewRecoveryCodes(t *testing.T) {
|
||||
codes := NewRecoveryCodes()
|
||||
if len(codes) != RecoveryCodeCount {
|
||||
t.Fatalf("len(NewRecoveryCodes()) = %d, want %d", len(codes), RecoveryCodeCount)
|
||||
}
|
||||
format := regexp.MustCompile(`^[a-z2-9]{5}-[a-z2-9]{5}$`)
|
||||
seen := map[string]bool{}
|
||||
for _, c := range codes {
|
||||
if !format.MatchString(c) {
|
||||
t.Errorf("code %q does not match %s", c, format)
|
||||
}
|
||||
if NormalizeRecoveryCode(c) == "" {
|
||||
t.Errorf("NormalizeRecoveryCode(%q) = \"\", want the code", c)
|
||||
}
|
||||
if seen[c] {
|
||||
t.Errorf("duplicate code %q", c)
|
||||
}
|
||||
seen[c] = true
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRecoveryCode(t *testing.T) {
|
||||
tests := []struct{ in, want string }{
|
||||
{"abcde-fghjk", "abcdefghjk"},
|
||||
{" ABCDE FGHJK ", "abcdefghjk"},
|
||||
{"abcdefghjk", "abcdefghjk"},
|
||||
{"123456", ""},
|
||||
{"abcde-fghj0", ""},
|
||||
{"abcde-fghjkm", ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := NormalizeRecoveryCode(tt.in); got != tt.want {
|
||||
t.Errorf("NormalizeRecoveryCode(%q) = %q, want %q", tt.in, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
// Package auth implements sessions, password and TOTP verification, rate
|
||||
// limiting and CSRF protection.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// ErrNoSession is returned for unknown, expired or malformed sessions.
|
||||
var ErrNoSession = errors.New("auth: no session")
|
||||
|
||||
// Session is a signed-in browser. Token is the cookie value and never
|
||||
// stored server side.
|
||||
type Session struct {
|
||||
Token string
|
||||
UserID uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
Locale string
|
||||
CSRF string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// CheckCSRF compares token with the session's CSRF token in constant time.
|
||||
func (s *Session) CheckCSRF(token string) bool {
|
||||
return token != "" && subtle.ConstantTimeCompare([]byte(token), []byte(s.CSRF)) == 1
|
||||
}
|
||||
|
||||
// Sessions stores sessions in Redis so any API replica can serve any request.
|
||||
type Sessions struct {
|
||||
rdb redis.UniversalClient
|
||||
idle time.Duration
|
||||
absolute time.Duration
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// NewSessions returns a store whose sessions expire after idle without use
|
||||
// and after absolute regardless of use.
|
||||
func NewSessions(rdb redis.UniversalClient, idle, absolute time.Duration) *Sessions {
|
||||
return &Sessions{rdb: rdb, idle: idle, absolute: absolute, now: time.Now}
|
||||
}
|
||||
|
||||
// Only the hash of the token is stored, so a leaked Redis dump does not
|
||||
// contain usable session cookies.
|
||||
func key(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return "session:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func userIndex(id uuid.UUID) string { return "user_sessions:" + id.String() }
|
||||
|
||||
// RandomToken returns 256 bits of randomness, URL-safe encoded.
|
||||
func RandomToken() string {
|
||||
b := make([]byte, 32)
|
||||
_, _ = rand.Read(b)
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
// Create starts a session. org and locale may be empty.
|
||||
func (s *Sessions) Create(ctx context.Context, user, org uuid.UUID, locale string) (*Session, error) {
|
||||
sess := &Session{
|
||||
Token: RandomToken(),
|
||||
UserID: user,
|
||||
OrgID: org,
|
||||
Locale: locale,
|
||||
CSRF: RandomToken(),
|
||||
CreatedAt: s.now(),
|
||||
}
|
||||
k := key(sess.Token)
|
||||
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
|
||||
p.HSet(ctx, k, map[string]any{
|
||||
"user": sess.UserID.String(),
|
||||
"org": orgString(org),
|
||||
"locale": locale,
|
||||
"csrf": sess.CSRF,
|
||||
"created": sess.CreatedAt.Unix(),
|
||||
})
|
||||
p.Expire(ctx, k, s.idle)
|
||||
p.SAdd(ctx, userIndex(user), k)
|
||||
p.Expire(ctx, userIndex(user), s.absolute)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("auth: create session: %w", err)
|
||||
}
|
||||
return sess, nil
|
||||
}
|
||||
|
||||
// Get loads the session for token and extends its idle expiry.
|
||||
func (s *Sessions) Get(ctx context.Context, token string) (*Session, error) {
|
||||
if token == "" {
|
||||
return nil, ErrNoSession
|
||||
}
|
||||
k := key(token)
|
||||
vals, err := s.rdb.HGetAll(ctx, k).Result()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("auth: load session: %w", err)
|
||||
}
|
||||
if len(vals) == 0 {
|
||||
return nil, ErrNoSession
|
||||
}
|
||||
sess, err := decode(token, vals)
|
||||
if err != nil {
|
||||
_ = s.rdb.Del(ctx, k).Err()
|
||||
return nil, ErrNoSession
|
||||
}
|
||||
if s.now().Sub(sess.CreatedAt) > s.absolute {
|
||||
_ = s.Delete(ctx, sess)
|
||||
return nil, ErrNoSession
|
||||
}
|
||||
// Sliding expiry, but never beyond the absolute lifetime.
|
||||
remaining := s.absolute - s.now().Sub(sess.CreatedAt)
|
||||
if err := s.rdb.Expire(ctx, k, min(s.idle, remaining)).Err(); err != nil {
|
||||
return nil, fmt.Errorf("auth: touch session: %w", err)
|
||||
}
|
||||
return sess, nil
|
||||
}
|
||||
|
||||
// SwitchOrg changes the active organization. Membership must be checked
|
||||
// by the caller.
|
||||
func (s *Sessions) SwitchOrg(ctx context.Context, sess *Session, org uuid.UUID) error {
|
||||
if err := s.rdb.HSet(ctx, key(sess.Token), "org", orgString(org)).Err(); err != nil {
|
||||
return fmt.Errorf("auth: switch org: %w", err)
|
||||
}
|
||||
sess.OrgID = org
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetLocale changes the session language.
|
||||
func (s *Sessions) SetLocale(ctx context.Context, sess *Session, locale string) error {
|
||||
if err := s.rdb.HSet(ctx, key(sess.Token), "locale", locale).Err(); err != nil {
|
||||
return fmt.Errorf("auth: set locale: %w", err)
|
||||
}
|
||||
sess.Locale = locale
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete ends sess.
|
||||
func (s *Sessions) Delete(ctx context.Context, sess *Session) error {
|
||||
k := key(sess.Token)
|
||||
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
|
||||
p.Del(ctx, k)
|
||||
p.SRem(ctx, userIndex(sess.UserID), k)
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteAllForUser ends every session of a user, e.g. after a password change
|
||||
// or when an admin disables the account.
|
||||
func (s *Sessions) DeleteAllForUser(ctx context.Context, user uuid.UUID) error {
|
||||
idx := userIndex(user)
|
||||
keys, err := s.rdb.SMembers(ctx, idx).Result()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
|
||||
if len(keys) > 0 {
|
||||
p.Del(ctx, keys...)
|
||||
}
|
||||
p.Del(ctx, idx)
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func decode(token string, v map[string]string) (*Session, error) {
|
||||
user, err := uuid.Parse(v["user"])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var org uuid.UUID
|
||||
if v["org"] != "" {
|
||||
if org, err = uuid.Parse(v["org"]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
created, err := strconv.ParseInt(v["created"], 10, 64)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Session{Token: token, UserID: user, OrgID: org, Locale: v["locale"], CSRF: v["csrf"], CreatedAt: time.Unix(created, 0)}, nil
|
||||
}
|
||||
|
||||
func orgString(id uuid.UUID) string {
|
||||
if id == uuid.Nil {
|
||||
return ""
|
||||
}
|
||||
return id.String()
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func newTestRedis(t *testing.T) *redis.Client {
|
||||
t.Helper()
|
||||
url := os.Getenv("UPTIME_TEST_REDIS_URL")
|
||||
if url == "" {
|
||||
t.Skip("UPTIME_TEST_REDIS_URL not set")
|
||||
}
|
||||
opts, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
t.Fatalf("redis.ParseURL(%q) failed: %v", url, err)
|
||||
}
|
||||
rdb := redis.NewClient(opts)
|
||||
t.Cleanup(func() { _ = rdb.Close() })
|
||||
return rdb
|
||||
}
|
||||
|
||||
func newTestSessions(t *testing.T) (*Sessions, *time.Time) {
|
||||
t.Helper()
|
||||
now := time.Now()
|
||||
s := NewSessions(newTestRedis(t), time.Hour, 24*time.Hour)
|
||||
s.now = func() time.Time { return now }
|
||||
return s, &now
|
||||
}
|
||||
|
||||
func mustCreate(t *testing.T, s *Sessions, user uuid.UUID) *Session {
|
||||
t.Helper()
|
||||
sess, err := s.Create(context.Background(), user, uuid.Nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("Create() failed: %v", err)
|
||||
}
|
||||
return sess
|
||||
}
|
||||
|
||||
func TestSessionRoundTrip(t *testing.T) {
|
||||
s, _ := newTestSessions(t)
|
||||
ctx := context.Background()
|
||||
user, org := uuid.New(), uuid.New()
|
||||
|
||||
created, err := s.Create(ctx, user, org, "de")
|
||||
if err != nil {
|
||||
t.Fatalf("Create() failed: %v", err)
|
||||
}
|
||||
got, err := s.Get(ctx, created.Token)
|
||||
if err != nil {
|
||||
t.Fatalf("Get() failed: %v", err)
|
||||
}
|
||||
if got.UserID != user || got.OrgID != org || got.Locale != "de" || got.CSRF != created.CSRF {
|
||||
t.Errorf("Get() = %+v, want user %v org %v locale de csrf %q", got, user, org, created.CSRF)
|
||||
}
|
||||
for token, want := range map[string]bool{created.CSRF: true, "": false, "x": false} {
|
||||
if ok := got.CheckCSRF(token); ok != want {
|
||||
t.Errorf("CheckCSRF(%q) = %t, want %t", token, ok, want)
|
||||
}
|
||||
}
|
||||
if err := s.Delete(ctx, got); err != nil {
|
||||
t.Fatalf("Delete() failed: %v", err)
|
||||
}
|
||||
if _, err := s.Get(ctx, created.Token); !errors.Is(err, ErrNoSession) {
|
||||
t.Errorf("Get(deleted) error = %v, want %v", err, ErrNoSession)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionAbsoluteLifetime(t *testing.T) {
|
||||
s, now := newTestSessions(t)
|
||||
sess := mustCreate(t, s, uuid.New())
|
||||
*now = now.Add(25 * time.Hour)
|
||||
if _, err := s.Get(context.Background(), sess.Token); !errors.Is(err, ErrNoSession) {
|
||||
t.Errorf("Get(after absolute lifetime) error = %v, want %v", err, ErrNoSession)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteAllForUser(t *testing.T) {
|
||||
s, _ := newTestSessions(t)
|
||||
ctx := context.Background()
|
||||
user := uuid.New()
|
||||
a, b := mustCreate(t, s, user), mustCreate(t, s, user)
|
||||
other := mustCreate(t, s, uuid.New())
|
||||
|
||||
if err := s.DeleteAllForUser(ctx, user); err != nil {
|
||||
t.Fatalf("DeleteAllForUser() failed: %v", err)
|
||||
}
|
||||
for _, sess := range []*Session{a, b} {
|
||||
if _, err := s.Get(ctx, sess.Token); !errors.Is(err, ErrNoSession) {
|
||||
t.Errorf("Get(session of removed user) error = %v, want %v", err, ErrNoSession)
|
||||
}
|
||||
}
|
||||
if _, err := s.Get(ctx, other.Token); err != nil {
|
||||
t.Errorf("Get(session of other user) error = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenIsNotStoredInPlain(t *testing.T) {
|
||||
s, _ := newTestSessions(t)
|
||||
sess := mustCreate(t, s, uuid.New())
|
||||
if n, err := s.rdb.Exists(context.Background(), "session:"+sess.Token).Result(); err != nil || n != 0 {
|
||||
t.Errorf("EXISTS session:<raw token> = %d, %v; want 0, nil", n, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/pquerna/otp"
|
||||
"github.com/pquerna/otp/totp"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const totpIssuer = "uptimesebi"
|
||||
|
||||
// NewTOTPKey generates a secret for account using the defaults every common
|
||||
// authenticator app supports (SHA-1, 6 digits, 30 s).
|
||||
func NewTOTPKey(account string) (*otp.Key, error) {
|
||||
return totp.Generate(totp.GenerateOpts{Issuer: totpIssuer, AccountName: account})
|
||||
}
|
||||
|
||||
// TOTPVerifier rejects a code that was already accepted once, so an observed
|
||||
// code cannot be replayed within its validity window.
|
||||
type TOTPVerifier struct {
|
||||
rdb redis.UniversalClient
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// NewTOTPVerifier returns a verifier that records used codes in rdb.
|
||||
func NewTOTPVerifier(rdb redis.UniversalClient) *TOTPVerifier {
|
||||
return &TOTPVerifier{rdb: rdb, now: time.Now}
|
||||
}
|
||||
|
||||
// Verify accepts code for secret within one step of clock skew, at most once
|
||||
// per user.
|
||||
func (v *TOTPVerifier) Verify(ctx context.Context, user uuid.UUID, secret, code string) (bool, error) {
|
||||
ok, err := totp.ValidateCustom(code, secret, v.now(), totp.ValidateOpts{
|
||||
Period: 30, Skew: 1, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1,
|
||||
})
|
||||
if err != nil || !ok {
|
||||
return false, nil
|
||||
}
|
||||
fresh, err := v.rdb.SetNX(ctx, "totp_used:"+user.String()+":"+code, 1, 2*time.Minute).Result()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return fresh, nil
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/pquerna/otp/totp"
|
||||
)
|
||||
|
||||
func TestTOTPVerifierRejectsReplay(t *testing.T) {
|
||||
key, err := NewTOTPKey("a@example.test")
|
||||
if err != nil {
|
||||
t.Fatalf("NewTOTPKey() failed: %v", err)
|
||||
}
|
||||
now := time.Now()
|
||||
code, err := totp.GenerateCode(key.Secret(), now)
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateCode() failed: %v", err)
|
||||
}
|
||||
v := NewTOTPVerifier(newTestRedis(t))
|
||||
v.now = func() time.Time { return now }
|
||||
user := uuid.New()
|
||||
ctx := context.Background()
|
||||
|
||||
if ok, err := v.Verify(ctx, user, key.Secret(), code); !ok || err != nil {
|
||||
t.Errorf("Verify(fresh code) = %t, %v; want true, nil", ok, err)
|
||||
}
|
||||
if ok, err := v.Verify(ctx, user, key.Secret(), code); ok || err != nil {
|
||||
t.Errorf("Verify(replayed code) = %t, %v; want false, nil", ok, err)
|
||||
}
|
||||
wrong := "000000"
|
||||
if wrong == code {
|
||||
wrong = "000001"
|
||||
}
|
||||
if ok, err := v.Verify(ctx, user, key.Secret(), wrong); ok || err != nil {
|
||||
t.Errorf("Verify(wrong code) = %t, %v; want false, nil", ok, err)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
// Package buildinfo exposes release metadata injected via -ldflags -X.
|
||||
package buildinfo
|
||||
|
||||
// Set by the release build; see Makefile and Dockerfile.
|
||||
var (
|
||||
// Version is the release tag, or "dev" for local builds.
|
||||
Version = "dev"
|
||||
Commit = "none"
|
||||
// Commit is the short git revision the binary was built from.
|
||||
Commit = "none"
|
||||
)
|
||||
@@ -1,20 +1,28 @@
|
||||
// Package config reads component settings from UPTIME_* environment
|
||||
// variables.
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/caarlos0/env/v11"
|
||||
)
|
||||
|
||||
// Edition switches features that only make sense when we operate the
|
||||
// service, such as billing.
|
||||
type Edition string
|
||||
|
||||
// Editions.
|
||||
const (
|
||||
EditionCloud Edition = "cloud"
|
||||
EditionSelfHosted Edition = "selfhosted"
|
||||
)
|
||||
|
||||
// Common holds settings shared by all components.
|
||||
type Common struct {
|
||||
Edition Edition `env:"UPTIME_EDITION" envDefault:"selfhosted"`
|
||||
LogLevel slog.Level `env:"UPTIME_LOG_LEVEL" envDefault:"info"`
|
||||
@@ -33,24 +41,88 @@ type Sentinel struct {
|
||||
Password string `env:"UPTIME_REDIS_SENTINEL_PASSWORD"`
|
||||
}
|
||||
|
||||
// Enabled reports whether a sentinel master name is configured.
|
||||
func (s Sentinel) Enabled() bool { return s.Master != "" }
|
||||
|
||||
// SignupMode controls who may create an account and organization.
|
||||
type SignupMode string
|
||||
|
||||
// Signup modes. SignupFirstUser allows exactly one account, the operator of a
|
||||
// fresh self-hosted installation.
|
||||
const (
|
||||
SignupOpen SignupMode = "open"
|
||||
SignupFirstUser SignupMode = "first-user"
|
||||
SignupClosed SignupMode = "closed"
|
||||
)
|
||||
|
||||
// API configures cmd/api.
|
||||
type API struct {
|
||||
Common
|
||||
Listen string `env:"UPTIME_API_LISTEN" envDefault:":8080"`
|
||||
Listen string `env:"UPTIME_API_LISTEN" envDefault:":8080"`
|
||||
SecretKeys string `env:"UPTIME_SECRET_KEYS"`
|
||||
Signup SignupMode `env:"UPTIME_SIGNUP" envDefault:"first-user"`
|
||||
SessionIdle time.Duration `env:"UPTIME_SESSION_IDLE" envDefault:"168h"`
|
||||
SessionAbsolute time.Duration `env:"UPTIME_SESSION_ABSOLUTE" envDefault:"720h"`
|
||||
// PublicURL is the externally reachable base URL, used for SSO callbacks.
|
||||
PublicURL string `env:"UPTIME_PUBLIC_URL" envDefault:"http://localhost:8080"`
|
||||
// SSOPrivateNetworks is "auto", "true" or "false". Auto allows
|
||||
// organizations' IdPs on private networks only in the self-hosted edition.
|
||||
SSOPrivateNetworks string `env:"UPTIME_SSO_ALLOW_PRIVATE_NETWORKS" envDefault:"auto"`
|
||||
}
|
||||
|
||||
// SSOAllowPrivate resolves SSOPrivateNetworks.
|
||||
func (a API) SSOAllowPrivate() bool {
|
||||
switch a.SSOPrivateNetworks {
|
||||
case "true":
|
||||
return true
|
||||
case "false":
|
||||
return false
|
||||
}
|
||||
return a.Edition == EditionSelfHosted
|
||||
}
|
||||
|
||||
// Validate checks API-specific settings in addition to Common.Validate.
|
||||
func (a API) Validate() error {
|
||||
if err := a.Common.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if a.SecretKeys == "" {
|
||||
return fmt.Errorf("config: UPTIME_SECRET_KEYS is required (format id:base64-32-bytes)")
|
||||
}
|
||||
switch a.Signup {
|
||||
case SignupOpen, SignupFirstUser, SignupClosed:
|
||||
default:
|
||||
return fmt.Errorf("config: unknown UPTIME_SIGNUP %q", a.Signup)
|
||||
}
|
||||
switch a.SSOPrivateNetworks {
|
||||
case "auto", "true", "false":
|
||||
default:
|
||||
return fmt.Errorf("config: UPTIME_SSO_ALLOW_PRIVATE_NETWORKS must be auto, true or false")
|
||||
}
|
||||
if u, err := url.Parse(a.PublicURL); err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http") || strings.HasSuffix(a.PublicURL, "/") {
|
||||
return fmt.Errorf("config: UPTIME_PUBLIC_URL must be an absolute http(s) URL without trailing slash")
|
||||
}
|
||||
if a.SessionIdle <= 0 || a.SessionAbsolute < a.SessionIdle {
|
||||
return fmt.Errorf("config: UPTIME_SESSION_ABSOLUTE must be >= UPTIME_SESSION_IDLE > 0")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Checker configures cmd/checker. Region names the location this instance
|
||||
// checks from and must match the regions assigned to monitors.
|
||||
type Checker struct {
|
||||
Common
|
||||
Region string `env:"UPTIME_CHECKER_REGION,required"`
|
||||
Region string `env:"UPTIME_CHECKER_REGION,required,notEmpty"`
|
||||
HealthListen string `env:"UPTIME_CHECKER_HEALTH_LISTEN" envDefault:":8081"`
|
||||
}
|
||||
|
||||
// StatusPage configures cmd/statuspage.
|
||||
type StatusPage struct {
|
||||
Common
|
||||
Listen string `env:"UPTIME_STATUSPAGE_LISTEN" envDefault:":8082"`
|
||||
}
|
||||
|
||||
// Load parses the environment into a T, applying envDefault tags.
|
||||
func Load[T any]() (T, error) {
|
||||
var cfg T
|
||||
if err := env.Parse(&cfg); err != nil {
|
||||
@@ -59,6 +131,7 @@ func Load[T any]() (T, error) {
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// Validate reports missing or contradictory settings.
|
||||
func (c Common) Validate() error {
|
||||
switch c.Edition {
|
||||
case EditionCloud, EditionSelfHosted:
|
||||
|
||||
@@ -2,24 +2,24 @@ package config
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestValidateRedisModes(t *testing.T) {
|
||||
base := Common{Edition: EditionSelfHosted, DatabaseURL: "postgres://x"}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
mod func(*Common)
|
||||
ok bool
|
||||
func TestCommonValidateRedisModes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
modify func(*Common)
|
||||
wantErr bool
|
||||
}{
|
||||
{"standalone", func(c *Common) { c.RedisURL = "redis://r" }, true},
|
||||
{"nothing", func(c *Common) {}, false},
|
||||
{"sentinel", func(c *Common) { c.RedisSentinel = Sentinel{Master: "m", Addrs: []string{"s:26379"}} }, true},
|
||||
{"sentinel without addrs", func(c *Common) { c.RedisSentinel = Sentinel{Master: "m"} }, false},
|
||||
{"standalone", func(c *Common) { c.RedisURL = "redis://r" }, false},
|
||||
{"no redis", func(*Common) {}, true},
|
||||
{"sentinel", func(c *Common) { c.RedisSentinel = Sentinel{Master: "m", Addrs: []string{"s:26379"}} }, false},
|
||||
{"sentinel without addrs", func(c *Common) { c.RedisSentinel = Sentinel{Master: "m"} }, true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
c := base
|
||||
tc.mod(&c)
|
||||
if err := c.Validate(); (err == nil) != tc.ok {
|
||||
t.Errorf("%s: err=%v", tc.name, err)
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c := Common{Edition: EditionSelfHosted, DatabaseURL: "postgres://x"}
|
||||
tt.modify(&c)
|
||||
if err := c.Validate(); (err != nil) != tt.wantErr {
|
||||
t.Errorf("Validate() = %v, want error: %t", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
// Package i18n translates user-facing text. Message catalogs are embedded
|
||||
// JSON files, one per language, keyed by message ID. English is the source
|
||||
// language and the fallback for missing translations.
|
||||
package i18n
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
goi18n "github.com/nicksnyder/go-i18n/v2/i18n"
|
||||
"golang.org/x/text/language"
|
||||
)
|
||||
|
||||
//go:embed locales/*.json
|
||||
var locales embed.FS
|
||||
|
||||
// Catalog holds all translations and picks the best supported language for
|
||||
// a list of preferences.
|
||||
type Catalog struct {
|
||||
bundle *goi18n.Bundle
|
||||
tags []language.Tag
|
||||
matcher language.Matcher
|
||||
}
|
||||
|
||||
// Load parses the embedded catalogs. English is always listed first so the
|
||||
// matcher falls back to it.
|
||||
func Load() (*Catalog, error) {
|
||||
b := goi18n.NewBundle(language.English)
|
||||
b.RegisterUnmarshalFunc("json", json.Unmarshal)
|
||||
files, err := fs.Glob(locales, "locales/*.json")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tags := []language.Tag{language.English}
|
||||
for _, f := range files {
|
||||
data, err := locales.ReadFile(f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mf, err := b.ParseMessageFileBytes(data, path.Base(f))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("i18n: parse %s: %w", f, err)
|
||||
}
|
||||
if mf.Tag != language.English {
|
||||
tags = append(tags, mf.Tag)
|
||||
}
|
||||
}
|
||||
return &Catalog{bundle: b, tags: tags, matcher: language.NewMatcher(tags)}, nil
|
||||
}
|
||||
|
||||
// Supported returns the base language codes, e.g. "en" and "de".
|
||||
func (c *Catalog) Supported() []string {
|
||||
out := make([]string, len(c.tags))
|
||||
for i, t := range c.tags {
|
||||
out[i] = t.String()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// IsSupported reports whether code names one of the catalog languages exactly.
|
||||
func (c *Catalog) IsSupported(code string) bool {
|
||||
for _, t := range c.tags {
|
||||
if t.String() == code {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Match picks a language from preferences in priority order. Each entry may
|
||||
// be a single code or an Accept-Language header value; empty entries are
|
||||
// skipped.
|
||||
func (c *Catalog) Match(prefs ...string) *Localizer {
|
||||
for _, p := range prefs {
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
tags, _, err := language.ParseAcceptLanguage(p)
|
||||
if err != nil || len(tags) == 0 {
|
||||
continue
|
||||
}
|
||||
if _, idx, conf := c.matcher.Match(tags...); conf > language.No {
|
||||
return c.localizer(c.tags[idx])
|
||||
}
|
||||
}
|
||||
return c.localizer(language.English)
|
||||
}
|
||||
|
||||
func (c *Catalog) localizer(t language.Tag) *Localizer {
|
||||
return &Localizer{lang: t.String(), l: goi18n.NewLocalizer(c.bundle, t.String())}
|
||||
}
|
||||
|
||||
// Localizer translates into one language.
|
||||
type Localizer struct {
|
||||
lang string
|
||||
l *goi18n.Localizer
|
||||
}
|
||||
|
||||
// Lang returns the language code, suitable for <html lang>.
|
||||
func (l *Localizer) Lang() string { return l.lang }
|
||||
|
||||
// T translates id. data fills template placeholders such as {{.Min}}; an
|
||||
// integer "Count" entry also selects the plural form. A missing ID is
|
||||
// returned unchanged so it stands out instead of rendering empty text.
|
||||
func (l *Localizer) T(id string, data map[string]any) string {
|
||||
cfg := &goi18n.LocalizeConfig{MessageID: id, TemplateData: data}
|
||||
if n, ok := data["Count"].(int); ok {
|
||||
cfg.PluralCount = n
|
||||
}
|
||||
s, err := l.l.Localize(cfg)
|
||||
if err != nil && s == "" {
|
||||
return id
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
type ctxKey struct{}
|
||||
|
||||
// NewContext returns ctx carrying l.
|
||||
func NewContext(ctx context.Context, l *Localizer) context.Context {
|
||||
return context.WithValue(ctx, ctxKey{}, l)
|
||||
}
|
||||
|
||||
// FromContext returns the localizer in ctx, or nil.
|
||||
func FromContext(ctx context.Context) *Localizer {
|
||||
l, _ := ctx.Value(ctxKey{}).(*Localizer)
|
||||
return l
|
||||
}
|
||||
|
||||
// T translates id with the localizer in ctx. It is the entry point for
|
||||
// templates, which always have ctx in scope.
|
||||
func T(ctx context.Context, id string, kv ...any) string {
|
||||
l := FromContext(ctx)
|
||||
if l == nil {
|
||||
return id
|
||||
}
|
||||
return l.T(id, pairs(kv))
|
||||
}
|
||||
|
||||
// Lang returns the language of the localizer in ctx, defaulting to "en".
|
||||
func Lang(ctx context.Context) string {
|
||||
if l := FromContext(ctx); l != nil {
|
||||
return l.Lang()
|
||||
}
|
||||
return "en"
|
||||
}
|
||||
|
||||
func pairs(kv []any) map[string]any {
|
||||
if len(kv) == 0 {
|
||||
return nil
|
||||
}
|
||||
m := make(map[string]any, len(kv)/2)
|
||||
for i := 0; i+1 < len(kv); i += 2 {
|
||||
if k, ok := kv[i].(string); ok {
|
||||
m[strings.TrimSpace(k)] = kv[i+1]
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package i18n
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func catalogKeys(t *testing.T) map[string]map[string]bool {
|
||||
t.Helper()
|
||||
files, err := fs.Glob(locales, "locales/*.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := map[string]map[string]bool{}
|
||||
for _, f := range files {
|
||||
data, err := locales.ReadFile(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal(data, &m); err != nil {
|
||||
t.Fatalf("%s: %v", f, err)
|
||||
}
|
||||
keys := map[string]bool{}
|
||||
for k := range m {
|
||||
keys[k] = true
|
||||
}
|
||||
out[strings.TrimSuffix(filepath.Base(f), ".json")] = keys
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestCatalogsHaveSameKeys(t *testing.T) {
|
||||
cats := catalogKeys(t)
|
||||
en := cats["en"]
|
||||
for lang, keys := range cats {
|
||||
for k := range en {
|
||||
if !keys[k] {
|
||||
t.Errorf("%s.json is missing %q", lang, k)
|
||||
}
|
||||
}
|
||||
for k := range keys {
|
||||
if !en[k] {
|
||||
t.Errorf("%s.json has %q which en.json lacks", lang, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var usagePatterns = []struct {
|
||||
re *regexp.Regexp
|
||||
prefix string
|
||||
}{
|
||||
{regexp.MustCompile(`i18n\.T\(ctx, "([a-z0-9_.]+)"[,)]`), ""},
|
||||
{regexp.MustCompile(`\bfail\(c, [^,]+, "([a-z_]+)"`), "error."},
|
||||
{regexp.MustCompile(`\b(?:pageFor\(c|s\.page\()(?:, )?"([a-z0-9_.]+)"`), ""},
|
||||
{regexp.MustCompile(`[^(]"(sso_[a-z_]+)"`), "error."},
|
||||
{regexp.MustCompile(`return "(invalid_[a-z_]+)"`), "error."},
|
||||
{regexp.MustCompile(`NoticeID = "([a-z0-9_.]+)"`), ""},
|
||||
}
|
||||
|
||||
// TestUsedKeysExist scans the source tree for literal message IDs so a typo
|
||||
// fails the build instead of showing a raw ID in production.
|
||||
func TestUsedKeysExist(t *testing.T) {
|
||||
en := catalogKeys(t)["en"]
|
||||
var missing []string
|
||||
err := filepath.WalkDir("..", func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil || d.IsDir() {
|
||||
return err
|
||||
}
|
||||
if !strings.HasSuffix(p, ".go") && !strings.HasSuffix(p, ".templ") {
|
||||
return nil
|
||||
}
|
||||
if strings.HasSuffix(p, "_templ.go") || strings.HasSuffix(p, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
src, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, u := range usagePatterns {
|
||||
for _, m := range u.re.FindAllStringSubmatch(string(src), -1) {
|
||||
if id := u.prefix + m[1]; !en[id] {
|
||||
missing = append(missing, p+": "+id)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sort.Strings(missing)
|
||||
for _, m := range missing {
|
||||
t.Errorf("unknown message ID %s", m)
|
||||
}
|
||||
}
|
||||
|
||||
// The language switcher builds "lang.<code>" dynamically.
|
||||
func TestEveryLanguageHasAName(t *testing.T) {
|
||||
c, err := Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
en := catalogKeys(t)["en"]
|
||||
for _, l := range c.Supported() {
|
||||
if !en["lang."+l] {
|
||||
t.Errorf("en.json is missing %q", "lang."+l)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatch(t *testing.T) {
|
||||
c, err := Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tests := []struct {
|
||||
prefs []string
|
||||
want string
|
||||
}{
|
||||
{nil, "en"},
|
||||
{[]string{"de"}, "de"},
|
||||
{[]string{"", "de-AT,en;q=0.5"}, "de"},
|
||||
{[]string{"fr-FR,fr;q=0.9"}, "en"},
|
||||
{[]string{"en", "de"}, "en"},
|
||||
{[]string{"garbage", "de"}, "de"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := c.Match(tt.prefs...).Lang(); got != tt.want {
|
||||
t.Errorf("Match(%q) = %q, want %q", tt.prefs, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestT(t *testing.T) {
|
||||
c, err := Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := NewContext(context.Background(), c.Match("de"))
|
||||
if got, want := T(ctx, "error.password_too_short", "Min", 12), "Das Passwort braucht mindestens 12 Zeichen."; got != want {
|
||||
t.Errorf("T(de, password_too_short) = %q, want %q", got, want)
|
||||
}
|
||||
for n, want := range map[int]string{1: "1 Wiederherstellungscode übrig", 3: "3 Wiederherstellungscodes übrig"} {
|
||||
if got := T(ctx, "security.recovery.left", "Count", n); got != want {
|
||||
t.Errorf("T(de, recovery.left, %d) = %q, want %q", n, got, want)
|
||||
}
|
||||
}
|
||||
if got, want := T(ctx, "no.such.key"), "no.such.key"; got != want {
|
||||
t.Errorf("T(missing) = %q, want %q", got, want)
|
||||
}
|
||||
if got, want := T(context.Background(), "auth.login.title"), "auth.login.title"; got != want {
|
||||
t.Errorf("T(no localizer) = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
{
|
||||
"app.network_error": "Verbindung fehlgeschlagen.",
|
||||
"auth.field.code": "Code",
|
||||
"auth.field.email": "E-Mail",
|
||||
"auth.field.name": "Name",
|
||||
"auth.field.new_password": "Passwort (min. {{.Min}} Zeichen)",
|
||||
"auth.field.org_name": "Organisation",
|
||||
"auth.field.org_slug": "Kurzname (a–z, 0–9, -)",
|
||||
"auth.field.password": "Passwort",
|
||||
"auth.login.no_account": "Noch kein Konto?",
|
||||
"auth.login.submit": "Weiter",
|
||||
"auth.login.title": "Anmelden",
|
||||
"auth.login.to_signup": "Registrieren",
|
||||
"auth.login.totp_hint": "Code aus der Authenticator-App oder einen Wiederherstellungscode eingeben.",
|
||||
"auth.signup.submit": "Anlegen",
|
||||
"auth.signup.title": "Konto anlegen",
|
||||
"auth.signup.to_login": "Zur Anmeldung",
|
||||
"auth.sso.heading": "Single Sign-on",
|
||||
"auth.sso.org_placeholder": "Kurzname der Organisation",
|
||||
"auth.sso.submit": "Weiter",
|
||||
"common.no": "nein",
|
||||
"common.save": "Speichern",
|
||||
"common.yes": "ja",
|
||||
"console.monitors.empty": "Noch keine Monitore angelegt.",
|
||||
"console.monitors.title": "Monitore",
|
||||
"console.nav.logout": "Abmelden",
|
||||
"console.nav.security": "Sicherheit",
|
||||
"console.nav.sso": "SSO",
|
||||
"console.totp_missing": "Deine Organisation verlangt Zwei-Faktor-Anmeldung.",
|
||||
"console.totp_missing_action": "Jetzt einrichten",
|
||||
"error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.",
|
||||
"error.forbidden": "Dafür fehlt dir die Berechtigung.",
|
||||
"error.internal": "Interner Fehler.",
|
||||
"error.invalid_code": "Code ungültig.",
|
||||
"error.invalid_credentials": "E-Mail oder Passwort falsch.",
|
||||
"error.invalid_domain": "Eine der Domains ist ungültig.",
|
||||
"error.invalid_input": "Eingaben prüfen.",
|
||||
"error.invalid_slug": "Kurzname: 2–63 Zeichen, a–z, 0–9 und Bindestrich.",
|
||||
"error.mfa_expired": "Anmeldung abgelaufen, bitte erneut anmelden.",
|
||||
"error.no_password": "Konto ohne Passwort.",
|
||||
"error.not_found": "Nicht gefunden.",
|
||||
"error.org_not_found": "Organisation nicht gefunden.",
|
||||
"error.password_too_short": "Das Passwort braucht mindestens {{.Min}} Zeichen.",
|
||||
"error.rate_limited": "Zu viele Versuche, bitte später erneut.",
|
||||
"error.signup_closed": "Registrierung ist deaktiviert.",
|
||||
"error.slug_taken": "Dieser Kurzname ist bereits vergeben.",
|
||||
"error.sso_denied": "Die Anmeldung wurde beim Identity Provider abgebrochen.",
|
||||
"error.sso_discovery_failed": "Der Identity Provider ist nicht erreichbar oder lieferte keine gültige Konfiguration.",
|
||||
"error.sso_expired": "Der Anmeldeversuch ist abgelaufen, bitte neu starten.",
|
||||
"error.sso_forbidden_address": "Der Issuer zeigt auf eine nicht öffentliche Adresse.",
|
||||
"error.sso_identity_taken": "Diese SSO-Anmeldung ist bereits mit einem anderen Konto verknüpft.",
|
||||
"error.sso_invalid_issuer": "Der Issuer muss eine https-URL ohne Query und Zugangsdaten sein.",
|
||||
"error.sso_link_required": "Es gibt bereits ein Konto mit dieser E-Mail. Melde dich mit Passwort an und verknüpfe SSO unter Sicherheit.",
|
||||
"error.sso_not_member": "Dein Konto ist kein Mitglied dieser Organisation.",
|
||||
"error.sso_not_provisioned": "Für diese Anmeldung gibt es kein Konto. Bitte lass dich von einem Admin einladen.",
|
||||
"error.sso_provider_error": "Der Identity Provider konnte die Anmeldung nicht abschließen.",
|
||||
"error.sso_unavailable": "Für diese Organisation ist kein Single Sign-on verfügbar.",
|
||||
"error.totp_already_enabled": "TOTP ist bereits aktiv.",
|
||||
"error.totp_required_by_org": "Eine deiner Organisationen verlangt TOTP.",
|
||||
"error.totp_setup_expired": "Einrichtung abgelaufen, bitte neu starten.",
|
||||
"error.unsupported_locale": "Sprache wird nicht unterstützt.",
|
||||
"lang.de": "Deutsch",
|
||||
"lang.en": "English",
|
||||
"security.recovery.left": {
|
||||
"one": "{{.Count}} Wiederherstellungscode übrig",
|
||||
"other": "{{.Count}} Wiederherstellungscodes übrig"
|
||||
},
|
||||
"security.recovery.regenerate": "Neue Wiederherstellungscodes erzeugen",
|
||||
"security.recovery.save_now": "Bewahre diese Wiederherstellungscodes sicher auf. Jeder funktioniert einmal, falls du deinen Authenticator verlierst. Sie werden nicht erneut angezeigt.",
|
||||
"security.recovery.saved": "Ich habe sie gespeichert",
|
||||
"security.sso.heading": "Single Sign-on",
|
||||
"security.sso.link": "SSO-Anmeldung verknüpfen",
|
||||
"security.sso.linked": "SSO-Anmeldung verknüpft.",
|
||||
"security.sso.none": "In dieser Organisation ist keine SSO-Anmeldung verknüpft.",
|
||||
"security.title": "Sicherheit",
|
||||
"security.totp.active": "aktiv",
|
||||
"security.totp.app_code": "Code aus der App",
|
||||
"security.totp.confirm": "Bestätigen",
|
||||
"security.totp.current_code": "Aktueller Code oder Wiederherstellungscode",
|
||||
"security.totp.disable": "Deaktivieren",
|
||||
"security.totp.heading": "Zwei-Faktor (TOTP)",
|
||||
"security.totp.inactive": "nicht eingerichtet",
|
||||
"security.totp.qr_alt": "QR-Code für die Authenticator-App",
|
||||
"security.totp.start": "Einrichten",
|
||||
"sso.action.delete": "Provider löschen",
|
||||
"sso.action.delete_confirm": "Diesen Provider löschen? Verknüpfte Anmeldungen funktionieren dann nicht mehr.",
|
||||
"sso.action.edit": "Bearbeiten",
|
||||
"sso.choose.title": "Anmeldung wählen",
|
||||
"sso.field.allowed_domains": "Erlaubte E-Mail-Domains",
|
||||
"sso.field.allowed_domains_hint": "Kommagetrennt. Gilt nur für automatisch angelegte Konten; leer erlaubt jede Domain.",
|
||||
"sso.field.auto_provision": "Konten automatisch anlegen",
|
||||
"sso.field.client_id": "Client-ID",
|
||||
"sso.field.client_secret": "Client-Secret",
|
||||
"sso.field.client_secret_keep": "unverändert",
|
||||
"sso.field.enabled": "Aktiv",
|
||||
"sso.field.issuer": "Issuer-URL",
|
||||
"sso.field.name": "Name",
|
||||
"sso.settings.add": "Provider hinzufügen",
|
||||
"sso.settings.intro": "Mitglieder dieser Organisation können sich über euren eigenen OpenID-Connect-Identity-Provider anmelden. Tragt die Redirect-URL unten bei eurem Provider als erlaubten Callback ein.",
|
||||
"sso.settings.login_url": "Anmelde-URL",
|
||||
"sso.settings.redirect_url": "Redirect-URL",
|
||||
"sso.settings.title": "Single Sign-on"
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
{
|
||||
"app.network_error": "Connection failed.",
|
||||
"auth.field.code": "Code",
|
||||
"auth.field.email": "Email",
|
||||
"auth.field.name": "Name",
|
||||
"auth.field.new_password": "Password (min. {{.Min}} characters)",
|
||||
"auth.field.org_name": "Organization",
|
||||
"auth.field.org_slug": "Short name (a–z, 0–9, -)",
|
||||
"auth.field.password": "Password",
|
||||
"auth.login.no_account": "No account yet?",
|
||||
"auth.login.submit": "Continue",
|
||||
"auth.login.title": "Sign in",
|
||||
"auth.login.to_signup": "Sign up",
|
||||
"auth.login.totp_hint": "Enter the code from your authenticator app or one of your recovery codes.",
|
||||
"auth.signup.submit": "Create",
|
||||
"auth.signup.title": "Create account",
|
||||
"auth.signup.to_login": "Back to sign in",
|
||||
"auth.sso.heading": "Single sign-on",
|
||||
"auth.sso.org_placeholder": "Organization short name",
|
||||
"auth.sso.submit": "Continue",
|
||||
"common.no": "no",
|
||||
"common.save": "Save",
|
||||
"common.yes": "yes",
|
||||
"console.monitors.empty": "No monitors yet.",
|
||||
"console.monitors.title": "Monitors",
|
||||
"console.nav.logout": "Sign out",
|
||||
"console.nav.security": "Security",
|
||||
"console.nav.sso": "SSO",
|
||||
"console.totp_missing": "Your organization requires two-factor sign-in.",
|
||||
"console.totp_missing_action": "Set up now",
|
||||
"error.email_taken": "This email address is already registered.",
|
||||
"error.forbidden": "You are not allowed to do this.",
|
||||
"error.internal": "Internal error.",
|
||||
"error.invalid_code": "Invalid code.",
|
||||
"error.invalid_credentials": "Wrong email or password.",
|
||||
"error.invalid_domain": "One of the domains is not valid.",
|
||||
"error.invalid_input": "Please check your input.",
|
||||
"error.invalid_slug": "Short name: 2–63 characters, a–z, 0–9 and hyphen.",
|
||||
"error.mfa_expired": "Sign-in expired, please start again.",
|
||||
"error.no_password": "This account has no password.",
|
||||
"error.not_found": "Not found.",
|
||||
"error.org_not_found": "Organization not found.",
|
||||
"error.password_too_short": "The password needs at least {{.Min}} characters.",
|
||||
"error.rate_limited": "Too many attempts, please try again later.",
|
||||
"error.signup_closed": "Sign-up is disabled.",
|
||||
"error.slug_taken": "This short name is already taken.",
|
||||
"error.sso_denied": "Sign-in was cancelled at the identity provider.",
|
||||
"error.sso_discovery_failed": "The identity provider could not be reached or returned no valid configuration.",
|
||||
"error.sso_expired": "The sign-in attempt expired, please start again.",
|
||||
"error.sso_forbidden_address": "The issuer points to a non-public address.",
|
||||
"error.sso_identity_taken": "This SSO sign-in is already linked to another account.",
|
||||
"error.sso_invalid_issuer": "The issuer must be an https URL without query or credentials.",
|
||||
"error.sso_link_required": "An account with this email already exists. Sign in with your password and link SSO under Security.",
|
||||
"error.sso_not_member": "Your account is not a member of this organization.",
|
||||
"error.sso_not_provisioned": "No account exists for this sign-in. Ask an administrator to invite you.",
|
||||
"error.sso_provider_error": "The identity provider could not complete the sign-in.",
|
||||
"error.sso_unavailable": "Single sign-on is not available for this organization.",
|
||||
"error.totp_already_enabled": "TOTP is already active.",
|
||||
"error.totp_required_by_org": "One of your organizations requires TOTP.",
|
||||
"error.totp_setup_expired": "Setup expired, please start again.",
|
||||
"error.unsupported_locale": "Unsupported language.",
|
||||
"lang.de": "Deutsch",
|
||||
"lang.en": "English",
|
||||
"security.recovery.left": {
|
||||
"one": "{{.Count}} recovery code left",
|
||||
"other": "{{.Count}} recovery codes left"
|
||||
},
|
||||
"security.recovery.regenerate": "Generate new recovery codes",
|
||||
"security.recovery.save_now": "Store these recovery codes somewhere safe. Each works once if you lose your authenticator. They will not be shown again.",
|
||||
"security.recovery.saved": "I have saved them",
|
||||
"security.sso.heading": "Single sign-on",
|
||||
"security.sso.link": "Link SSO sign-in",
|
||||
"security.sso.linked": "SSO sign-in linked.",
|
||||
"security.sso.none": "No SSO sign-in linked in this organization.",
|
||||
"security.title": "Security",
|
||||
"security.totp.active": "active",
|
||||
"security.totp.app_code": "Code from the app",
|
||||
"security.totp.confirm": "Confirm",
|
||||
"security.totp.current_code": "Current code or recovery code",
|
||||
"security.totp.disable": "Disable",
|
||||
"security.totp.heading": "Two-factor (TOTP)",
|
||||
"security.totp.inactive": "not set up",
|
||||
"security.totp.qr_alt": "QR code for your authenticator app",
|
||||
"security.totp.start": "Set up",
|
||||
"sso.action.delete": "Delete provider",
|
||||
"sso.action.delete_confirm": "Delete this provider? Linked sign-ins stop working.",
|
||||
"sso.action.edit": "Edit",
|
||||
"sso.choose.title": "Choose sign-in",
|
||||
"sso.field.allowed_domains": "Allowed email domains",
|
||||
"sso.field.allowed_domains_hint": "Comma-separated. Only applies to automatically created accounts; empty allows any domain.",
|
||||
"sso.field.auto_provision": "Create accounts automatically",
|
||||
"sso.field.client_id": "Client ID",
|
||||
"sso.field.client_secret": "Client secret",
|
||||
"sso.field.client_secret_keep": "unchanged",
|
||||
"sso.field.enabled": "Enabled",
|
||||
"sso.field.issuer": "Issuer URL",
|
||||
"sso.field.name": "Name",
|
||||
"sso.settings.add": "Add provider",
|
||||
"sso.settings.intro": "Members of this organization can sign in through your own OpenID Connect identity provider. Register the redirect URL below as an allowed callback at your provider.",
|
||||
"sso.settings.login_url": "Sign-in URL",
|
||||
"sso.settings.redirect_url": "Redirect URL",
|
||||
"sso.settings.title": "Single sign-on"
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
// Package migrations embeds the SQL schema migrations and applies them with
|
||||
// goose.
|
||||
package migrations
|
||||
|
||||
import (
|
||||
@@ -7,7 +9,7 @@ import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
_ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" database/sql driver
|
||||
"github.com/pressly/goose/v3"
|
||||
"github.com/pressly/goose/v3/lock"
|
||||
)
|
||||
@@ -40,30 +42,33 @@ func newProvider(dsn string) (*goose.Provider, *sql.DB, error) {
|
||||
return p, db, nil
|
||||
}
|
||||
|
||||
// Up applies all pending migrations.
|
||||
func Up(ctx context.Context, dsn string) ([]*goose.MigrationResult, error) {
|
||||
p, db, err := newProvider(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("migrate: %w", err)
|
||||
}
|
||||
defer db.Close()
|
||||
defer func() { _ = db.Close() }()
|
||||
return p.Up(ctx)
|
||||
}
|
||||
|
||||
// Down rolls back the most recent migration.
|
||||
func Down(ctx context.Context, dsn string) (*goose.MigrationResult, error) {
|
||||
p, db, err := newProvider(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("migrate: %w", err)
|
||||
}
|
||||
defer db.Close()
|
||||
defer func() { _ = db.Close() }()
|
||||
return p.Down(ctx)
|
||||
}
|
||||
|
||||
// Status lists every migration with its applied state.
|
||||
func Status(ctx context.Context, dsn string) ([]*goose.MigrationStatus, error) {
|
||||
p, db, err := newProvider(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("migrate: %w", err)
|
||||
}
|
||||
defer db.Close()
|
||||
defer func() { _ = db.Close() }()
|
||||
return p.Status(ctx)
|
||||
}
|
||||
|
||||
@@ -74,6 +79,6 @@ func Pending(ctx context.Context, dsn string) (bool, error) {
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("migrate: %w", err)
|
||||
}
|
||||
defer db.Close()
|
||||
defer func() { _ = db.Close() }()
|
||||
return p.HasPending(ctx)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
email citext NOT NULL UNIQUE CHECK (length(email) BETWEEN 3 AND 320),
|
||||
display_name text NOT NULL DEFAULT '' CHECK (length(display_name) <= 200),
|
||||
password_hash text,
|
||||
disabled_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE memberships (
|
||||
org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
is_owner boolean NOT NULL DEFAULT false,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (org_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX memberships_user_idx ON memberships (user_id);
|
||||
CREATE UNIQUE INDEX memberships_one_owner_idx ON memberships (org_id) WHERE is_owner;
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE memberships;
|
||||
DROP TABLE users;
|
||||
@@ -0,0 +1,53 @@
|
||||
-- +goose Up
|
||||
-- Tenant context is carried in transaction-local settings (set_config(..., true)).
|
||||
-- Without any setting nothing is visible, so a forgotten scope fails closed.
|
||||
-- app.scope = 'system' is reserved for cross-tenant work such as scheduling.
|
||||
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION app_scope_system() RETURNS boolean
|
||||
LANGUAGE sql STABLE AS $$
|
||||
SELECT coalesce(current_setting('app.scope', true), '') = 'system'
|
||||
$$;
|
||||
|
||||
CREATE FUNCTION app_org_id() RETURNS uuid
|
||||
LANGUAGE sql STABLE AS $$
|
||||
SELECT nullif(current_setting('app.org_id', true), '')::uuid
|
||||
$$;
|
||||
|
||||
CREATE FUNCTION app_user_id() RETURNS uuid
|
||||
LANGUAGE sql STABLE AS $$
|
||||
SELECT nullif(current_setting('app.user_id', true), '')::uuid
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
ALTER TABLE orgs ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE orgs FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY orgs_read ON orgs FOR SELECT
|
||||
USING (
|
||||
app_scope_system() OR id = app_org_id()
|
||||
OR EXISTS (SELECT 1 FROM memberships m WHERE m.org_id = orgs.id AND m.user_id = app_user_id())
|
||||
);
|
||||
CREATE POLICY orgs_write ON orgs FOR ALL
|
||||
USING (app_scope_system() OR id = app_org_id())
|
||||
WITH CHECK (app_scope_system() OR id = app_org_id());
|
||||
|
||||
ALTER TABLE memberships ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE memberships FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY memberships_read ON memberships FOR SELECT
|
||||
USING (app_scope_system() OR org_id = app_org_id() OR user_id = app_user_id());
|
||||
CREATE POLICY memberships_write ON memberships FOR ALL
|
||||
USING (app_scope_system() OR org_id = app_org_id())
|
||||
WITH CHECK (app_scope_system() OR org_id = app_org_id());
|
||||
|
||||
-- +goose Down
|
||||
DROP POLICY memberships_write ON memberships;
|
||||
DROP POLICY memberships_read ON memberships;
|
||||
ALTER TABLE memberships NO FORCE ROW LEVEL SECURITY;
|
||||
ALTER TABLE memberships DISABLE ROW LEVEL SECURITY;
|
||||
DROP POLICY orgs_write ON orgs;
|
||||
DROP POLICY orgs_read ON orgs;
|
||||
ALTER TABLE orgs NO FORCE ROW LEVEL SECURITY;
|
||||
ALTER TABLE orgs DISABLE ROW LEVEL SECURITY;
|
||||
DROP FUNCTION app_user_id();
|
||||
DROP FUNCTION app_org_id();
|
||||
DROP FUNCTION app_scope_system();
|
||||
@@ -0,0 +1,14 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE users
|
||||
ADD COLUMN totp_secret bytea,
|
||||
ADD COLUMN totp_enabled_at timestamptz,
|
||||
ADD CONSTRAINT users_totp_consistent CHECK ((totp_secret IS NULL) = (totp_enabled_at IS NULL));
|
||||
|
||||
ALTER TABLE orgs ADD COLUMN require_totp boolean NOT NULL DEFAULT false;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE orgs DROP COLUMN require_totp;
|
||||
ALTER TABLE users
|
||||
DROP CONSTRAINT users_totp_consistent,
|
||||
DROP COLUMN totp_enabled_at,
|
||||
DROP COLUMN totp_secret;
|
||||
@@ -0,0 +1,6 @@
|
||||
-- +goose Up
|
||||
-- Validated against the supported catalogs in code; the check only guards the format.
|
||||
ALTER TABLE users ADD COLUMN locale text CHECK (locale ~ '^[a-z]{2}(-[A-Z]{2})?$');
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE users DROP COLUMN locale;
|
||||
@@ -0,0 +1,70 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE sso_providers (
|
||||
id uuid PRIMARY KEY,
|
||||
org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
|
||||
name text NOT NULL CHECK (length(name) BETWEEN 1 AND 100),
|
||||
issuer text NOT NULL CHECK (issuer ~ '^https?://[^\s]+$' AND length(issuer) <= 500),
|
||||
client_id text NOT NULL CHECK (length(client_id) BETWEEN 1 AND 500),
|
||||
-- Sealed with the application keyring, bound to the provider id.
|
||||
client_secret bytea,
|
||||
scopes text[] NOT NULL DEFAULT '{openid,email,profile}',
|
||||
-- Lower-case domains; empty means any. Applies to auto-provisioning only.
|
||||
allowed_domains text[] NOT NULL DEFAULT '{}',
|
||||
auto_provision boolean NOT NULL DEFAULT false,
|
||||
enabled boolean NOT NULL DEFAULT true,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX sso_providers_org_idx ON sso_providers (org_id);
|
||||
|
||||
-- Accounts are linked by issuer subject, never by email: an org admin
|
||||
-- controls their IdP and could otherwise assert any address.
|
||||
CREATE TABLE user_identities (
|
||||
provider_id uuid NOT NULL REFERENCES sso_providers (id) ON DELETE CASCADE,
|
||||
subject text NOT NULL CHECK (length(subject) BETWEEN 1 AND 255),
|
||||
org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
email citext,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_login_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (provider_id, subject)
|
||||
);
|
||||
|
||||
CREATE INDEX user_identities_user_idx ON user_identities (user_id);
|
||||
|
||||
ALTER TABLE sso_providers ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE sso_providers FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY sso_providers_tenant ON sso_providers FOR ALL
|
||||
USING (app_scope_system() OR org_id = app_org_id())
|
||||
WITH CHECK (app_scope_system() OR org_id = app_org_id());
|
||||
|
||||
ALTER TABLE user_identities ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE user_identities FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY user_identities_tenant ON user_identities FOR ALL
|
||||
USING (app_scope_system() OR org_id = app_org_id() OR user_id = app_user_id())
|
||||
WITH CHECK (app_scope_system() OR org_id = app_org_id());
|
||||
|
||||
-- SSO starts before anyone is signed in. This reveals only whether a slug
|
||||
-- exists, which the public /sso/<slug> URL does anyway. FORCE ROW LEVEL
|
||||
-- SECURITY applies to the table owner too, so SECURITY DEFINER would not
|
||||
-- help; the system scope is raised for this single lookup and restored.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION org_id_by_slug(s citext) RETURNS uuid
|
||||
LANGUAGE plpgsql VOLATILE AS $$
|
||||
DECLARE
|
||||
prev text := coalesce(current_setting('app.scope', true), '');
|
||||
result uuid;
|
||||
BEGIN
|
||||
PERFORM set_config('app.scope', 'system', true);
|
||||
SELECT id INTO result FROM orgs WHERE slug = s;
|
||||
PERFORM set_config('app.scope', prev, true);
|
||||
RETURN result;
|
||||
END
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- +goose Down
|
||||
DROP FUNCTION org_id_by_slug(citext);
|
||||
DROP TABLE user_identities;
|
||||
DROP TABLE sso_providers;
|
||||
@@ -0,0 +1,13 @@
|
||||
-- +goose Up
|
||||
-- Like users, these rows belong to a person rather than an organization and
|
||||
-- are not under row-level security.
|
||||
CREATE TABLE recovery_codes (
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
code_hash bytea NOT NULL,
|
||||
used_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, code_hash)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE recovery_codes;
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Probe reports whether a dependency is usable.
|
||||
type Probe func(context.Context) error
|
||||
|
||||
// Health separates liveness from readiness so a draining instance drops out
|
||||
@@ -18,12 +19,15 @@ type Health struct {
|
||||
draining atomic.Bool
|
||||
}
|
||||
|
||||
// NewHealth returns a Health that is ready while all probes pass.
|
||||
func NewHealth(probes map[string]Probe) *Health {
|
||||
return &Health{probes: probes}
|
||||
}
|
||||
|
||||
// Drain makes /readyz fail permanently. Call it before shutdown.
|
||||
func (h *Health) Drain() { h.draining.Store(true) }
|
||||
|
||||
// Register mounts /healthz (liveness) and /readyz (readiness).
|
||||
func (h *Health) Register(r gin.IRoutes) {
|
||||
r.GET("/healthz", func(c *gin.Context) { c.Status(http.StatusNoContent) })
|
||||
r.GET("/readyz", h.ready)
|
||||
|
||||
+38
-10
@@ -1,21 +1,49 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
|
||||
)
|
||||
|
||||
var logLevel = new(slog.LevelVar)
|
||||
|
||||
// NewLogger installs a JSON logger as the process default so output from the
|
||||
// standard log package and dependencies ends up in the same format.
|
||||
func NewLogger(component string) *slog.Logger {
|
||||
l := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: logLevel})).
|
||||
With("component", component, "app_version", buildinfo.Version)
|
||||
slog.SetDefault(l)
|
||||
return l
|
||||
// NewLogger returns a JSON logger tagged with component and the release
|
||||
// version, and the level variable controlling it. The level can be changed
|
||||
// once configuration is loaded; the logger is needed before that to report
|
||||
// configuration errors.
|
||||
//
|
||||
// Records logged with a request context carry its request_id, so handlers
|
||||
// should prefer the *Context logging methods.
|
||||
func NewLogger(component string) (*slog.Logger, *slog.LevelVar) {
|
||||
return newLogger(os.Stderr, component)
|
||||
}
|
||||
|
||||
func SetLogLevel(l slog.Level) { logLevel.Set(l) }
|
||||
func newLogger(w io.Writer, component string) (*slog.Logger, *slog.LevelVar) {
|
||||
level := new(slog.LevelVar)
|
||||
h := contextHandler{slog.NewJSONHandler(w, &slog.HandlerOptions{Level: level})}
|
||||
return slog.New(h).With("component", component, "app_version", buildinfo.Version), level
|
||||
}
|
||||
|
||||
// contextHandler adds attributes carried in the context to each record.
|
||||
type contextHandler struct{ slog.Handler }
|
||||
|
||||
// Handle implements slog.Handler.
|
||||
func (h contextHandler) Handle(ctx context.Context, r slog.Record) error {
|
||||
if id := requestid.FromContext(ctx); id != "" {
|
||||
r.AddAttrs(slog.String("request_id", id))
|
||||
}
|
||||
return h.Handler.Handle(ctx, r)
|
||||
}
|
||||
|
||||
// WithAttrs keeps the wrapper so derived loggers still add the request ID.
|
||||
func (h contextHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
return contextHandler{h.Handler.WithAttrs(attrs)}
|
||||
}
|
||||
|
||||
// WithGroup keeps the wrapper so derived loggers still add the request ID.
|
||||
func (h contextHandler) WithGroup(name string) slog.Handler {
|
||||
return contextHandler{h.Handler.WithGroup(name)}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
|
||||
)
|
||||
|
||||
func TestLoggerAddsRequestID(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
log, _ := newLogger(&buf, "test")
|
||||
log = log.With("extra", 1)
|
||||
|
||||
log.InfoContext(requestid.NewContext(context.Background(), "abc"), "with id")
|
||||
log.InfoContext(context.Background(), "without id")
|
||||
|
||||
dec := json.NewDecoder(&buf)
|
||||
for _, want := range []any{"abc", nil} {
|
||||
var rec map[string]any
|
||||
if err := dec.Decode(&rec); err != nil {
|
||||
t.Fatalf("decoding log line: %v", err)
|
||||
}
|
||||
if got := rec["request_id"]; got != want {
|
||||
t.Errorf("%q: request_id = %v, want %v", rec["msg"], got, want)
|
||||
}
|
||||
if rec["extra"] != float64(1) || rec["component"] != "test" {
|
||||
t.Errorf("%q: lost attributes from With: %v", rec["msg"], rec)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
// Package platform wires the infrastructure shared by all commands:
|
||||
// logging, Postgres, Redis, HTTP serving and health probes.
|
||||
package platform
|
||||
|
||||
import (
|
||||
@@ -7,6 +9,7 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// OpenPostgres connects a pool and verifies it with a ping.
|
||||
func OpenPostgres(ctx context.Context, url string) (*pgxpool.Pool, error) {
|
||||
cfg, err := pgxpool.ParseConfig(url)
|
||||
if err != nil {
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
)
|
||||
|
||||
// OpenRedis connects to a single server or, when c.RedisSentinel is enabled,
|
||||
// to the current master via sentinel with automatic failover.
|
||||
func OpenRedis(ctx context.Context, c config.Common) (*redis.Client, error) {
|
||||
var rdb *redis.Client
|
||||
if c.RedisSentinel.Enabled() {
|
||||
|
||||
@@ -7,18 +7,19 @@ import (
|
||||
)
|
||||
|
||||
func TestFailoverOptionsTakesMasterAuthFromURL(t *testing.T) {
|
||||
const url = "rediss://app:masterpw@ignored:6379/3"
|
||||
s := config.Sentinel{Master: "mymaster", Addrs: []string{"s1:26379", "s2:26379"}, Password: "sentinelpw"}
|
||||
fo, err := failoverOptions("rediss://app:masterpw@ignored:6379/3", s)
|
||||
fo, err := failoverOptions(url, s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
t.Fatalf("failoverOptions(%q) failed: %v", url, err)
|
||||
}
|
||||
if fo.Password != "masterpw" || fo.Username != "app" || fo.DB != 3 {
|
||||
t.Fatalf("master auth not applied: %+v", fo)
|
||||
if fo.Username != "app" || fo.Password != "masterpw" || fo.DB != 3 {
|
||||
t.Errorf("failoverOptions(%q) master auth = %q/%q db %d, want app/masterpw db 3", url, fo.Username, fo.Password, fo.DB)
|
||||
}
|
||||
if fo.SentinelPassword != "sentinelpw" || len(fo.SentinelAddrs) != 2 {
|
||||
t.Fatalf("sentinel settings lost: %+v", fo)
|
||||
t.Errorf("failoverOptions(%q) sentinel = %q %v, want sentinelpw with 2 addrs", url, fo.SentinelPassword, fo.SentinelAddrs)
|
||||
}
|
||||
if fo.TLSConfig == nil {
|
||||
t.Fatal("rediss scheme must enable TLS")
|
||||
t.Errorf("failoverOptions(%q).TLSConfig = nil, want TLS for rediss scheme", url)
|
||||
}
|
||||
}
|
||||
@@ -8,16 +8,20 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
|
||||
)
|
||||
|
||||
var quietPaths = map[string]bool{"/healthz": true, "/readyz": true}
|
||||
|
||||
// NewRouter returns a gin engine that assigns request IDs, logs requests and
|
||||
// panics through log as JSON and writes nothing to stdout itself.
|
||||
func NewRouter(log *slog.Logger) *gin.Engine {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
gin.DefaultWriter = io.Discard
|
||||
gin.DefaultErrorWriter = io.Discard
|
||||
r := gin.New()
|
||||
r.Use(accessLog(log), recovery(log))
|
||||
r.Use(requestid.Middleware(), accessLog(log), recovery(log))
|
||||
return r
|
||||
}
|
||||
|
||||
|
||||
@@ -15,12 +15,14 @@ import (
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/migrations"
|
||||
)
|
||||
|
||||
// Deps are the connections every command needs.
|
||||
type Deps struct {
|
||||
Log *slog.Logger
|
||||
DB *pgxpool.Pool
|
||||
Redis *redis.Client
|
||||
}
|
||||
|
||||
// Close releases all connections. It is safe on a partially built Deps.
|
||||
func (d *Deps) Close() {
|
||||
if d.DB != nil {
|
||||
d.DB.Close()
|
||||
@@ -30,6 +32,7 @@ func (d *Deps) Close() {
|
||||
}
|
||||
}
|
||||
|
||||
// Probes returns readiness probes for the connections.
|
||||
func (d *Deps) Probes() map[string]Probe {
|
||||
return map[string]Probe{
|
||||
"postgres": func(ctx context.Context) error { return d.DB.Ping(ctx) },
|
||||
@@ -37,10 +40,13 @@ func (d *Deps) Probes() map[string]Probe {
|
||||
}
|
||||
}
|
||||
|
||||
// SignalContext is cancelled on SIGINT or SIGTERM.
|
||||
func SignalContext() (context.Context, context.CancelFunc) {
|
||||
return signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
}
|
||||
|
||||
// Connect validates c, refuses to start against an outdated schema, and
|
||||
// opens Postgres and Redis.
|
||||
func Connect(ctx context.Context, c config.Common, log *slog.Logger) (*Deps, error) {
|
||||
if err := c.Validate(); err != nil {
|
||||
return nil, err
|
||||
@@ -60,5 +66,16 @@ func Connect(ctx context.Context, c config.Common, log *slog.Logger) (*Deps, err
|
||||
d.Close()
|
||||
return nil, err
|
||||
}
|
||||
warnIfRLSBypassed(ctx, d)
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// warnIfRLSBypassed flags deployments where tenant isolation silently degrades
|
||||
// to application-level filtering only.
|
||||
func warnIfRLSBypassed(ctx context.Context, d *Deps) {
|
||||
var bypass bool
|
||||
err := d.DB.QueryRow(ctx, `SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user`).Scan(&bypass)
|
||||
if err == nil && bypass {
|
||||
d.Log.Warn("database role bypasses row-level security; connect as a non-superuser role without BYPASSRLS")
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,7 @@ func Serve(ctx context.Context, log *slog.Logger, srv *http.Server, health *Heal
|
||||
return srv.Shutdown(sctx)
|
||||
}
|
||||
|
||||
// NewHTTPServer returns a server with timeouts that bound slow clients.
|
||||
func NewHTTPServer(addr string, h http.Handler) *http.Server {
|
||||
return &http.Server{
|
||||
Addr: addr,
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// Package requestid assigns every HTTP request an ID that ties together the
|
||||
// response, all log lines written for it and error reports from users.
|
||||
package requestid
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Header carries the ID in both directions.
|
||||
const Header = "X-Request-ID"
|
||||
|
||||
// Incoming IDs end up in logs and response headers, so anything beyond a
|
||||
// conservative token alphabet is replaced rather than passed through.
|
||||
var valid = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
type ctxKey struct{}
|
||||
|
||||
// NewContext returns ctx carrying id.
|
||||
func NewContext(ctx context.Context, id string) context.Context {
|
||||
return context.WithValue(ctx, ctxKey{}, id)
|
||||
}
|
||||
|
||||
// FromContext returns the request ID in ctx, or "" outside a request.
|
||||
func FromContext(ctx context.Context) string {
|
||||
id, _ := ctx.Value(ctxKey{}).(string)
|
||||
return id
|
||||
}
|
||||
|
||||
// Middleware keeps a well-formed X-Request-ID set by a proxy in front of us
|
||||
// and otherwise generates a time-ordered UUIDv7, so IDs sort by arrival.
|
||||
// It must run before any middleware that logs.
|
||||
func Middleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
id := c.GetHeader(Header)
|
||||
if !valid.MatchString(id) {
|
||||
id = newID()
|
||||
}
|
||||
c.Request = c.Request.WithContext(NewContext(c.Request.Context(), id))
|
||||
c.Header(Header, id)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func newID() string {
|
||||
if id, err := uuid.NewV7(); err == nil {
|
||||
return id.String()
|
||||
}
|
||||
return uuid.NewString()
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package requestid
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestMiddleware(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
incoming string
|
||||
keep bool
|
||||
}{
|
||||
{name: "none", incoming: "", keep: false},
|
||||
{name: "uuid from proxy", incoming: "0b9a7c3e-6a43-4d2c-9a55-2f3b1c0d4e5f", keep: true},
|
||||
{name: "trace style", incoming: "Root=1-5759e988-bd862e3fe1be46a994272793", keep: false},
|
||||
{name: "opaque token", incoming: "edge:abc.123_X", keep: true},
|
||||
{name: "header injection", incoming: "abc\r\nSet-Cookie: x=y", keep: false},
|
||||
{name: "too long", incoming: strings.Repeat("a", 129), keep: false},
|
||||
}
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var seen string
|
||||
r := gin.New()
|
||||
r.Use(Middleware())
|
||||
r.GET("/", func(c *gin.Context) { seen = FromContext(c.Request.Context()) })
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
if tt.incoming != "" {
|
||||
req.Header.Set(Header, tt.incoming)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
got := w.Header().Get(Header)
|
||||
if got != seen {
|
||||
t.Errorf("response header %q != context ID %q", got, seen)
|
||||
}
|
||||
if tt.keep {
|
||||
if got != tt.incoming {
|
||||
t.Errorf("ID = %q, want incoming %q", got, tt.incoming)
|
||||
}
|
||||
return
|
||||
}
|
||||
if u, err := uuid.Parse(got); err != nil || u.Version() != 7 {
|
||||
t.Errorf("ID = %q, want generated UUIDv7", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
// Package sealed encrypts small secrets (TOTP seeds, integration credentials)
|
||||
// before they are written to the database.
|
||||
package sealed
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ErrUnknownKey is returned for values sealed with a key that was removed
|
||||
// from the keyring.
|
||||
var ErrUnknownKey = errors.New("sealed: unknown key id")
|
||||
|
||||
// Keyring holds one active key for sealing and any number of retired keys
|
||||
// that can still open old values, so keys can be rotated without downtime.
|
||||
type Keyring struct {
|
||||
active string
|
||||
aeads map[string]cipher.AEAD
|
||||
}
|
||||
|
||||
// Parse reads "id:base64key,id2:base64key2"; the first entry is active.
|
||||
func Parse(spec string) (*Keyring, error) {
|
||||
kr := &Keyring{aeads: map[string]cipher.AEAD{}}
|
||||
for i, part := range strings.Split(spec, ",") {
|
||||
id, b64, ok := strings.Cut(strings.TrimSpace(part), ":")
|
||||
if !ok || id == "" {
|
||||
return nil, fmt.Errorf("sealed: entry %d must be id:base64", i+1)
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(b64)
|
||||
if err != nil || len(raw) != 32 {
|
||||
return nil, fmt.Errorf("sealed: key %q must be 32 bytes, base64 encoded", id)
|
||||
}
|
||||
block, err := aes.NewCipher(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
aead, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, dup := kr.aeads[id]; dup {
|
||||
return nil, fmt.Errorf("sealed: duplicate key id %q", id)
|
||||
}
|
||||
kr.aeads[id] = aead
|
||||
if i == 0 {
|
||||
kr.active = id
|
||||
}
|
||||
}
|
||||
return kr, nil
|
||||
}
|
||||
|
||||
// Seal binds the ciphertext to aad (e.g. the owning row id) so a sealed value
|
||||
// cannot be copied onto another row.
|
||||
func (k *Keyring) Seal(plain, aad []byte) []byte {
|
||||
aead := k.aeads[k.active]
|
||||
nonce := make([]byte, aead.NonceSize())
|
||||
_, _ = rand.Read(nonce)
|
||||
out := append([]byte(k.active+":"), nonce...)
|
||||
return aead.Seal(out, nonce, plain, aad)
|
||||
}
|
||||
|
||||
// Open decrypts a value produced by Seal with the same aad.
|
||||
func (k *Keyring) Open(sealed, aad []byte) ([]byte, error) {
|
||||
id, rest, ok := strings.Cut(string(sealed), ":")
|
||||
if !ok {
|
||||
return nil, errors.New("sealed: malformed value")
|
||||
}
|
||||
aead, ok := k.aeads[id]
|
||||
if !ok {
|
||||
return nil, ErrUnknownKey
|
||||
}
|
||||
body := []byte(rest)
|
||||
if len(body) < aead.NonceSize() {
|
||||
return nil, errors.New("sealed: malformed value")
|
||||
}
|
||||
return aead.Open(nil, body[:aead.NonceSize()], body[aead.NonceSize():], aad)
|
||||
}
|
||||
|
||||
// NeedsReseal reports whether sealed was produced with a retired key and
|
||||
// should be rewritten.
|
||||
func (k *Keyring) NeedsReseal(sealed []byte) bool {
|
||||
id, _, _ := strings.Cut(string(sealed), ":")
|
||||
return id != k.active
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package sealed
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func newKey() string {
|
||||
b := make([]byte, 32)
|
||||
_, _ = rand.Read(b)
|
||||
return base64.StdEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
func mustParse(t *testing.T, spec string) *Keyring {
|
||||
t.Helper()
|
||||
kr, err := Parse(spec)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse(%q) failed: %v", spec, err)
|
||||
}
|
||||
return kr
|
||||
}
|
||||
|
||||
func TestKeyRotation(t *testing.T) {
|
||||
k1, k2 := newKey(), newKey()
|
||||
aad := []byte("row-1")
|
||||
box := mustParse(t, "a:"+k1).Seal([]byte("secret"), aad)
|
||||
|
||||
rotated := mustParse(t, "b:"+k2+",a:"+k1)
|
||||
if got, err := rotated.Open(box, aad); err != nil || !bytes.Equal(got, []byte("secret")) {
|
||||
t.Errorf("Open(value sealed with retired key) = %q, %v; want %q, nil", got, err, "secret")
|
||||
}
|
||||
if !rotated.NeedsReseal(box) {
|
||||
t.Error("NeedsReseal(value sealed with retired key) = false, want true")
|
||||
}
|
||||
if rotated.NeedsReseal(rotated.Seal([]byte("x"), nil)) {
|
||||
t.Error("NeedsReseal(value sealed with active key) = true, want false")
|
||||
}
|
||||
|
||||
dropped := mustParse(t, "b:"+k2)
|
||||
if _, err := dropped.Open(box, aad); !errors.Is(err, ErrUnknownKey) {
|
||||
t.Errorf("Open(value sealed with removed key) error = %v, want %v", err, ErrUnknownKey)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenRejectsOtherAAD(t *testing.T) {
|
||||
kr := mustParse(t, "a:"+newKey())
|
||||
box := kr.Seal([]byte("secret"), []byte("row-1"))
|
||||
if _, err := kr.Open(box, []byte("row-2")); err == nil {
|
||||
t.Error("Open(box, other aad) error = nil, want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRejectsInvalidSpecs(t *testing.T) {
|
||||
for _, spec := range []string{"", "nokey", "a:short", "a:" + newKey() + ",a:" + newKey()} {
|
||||
if _, err := Parse(spec); err == nil {
|
||||
t.Errorf("Parse(%q) error = nil, want error", spec)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package sso
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ErrForbiddenAddress is returned when an IdP resolves to an address the
|
||||
// client may not contact.
|
||||
var ErrForbiddenAddress = errors.New("sso: issuer resolves to a non-public address")
|
||||
|
||||
var cgnat = netip.MustParsePrefix("100.64.0.0/10")
|
||||
|
||||
// SafeHTTPClient returns a client for talking to customer-configured IdPs.
|
||||
// Unless allowPrivate is set it refuses to connect to loopback, private,
|
||||
// link-local and similar ranges. The check runs on the resolved address at
|
||||
// dial time, so DNS rebinding and redirects cannot bypass it.
|
||||
func SafeHTTPClient(allowPrivate bool) *http.Client {
|
||||
d := &net.Dialer{Timeout: 5 * time.Second}
|
||||
if !allowPrivate {
|
||||
d.Control = func(_, address string, _ syscall.RawConn) error {
|
||||
ap, err := netip.ParseAddrPort(address)
|
||||
if err != nil || !isPublic(ap.Addr()) {
|
||||
return ErrForbiddenAddress
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
tr := http.DefaultTransport.(*http.Transport).Clone()
|
||||
tr.Proxy = nil
|
||||
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return d.DialContext(ctx, network, addr)
|
||||
}
|
||||
return &http.Client{Transport: tr, Timeout: 10 * time.Second}
|
||||
}
|
||||
|
||||
func isPublic(a netip.Addr) bool {
|
||||
a = a.Unmap()
|
||||
return a.IsGlobalUnicast() && !a.IsPrivate() && !cgnat.Contains(a)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package sso
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIsPublic(t *testing.T) {
|
||||
tests := map[string]bool{
|
||||
"8.8.8.8": true,
|
||||
"2606:4700::1111": true,
|
||||
"127.0.0.1": false,
|
||||
"10.1.2.3": false,
|
||||
"172.16.0.1": false,
|
||||
"192.168.1.1": false,
|
||||
"169.254.169.254": false,
|
||||
"100.64.0.1": false,
|
||||
"0.0.0.0": false,
|
||||
"::1": false,
|
||||
"fd00::1": false,
|
||||
"fe80::1": false,
|
||||
"::ffff:127.0.0.1": false,
|
||||
}
|
||||
for addr, want := range tests {
|
||||
if got := isPublic(netip.MustParseAddr(addr)); got != want {
|
||||
t.Errorf("isPublic(%s) = %t, want %t", addr, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeHTTPClientBlocksLoopback(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
defer srv.Close()
|
||||
|
||||
if _, err := SafeHTTPClient(false).Get(srv.URL); !errors.Is(err, ErrForbiddenAddress) {
|
||||
t.Errorf("Get(%s) with private networks denied: error = %v, want %v", srv.URL, err, ErrForbiddenAddress)
|
||||
}
|
||||
resp, err := SafeHTTPClient(true).Get(srv.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("Get(%s) with private networks allowed failed: %v", srv.URL, err)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
// Package sso implements OpenID Connect sign-in against identity providers
|
||||
// that each organization configures for itself.
|
||||
package sso
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// Provider is one organization's IdP registration.
|
||||
type Provider struct {
|
||||
Issuer string
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
Scopes []string
|
||||
}
|
||||
|
||||
// Claims are the ID token fields used to identify and provision a user.
|
||||
type Claims struct {
|
||||
Subject string `json:"sub"`
|
||||
Email string `json:"email"`
|
||||
EmailVerified bool `json:"email_verified"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// Flow holds the per-attempt secrets that must survive the redirect to the
|
||||
// IdP. Callers store it server side, keyed by State.
|
||||
type Flow struct {
|
||||
State string
|
||||
Nonce string
|
||||
Verifier string
|
||||
}
|
||||
|
||||
// ErrInvalidIssuer is returned for issuer URLs that are malformed or use a
|
||||
// scheme the client does not allow.
|
||||
var ErrInvalidIssuer = errors.New("sso: invalid issuer url")
|
||||
|
||||
const discoveryTTL = time.Hour
|
||||
|
||||
// Client performs discovery, builds authorization URLs and verifies
|
||||
// callbacks. Discovery documents are cached per issuer.
|
||||
type Client struct {
|
||||
http *http.Client
|
||||
redirectURL string
|
||||
allowHTTP bool
|
||||
now func() time.Time
|
||||
|
||||
mu sync.Mutex
|
||||
cache map[string]cached
|
||||
}
|
||||
|
||||
type cached struct {
|
||||
provider *oidc.Provider
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
// New returns a Client whose callbacks land on redirectURL. httpClient is
|
||||
// used for every request to an IdP; pass one from SafeHTTPClient. allowHTTP
|
||||
// permits plain-http issuers, which only makes sense for IdPs on a private
|
||||
// network.
|
||||
func New(httpClient *http.Client, redirectURL string, allowHTTP bool) *Client {
|
||||
return &Client{
|
||||
http: httpClient,
|
||||
redirectURL: redirectURL,
|
||||
allowHTTP: allowHTTP,
|
||||
now: time.Now,
|
||||
cache: map[string]cached{},
|
||||
}
|
||||
}
|
||||
|
||||
// RedirectURL is the callback URL to register at the IdP.
|
||||
func (c *Client) RedirectURL() string { return c.redirectURL }
|
||||
|
||||
// ValidateIssuer checks the URL syntactically and runs discovery, so that
|
||||
// misconfiguration surfaces when an admin saves the provider rather than
|
||||
// when users try to sign in.
|
||||
func (c *Client) ValidateIssuer(ctx context.Context, issuer string) error {
|
||||
if err := c.checkIssuer(issuer); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := c.discover(ctx, issuer)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Client) checkIssuer(issuer string) error {
|
||||
u, err := url.Parse(issuer)
|
||||
if err != nil || u.Host == "" || u.RawQuery != "" || u.Fragment != "" || u.User != nil {
|
||||
return ErrInvalidIssuer
|
||||
}
|
||||
if u.Scheme != "https" && !(c.allowHTTP && u.Scheme == "http") {
|
||||
return ErrInvalidIssuer
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) discover(ctx context.Context, issuer string) (*oidc.Provider, error) {
|
||||
c.mu.Lock()
|
||||
if e, ok := c.cache[issuer]; ok && c.now().Before(e.expires) {
|
||||
c.mu.Unlock()
|
||||
return e.provider, nil
|
||||
}
|
||||
c.mu.Unlock()
|
||||
|
||||
p, err := oidc.NewProvider(oidc.ClientContext(ctx, c.http), issuer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sso: discovery for %s: %w", issuer, err)
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.cache[issuer] = cached{provider: p, expires: c.now().Add(discoveryTTL)}
|
||||
c.mu.Unlock()
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (c *Client) oauth(p Provider, op *oidc.Provider) *oauth2.Config {
|
||||
scopes := p.Scopes
|
||||
if !slices.Contains(scopes, oidc.ScopeOpenID) {
|
||||
scopes = append([]string{oidc.ScopeOpenID}, scopes...)
|
||||
}
|
||||
return &oauth2.Config{
|
||||
ClientID: p.ClientID,
|
||||
ClientSecret: p.ClientSecret,
|
||||
Endpoint: op.Endpoint(),
|
||||
RedirectURL: c.redirectURL,
|
||||
Scopes: scopes,
|
||||
}
|
||||
}
|
||||
|
||||
// NewFlow returns fresh state, nonce and PKCE verifier.
|
||||
func NewFlow(random func() string) Flow {
|
||||
return Flow{State: random(), Nonce: random(), Verifier: oauth2.GenerateVerifier()}
|
||||
}
|
||||
|
||||
// AuthURL returns the IdP URL to redirect the browser to.
|
||||
func (c *Client) AuthURL(ctx context.Context, p Provider, f Flow) (string, error) {
|
||||
if err := c.checkIssuer(p.Issuer); err != nil {
|
||||
return "", err
|
||||
}
|
||||
op, err := c.discover(ctx, p.Issuer)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return c.oauth(p, op).AuthCodeURL(f.State,
|
||||
oidc.Nonce(f.Nonce),
|
||||
oauth2.S256ChallengeOption(f.Verifier),
|
||||
), nil
|
||||
}
|
||||
|
||||
// Exchange redeems the authorization code and verifies the ID token's
|
||||
// signature, issuer, audience, expiry and nonce.
|
||||
func (c *Client) Exchange(ctx context.Context, p Provider, f Flow, code string) (Claims, error) {
|
||||
op, err := c.discover(ctx, p.Issuer)
|
||||
if err != nil {
|
||||
return Claims{}, err
|
||||
}
|
||||
ctx = oidc.ClientContext(ctx, c.http)
|
||||
tok, err := c.oauth(p, op).Exchange(ctx, code, oauth2.VerifierOption(f.Verifier))
|
||||
if err != nil {
|
||||
return Claims{}, fmt.Errorf("sso: code exchange: %w", err)
|
||||
}
|
||||
raw, ok := tok.Extra("id_token").(string)
|
||||
if !ok {
|
||||
return Claims{}, errors.New("sso: token response without id_token")
|
||||
}
|
||||
idt, err := op.VerifierContext(ctx, &oidc.Config{ClientID: p.ClientID, Now: c.now}).Verify(ctx, raw)
|
||||
if err != nil {
|
||||
return Claims{}, fmt.Errorf("sso: id token: %w", err)
|
||||
}
|
||||
if idt.Nonce != f.Nonce {
|
||||
return Claims{}, errors.New("sso: id token nonce mismatch")
|
||||
}
|
||||
var cl Claims
|
||||
if err := idt.Claims(&cl); err != nil {
|
||||
return Claims{}, fmt.Errorf("sso: id token claims: %w", err)
|
||||
}
|
||||
if cl.Subject == "" {
|
||||
return Claims{}, errors.New("sso: id token without subject")
|
||||
}
|
||||
return cl, nil
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package sso_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/sso"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/sso/ssotest"
|
||||
)
|
||||
|
||||
const callback = "https://uptime.example/sso/callback"
|
||||
|
||||
// authorize follows the IdP redirect and returns the code and state it
|
||||
// would deliver to the callback.
|
||||
func authorize(t *testing.T, authURL string) (code, state string) {
|
||||
t.Helper()
|
||||
noFollow := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
resp, err := noFollow.Get(authURL)
|
||||
if err != nil {
|
||||
t.Fatalf("GET %s failed: %v", authURL, err)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
loc, err := url.Parse(resp.Header.Get("Location"))
|
||||
if err != nil || resp.StatusCode != http.StatusFound {
|
||||
t.Fatalf("authorize = %d %q, want 302 to callback", resp.StatusCode, resp.Header.Get("Location"))
|
||||
}
|
||||
return loc.Query().Get("code"), loc.Query().Get("state")
|
||||
}
|
||||
|
||||
func setup(t *testing.T) (*ssotest.IDP, *sso.Client, sso.Provider) {
|
||||
t.Helper()
|
||||
idp := ssotest.New(t)
|
||||
c := sso.New(sso.SafeHTTPClient(true), callback, true)
|
||||
p := sso.Provider{Issuer: idp.Issuer(), ClientID: idp.ClientID, ClientSecret: idp.Secret, Scopes: []string{"email"}}
|
||||
return idp, c, p
|
||||
}
|
||||
|
||||
func TestFlow(t *testing.T) {
|
||||
idp, c, p := setup(t)
|
||||
idp.SetUser(ssotest.User{Subject: "u-1", Email: "a@corp.test", EmailVerified: true, Name: "A"})
|
||||
ctx := context.Background()
|
||||
|
||||
flow := sso.NewFlow(rand.Text)
|
||||
authURL, err := c.AuthURL(ctx, p, flow)
|
||||
if err != nil {
|
||||
t.Fatalf("AuthURL() failed: %v", err)
|
||||
}
|
||||
code, state := authorize(t, authURL)
|
||||
if state != flow.State {
|
||||
t.Fatalf("state = %q, want %q", state, flow.State)
|
||||
}
|
||||
got, err := c.Exchange(ctx, p, flow, code)
|
||||
if err != nil {
|
||||
t.Fatalf("Exchange() failed: %v", err)
|
||||
}
|
||||
want := sso.Claims{Subject: "u-1", Email: "a@corp.test", EmailVerified: true, Name: "A"}
|
||||
if got != want {
|
||||
t.Errorf("Exchange() = %+v, want %+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExchangeRejects(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
tamper func(*ssotest.IDP, *sso.Flow)
|
||||
}{
|
||||
{"wrong nonce", func(i *ssotest.IDP, _ *sso.Flow) { i.NonceOverride = "other" }},
|
||||
{"wrong audience", func(i *ssotest.IDP, _ *sso.Flow) { i.AudienceOverride = "someone-else" }},
|
||||
{"wrong pkce verifier", func(_ *ssotest.IDP, f *sso.Flow) { f.Verifier = "x" + f.Verifier[1:] }},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
idp, c, p := setup(t)
|
||||
idp.SetUser(ssotest.User{Subject: "u-1"})
|
||||
ctx := context.Background()
|
||||
flow := sso.NewFlow(rand.Text)
|
||||
authURL, err := c.AuthURL(ctx, p, flow)
|
||||
if err != nil {
|
||||
t.Fatalf("AuthURL() failed: %v", err)
|
||||
}
|
||||
code, _ := authorize(t, authURL)
|
||||
tt.tamper(idp, &flow)
|
||||
if _, err := c.Exchange(ctx, p, flow, code); err == nil {
|
||||
t.Error("Exchange() error = nil, want rejection")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateIssuer(t *testing.T) {
|
||||
idp, _, _ := setup(t)
|
||||
strict := sso.New(sso.SafeHTTPClient(false), callback, false)
|
||||
tests := []struct {
|
||||
issuer string
|
||||
client *sso.Client
|
||||
want error
|
||||
}{
|
||||
{"ftp://idp.test", strict, sso.ErrInvalidIssuer},
|
||||
{"https://idp.test/?q=1", strict, sso.ErrInvalidIssuer},
|
||||
{"https://user@idp.test", strict, sso.ErrInvalidIssuer},
|
||||
{idp.Issuer(), strict, sso.ErrInvalidIssuer},
|
||||
{"https://127.0.0.1:1", strict, sso.ErrForbiddenAddress},
|
||||
{idp.Issuer(), sso.New(sso.SafeHTTPClient(true), callback, true), nil},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
err := tt.client.ValidateIssuer(context.Background(), tt.issuer)
|
||||
if !errors.Is(err, tt.want) {
|
||||
t.Errorf("ValidateIssuer(%q) = %v, want %v", tt.issuer, err, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
// Package ssotest provides a minimal OpenID Connect provider for tests.
|
||||
package ssotest
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-jose/go-jose/v4"
|
||||
"github.com/go-jose/go-jose/v4/jwt"
|
||||
)
|
||||
|
||||
// User is the identity the IDP asserts for the next login.
|
||||
type User struct {
|
||||
Subject string
|
||||
Email string
|
||||
EmailVerified bool
|
||||
Name string
|
||||
}
|
||||
|
||||
// IDP is an in-memory authorization server. It signs ID tokens with a fresh
|
||||
// RSA key and enforces PKCE.
|
||||
type IDP struct {
|
||||
Server *httptest.Server
|
||||
ClientID string
|
||||
Secret string
|
||||
|
||||
key *rsa.PrivateKey
|
||||
signer jose.Signer
|
||||
|
||||
mu sync.Mutex
|
||||
user User
|
||||
codes map[string]grant
|
||||
// NonceOverride, when set, replaces the nonce in issued tokens.
|
||||
NonceOverride string
|
||||
// AudienceOverride, when set, replaces the audience in issued tokens.
|
||||
AudienceOverride string
|
||||
}
|
||||
|
||||
type grant struct {
|
||||
nonce, challenge, redirect string
|
||||
user User
|
||||
}
|
||||
|
||||
// New starts an IDP that is shut down when t ends.
|
||||
func New(t *testing.T) *IDP {
|
||||
t.Helper()
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: jose.JSONWebKey{Key: key, KeyID: "k1"}}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
idp := &IDP{ClientID: "client-1", Secret: "secret-1", key: key, signer: signer, codes: map[string]grant{}}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /.well-known/openid-configuration", idp.discovery)
|
||||
mux.HandleFunc("GET /keys", idp.keys)
|
||||
mux.HandleFunc("GET /authorize", idp.authorize)
|
||||
mux.HandleFunc("POST /token", idp.token)
|
||||
idp.Server = httptest.NewServer(mux)
|
||||
t.Cleanup(idp.Server.Close)
|
||||
return idp
|
||||
}
|
||||
|
||||
// Issuer is the issuer URL to configure.
|
||||
func (i *IDP) Issuer() string { return i.Server.URL }
|
||||
|
||||
// SetUser selects who the next authorization asserts.
|
||||
func (i *IDP) SetUser(u User) {
|
||||
i.mu.Lock()
|
||||
defer i.mu.Unlock()
|
||||
i.user = u
|
||||
}
|
||||
|
||||
func (i *IDP) discovery(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, map[string]any{
|
||||
"issuer": i.Issuer(),
|
||||
"authorization_endpoint": i.Issuer() + "/authorize",
|
||||
"token_endpoint": i.Issuer() + "/token",
|
||||
"jwks_uri": i.Issuer() + "/keys",
|
||||
"response_types_supported": []string{"code"},
|
||||
"subject_types_supported": []string{"public"},
|
||||
"id_token_signing_alg_values_supported": []string{"RS256"},
|
||||
})
|
||||
}
|
||||
|
||||
func (i *IDP) keys(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{Key: &i.key.PublicKey, KeyID: "k1", Algorithm: "RS256", Use: "sig"}}})
|
||||
}
|
||||
|
||||
// authorize skips the login screen and immediately redirects back with a code.
|
||||
func (i *IDP) authorize(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
if q.Get("client_id") != i.ClientID || q.Get("code_challenge_method") != "S256" {
|
||||
http.Error(w, "bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
code := rand.Text()
|
||||
i.mu.Lock()
|
||||
i.codes[code] = grant{nonce: q.Get("nonce"), challenge: q.Get("code_challenge"), redirect: q.Get("redirect_uri"), user: i.user}
|
||||
i.mu.Unlock()
|
||||
back, _ := url.Parse(q.Get("redirect_uri"))
|
||||
v := back.Query()
|
||||
v.Set("code", code)
|
||||
v.Set("state", q.Get("state"))
|
||||
back.RawQuery = v.Encode()
|
||||
http.Redirect(w, r, back.String(), http.StatusFound)
|
||||
}
|
||||
|
||||
func (i *IDP) token(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "bad form", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
id, secret, ok := r.BasicAuth()
|
||||
if !ok {
|
||||
id, secret = r.PostForm.Get("client_id"), r.PostForm.Get("client_secret")
|
||||
}
|
||||
if id != i.ClientID || secret != i.Secret {
|
||||
http.Error(w, `{"error":"invalid_client"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
i.mu.Lock()
|
||||
g, ok := i.codes[r.PostForm.Get("code")]
|
||||
delete(i.codes, r.PostForm.Get("code"))
|
||||
i.mu.Unlock()
|
||||
sum := sha256.Sum256([]byte(r.PostForm.Get("code_verifier")))
|
||||
if !ok || base64.RawURLEncoding.EncodeToString(sum[:]) != g.challenge || r.PostForm.Get("redirect_uri") != g.redirect {
|
||||
http.Error(w, `{"error":"invalid_grant"}`, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
nonce, aud := g.nonce, i.ClientID
|
||||
if i.NonceOverride != "" {
|
||||
nonce = i.NonceOverride
|
||||
}
|
||||
if i.AudienceOverride != "" {
|
||||
aud = i.AudienceOverride
|
||||
}
|
||||
now := time.Now()
|
||||
claims := map[string]any{
|
||||
"iss": i.Issuer(), "sub": g.user.Subject, "aud": aud, "nonce": nonce,
|
||||
"iat": now.Unix(), "exp": now.Add(5 * time.Minute).Unix(),
|
||||
"email": g.user.Email, "email_verified": g.user.EmailVerified, "name": g.user.Name,
|
||||
}
|
||||
raw, err := jwt.Signed(i.signer).Claims(claims).Serialize()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]any{"access_token": "at", "token_type": "Bearer", "expires_in": 300, "id_token": raw})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: copyfrom.go
|
||||
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// iteratorForInsertRecoveryCodes implements pgx.CopyFromSource.
|
||||
type iteratorForInsertRecoveryCodes struct {
|
||||
rows []InsertRecoveryCodesParams
|
||||
skippedFirstNextCall bool
|
||||
}
|
||||
|
||||
func (r *iteratorForInsertRecoveryCodes) Next() bool {
|
||||
if len(r.rows) == 0 {
|
||||
return false
|
||||
}
|
||||
if !r.skippedFirstNextCall {
|
||||
r.skippedFirstNextCall = true
|
||||
return true
|
||||
}
|
||||
r.rows = r.rows[1:]
|
||||
return len(r.rows) > 0
|
||||
}
|
||||
|
||||
func (r iteratorForInsertRecoveryCodes) Values() ([]interface{}, error) {
|
||||
return []interface{}{
|
||||
r.rows[0].UserID,
|
||||
r.rows[0].CodeHash,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r iteratorForInsertRecoveryCodes) Err() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (q *Queries) InsertRecoveryCodes(ctx context.Context, arg []InsertRecoveryCodesParams) (int64, error) {
|
||||
return q.db.CopyFrom(ctx, []string{"recovery_codes"}, []string{"user_id", "code_hash"}, &iteratorForInsertRecoveryCodes{rows: arg})
|
||||
}
|
||||
@@ -15,6 +15,7 @@ type DBTX interface {
|
||||
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
|
||||
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
|
||||
QueryRow(context.Context, string, ...interface{}) pgx.Row
|
||||
CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error)
|
||||
}
|
||||
|
||||
func New(db DBTX) *Queries {
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: memberships.sql
|
||||
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const addMembership = `-- name: AddMembership :exec
|
||||
INSERT INTO memberships (org_id, user_id, is_owner) VALUES ($1, $2, $3)
|
||||
`
|
||||
|
||||
type AddMembershipParams struct {
|
||||
OrgID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
IsOwner bool
|
||||
}
|
||||
|
||||
func (q *Queries) AddMembership(ctx context.Context, arg AddMembershipParams) error {
|
||||
_, err := q.db.Exec(ctx, addMembership, arg.OrgID, arg.UserID, arg.IsOwner)
|
||||
return err
|
||||
}
|
||||
|
||||
const getMembership = `-- name: GetMembership :one
|
||||
SELECT org_id, user_id, is_owner, created_at FROM memberships WHERE org_id = $1 AND user_id = $2
|
||||
`
|
||||
|
||||
type GetMembershipParams struct {
|
||||
OrgID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error) {
|
||||
row := q.db.QueryRow(ctx, getMembership, arg.OrgID, arg.UserID)
|
||||
var i Membership
|
||||
err := row.Scan(
|
||||
&i.OrgID,
|
||||
&i.UserID,
|
||||
&i.IsOwner,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const listOrgMembers = `-- name: ListOrgMembers :many
|
||||
SELECT u.id, u.email, u.display_name, m.is_owner, m.created_at AS joined_at
|
||||
FROM memberships m
|
||||
JOIN users u ON u.id = m.user_id
|
||||
WHERE m.org_id = $1
|
||||
ORDER BY u.email
|
||||
`
|
||||
|
||||
type ListOrgMembersRow struct {
|
||||
ID uuid.UUID
|
||||
Email string
|
||||
DisplayName string
|
||||
IsOwner bool
|
||||
JoinedAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error) {
|
||||
rows, err := q.db.Query(ctx, listOrgMembers, orgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListOrgMembersRow{}
|
||||
for rows.Next() {
|
||||
var i ListOrgMembersRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Email,
|
||||
&i.DisplayName,
|
||||
&i.IsOwner,
|
||||
&i.JoinedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listUserOrgs = `-- name: ListUserOrgs :many
|
||||
SELECT o.id, o.slug, o.name, o.require_totp, m.is_owner
|
||||
FROM memberships m
|
||||
JOIN orgs o ON o.id = m.org_id
|
||||
WHERE m.user_id = $1
|
||||
ORDER BY o.name
|
||||
`
|
||||
|
||||
type ListUserOrgsRow struct {
|
||||
ID uuid.UUID
|
||||
Slug string
|
||||
Name string
|
||||
RequireTotp bool
|
||||
IsOwner bool
|
||||
}
|
||||
|
||||
func (q *Queries) ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listUserOrgs, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListUserOrgsRow{}
|
||||
for rows.Next() {
|
||||
var i ListUserOrgsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Slug,
|
||||
&i.Name,
|
||||
&i.RequireTotp,
|
||||
&i.IsOwner,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const removeMembership = `-- name: RemoveMembership :execrows
|
||||
DELETE FROM memberships WHERE org_id = $1 AND user_id = $2 AND NOT is_owner
|
||||
`
|
||||
|
||||
type RemoveMembershipParams struct {
|
||||
OrgID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, removeMembership, arg.OrgID, arg.UserID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
@@ -10,10 +10,63 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Org struct {
|
||||
ID uuid.UUID
|
||||
Slug string
|
||||
Name string
|
||||
type Membership struct {
|
||||
OrgID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
IsOwner bool
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type Org struct {
|
||||
ID uuid.UUID
|
||||
Slug string
|
||||
Name string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
RequireTotp bool
|
||||
}
|
||||
|
||||
type RecoveryCode struct {
|
||||
UserID uuid.UUID
|
||||
CodeHash []byte
|
||||
UsedAt *time.Time
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type SsoProvider struct {
|
||||
ID uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
Name string
|
||||
Issuer string
|
||||
ClientID string
|
||||
ClientSecret []byte
|
||||
Scopes []string
|
||||
AllowedDomains []string
|
||||
AutoProvision bool
|
||||
Enabled bool
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID
|
||||
Email string
|
||||
DisplayName string
|
||||
PasswordHash *string
|
||||
DisabledAt *time.Time
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
TotpSecret []byte
|
||||
TotpEnabledAt *time.Time
|
||||
Locale *string
|
||||
}
|
||||
|
||||
type UserIdentity struct {
|
||||
ProviderID uuid.UUID
|
||||
Subject string
|
||||
OrgID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
Email *string
|
||||
CreatedAt time.Time
|
||||
LastLoginAt time.Time
|
||||
}
|
||||
@@ -7,20 +7,23 @@ package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const createOrg = `-- name: CreateOrg :one
|
||||
INSERT INTO orgs (slug, name) VALUES ($1, $2)
|
||||
RETURNING id, slug, name, created_at, updated_at
|
||||
INSERT INTO orgs (id, slug, name) VALUES ($1, $2, $3)
|
||||
RETURNING id, slug, name, created_at, updated_at, require_totp
|
||||
`
|
||||
|
||||
type CreateOrgParams struct {
|
||||
ID uuid.UUID
|
||||
Slug string
|
||||
Name string
|
||||
}
|
||||
|
||||
func (q *Queries) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error) {
|
||||
row := q.db.QueryRow(ctx, createOrg, arg.Slug, arg.Name)
|
||||
row := q.db.QueryRow(ctx, createOrg, arg.ID, arg.Slug, arg.Name)
|
||||
var i Org
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
@@ -28,12 +31,43 @@ func (q *Queries) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, erro
|
||||
&i.Name,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.RequireTotp,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const deleteOrg = `-- name: DeleteOrg :execrows
|
||||
DELETE FROM orgs WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, deleteOrg, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const getOrg = `-- name: GetOrg :one
|
||||
SELECT id, slug, name, created_at, updated_at, require_totp FROM orgs WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) {
|
||||
row := q.db.QueryRow(ctx, getOrg, id)
|
||||
var i Org
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Slug,
|
||||
&i.Name,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.RequireTotp,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getOrgBySlug = `-- name: GetOrgBySlug :one
|
||||
SELECT id, slug, name, created_at, updated_at FROM orgs WHERE slug = $1
|
||||
SELECT id, slug, name, created_at, updated_at, require_totp FROM orgs WHERE slug = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) {
|
||||
@@ -45,6 +79,38 @@ func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) {
|
||||
&i.Name,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.RequireTotp,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const listOrgs = `-- name: ListOrgs :many
|
||||
SELECT id, slug, name, created_at, updated_at, require_totp FROM orgs ORDER BY name
|
||||
`
|
||||
|
||||
func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) {
|
||||
rows, err := q.db.Query(ctx, listOrgs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []Org{}
|
||||
for rows.Next() {
|
||||
var i Org
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Slug,
|
||||
&i.Name,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.RequireTotp,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -6,11 +6,46 @@ package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Querier interface {
|
||||
AddMembership(ctx context.Context, arg AddMembershipParams) error
|
||||
AnyUserExists(ctx context.Context) (bool, error)
|
||||
CountUnusedRecoveryCodes(ctx context.Context, userID uuid.UUID) (int64, error)
|
||||
CreateIdentity(ctx context.Context, arg CreateIdentityParams) error
|
||||
CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error)
|
||||
CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error)
|
||||
CreateUser(ctx context.Context, arg CreateUserParams) (User, error)
|
||||
DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error)
|
||||
DeleteRecoveryCodes(ctx context.Context, userID uuid.UUID) error
|
||||
DeleteSSOProvider(ctx context.Context, id uuid.UUID) (int64, error)
|
||||
DeleteUser(ctx context.Context, id uuid.UUID) (int64, error)
|
||||
DisableTOTP(ctx context.Context, id uuid.UUID) error
|
||||
EnableTOTP(ctx context.Context, arg EnableTOTPParams) error
|
||||
GetIdentity(ctx context.Context, arg GetIdentityParams) (UserIdentity, error)
|
||||
GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error)
|
||||
GetOrg(ctx context.Context, id uuid.UUID) (Org, error)
|
||||
GetOrgBySlug(ctx context.Context, slug string) (Org, error)
|
||||
GetSSOProvider(ctx context.Context, id uuid.UUID) (SsoProvider, error)
|
||||
GetUser(ctx context.Context, id uuid.UUID) (User, error)
|
||||
GetUserByEmail(ctx context.Context, email string) (User, error)
|
||||
InsertRecoveryCodes(ctx context.Context, arg []InsertRecoveryCodesParams) (int64, error)
|
||||
IsMember(ctx context.Context, arg IsMemberParams) (bool, error)
|
||||
ListEnabledSSOProviders(ctx context.Context) ([]ListEnabledSSOProvidersRow, error)
|
||||
ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error)
|
||||
ListOrgs(ctx context.Context) ([]Org, error)
|
||||
ListSSOProviders(ctx context.Context) ([]SsoProvider, error)
|
||||
ListUserIdentitiesInOrg(ctx context.Context, userID uuid.UUID) ([]ListUserIdentitiesInOrgRow, error)
|
||||
ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error)
|
||||
OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error)
|
||||
RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error)
|
||||
SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error
|
||||
SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error
|
||||
TouchIdentity(ctx context.Context, arg TouchIdentityParams) error
|
||||
UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error)
|
||||
UseRecoveryCode(ctx context.Context, arg UseRecoveryCodeParams) (int64, error)
|
||||
}
|
||||
|
||||
var _ Querier = (*Queries)(nil)
|
||||
@@ -0,0 +1,22 @@
|
||||
-- name: AddMembership :exec
|
||||
INSERT INTO memberships (org_id, user_id, is_owner) VALUES ($1, $2, $3);
|
||||
|
||||
-- name: RemoveMembership :execrows
|
||||
DELETE FROM memberships WHERE org_id = $1 AND user_id = $2 AND NOT is_owner;
|
||||
|
||||
-- name: ListOrgMembers :many
|
||||
SELECT u.id, u.email, u.display_name, m.is_owner, m.created_at AS joined_at
|
||||
FROM memberships m
|
||||
JOIN users u ON u.id = m.user_id
|
||||
WHERE m.org_id = $1
|
||||
ORDER BY u.email;
|
||||
|
||||
-- name: ListUserOrgs :many
|
||||
SELECT o.id, o.slug, o.name, o.require_totp, m.is_owner
|
||||
FROM memberships m
|
||||
JOIN orgs o ON o.id = m.org_id
|
||||
WHERE m.user_id = $1
|
||||
ORDER BY o.name;
|
||||
|
||||
-- name: GetMembership :one
|
||||
SELECT * FROM memberships WHERE org_id = $1 AND user_id = $2;
|
||||
@@ -1,6 +1,15 @@
|
||||
-- name: CreateOrg :one
|
||||
INSERT INTO orgs (slug, name) VALUES ($1, $2)
|
||||
INSERT INTO orgs (id, slug, name) VALUES ($1, $2, $3)
|
||||
RETURNING *;
|
||||
|
||||
-- name: GetOrg :one
|
||||
SELECT * FROM orgs WHERE id = $1;
|
||||
|
||||
-- name: GetOrgBySlug :one
|
||||
SELECT * FROM orgs WHERE slug = $1;
|
||||
|
||||
-- name: ListOrgs :many
|
||||
SELECT * FROM orgs ORDER BY name;
|
||||
|
||||
-- name: DeleteOrg :execrows
|
||||
DELETE FROM orgs WHERE id = $1;
|
||||
@@ -0,0 +1,12 @@
|
||||
-- name: DeleteRecoveryCodes :exec
|
||||
DELETE FROM recovery_codes WHERE user_id = $1;
|
||||
|
||||
-- name: InsertRecoveryCodes :copyfrom
|
||||
INSERT INTO recovery_codes (user_id, code_hash) VALUES ($1, $2);
|
||||
|
||||
-- name: UseRecoveryCode :execrows
|
||||
UPDATE recovery_codes SET used_at = now()
|
||||
WHERE user_id = $1 AND code_hash = $2 AND used_at IS NULL;
|
||||
|
||||
-- name: CountUnusedRecoveryCodes :one
|
||||
SELECT count(*) FROM recovery_codes WHERE user_id = $1 AND used_at IS NULL;
|
||||
@@ -0,0 +1,54 @@
|
||||
-- name: OrgIDBySlug :one
|
||||
SELECT coalesce(org_id_by_slug(sqlc.arg(slug)::citext), '00000000-0000-0000-0000-000000000000')::uuid AS id;
|
||||
|
||||
-- name: CreateSSOProvider :one
|
||||
INSERT INTO sso_providers (id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
RETURNING *;
|
||||
|
||||
-- name: UpdateSSOProvider :one
|
||||
UPDATE sso_providers SET
|
||||
name = $2,
|
||||
issuer = $3,
|
||||
client_id = $4,
|
||||
client_secret = coalesce(sqlc.narg(client_secret), client_secret),
|
||||
scopes = $5,
|
||||
allowed_domains = $6,
|
||||
auto_provision = $7,
|
||||
enabled = $8,
|
||||
updated_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING *;
|
||||
|
||||
-- name: DeleteSSOProvider :execrows
|
||||
DELETE FROM sso_providers WHERE id = $1;
|
||||
|
||||
-- name: GetSSOProvider :one
|
||||
SELECT * FROM sso_providers WHERE id = $1;
|
||||
|
||||
-- name: ListSSOProviders :many
|
||||
SELECT * FROM sso_providers ORDER BY name;
|
||||
|
||||
-- name: ListEnabledSSOProviders :many
|
||||
SELECT id, name FROM sso_providers WHERE enabled ORDER BY name;
|
||||
|
||||
-- name: GetIdentity :one
|
||||
SELECT * FROM user_identities WHERE provider_id = $1 AND subject = $2;
|
||||
|
||||
-- name: CreateIdentity :exec
|
||||
INSERT INTO user_identities (provider_id, subject, org_id, user_id, email)
|
||||
VALUES ($1, $2, $3, $4, $5);
|
||||
|
||||
-- name: TouchIdentity :exec
|
||||
UPDATE user_identities SET email = $3, last_login_at = now()
|
||||
WHERE provider_id = $1 AND subject = $2;
|
||||
|
||||
-- name: IsMember :one
|
||||
SELECT EXISTS (SELECT 1 FROM memberships WHERE org_id = $1 AND user_id = $2);
|
||||
|
||||
-- name: ListUserIdentitiesInOrg :many
|
||||
SELECT p.name AS provider_name, i.email, i.created_at, i.last_login_at
|
||||
FROM user_identities i
|
||||
JOIN sso_providers p ON p.id = i.provider_id
|
||||
WHERE i.user_id = $1
|
||||
ORDER BY p.name;
|
||||
@@ -0,0 +1,27 @@
|
||||
-- name: CreateUser :one
|
||||
INSERT INTO users (email, display_name, password_hash, locale) VALUES ($1, $2, $3, $4)
|
||||
RETURNING *;
|
||||
|
||||
-- name: GetUser :one
|
||||
SELECT * FROM users WHERE id = $1;
|
||||
|
||||
-- name: GetUserByEmail :one
|
||||
SELECT * FROM users WHERE email = $1;
|
||||
|
||||
-- name: AnyUserExists :one
|
||||
SELECT EXISTS (SELECT 1 FROM users);
|
||||
|
||||
-- name: SetPasswordHash :exec
|
||||
UPDATE users SET password_hash = $2, updated_at = now() WHERE id = $1;
|
||||
|
||||
-- name: EnableTOTP :exec
|
||||
UPDATE users SET totp_secret = $2, totp_enabled_at = now(), updated_at = now() WHERE id = $1;
|
||||
|
||||
-- name: DisableTOTP :exec
|
||||
UPDATE users SET totp_secret = NULL, totp_enabled_at = NULL, updated_at = now() WHERE id = $1;
|
||||
|
||||
-- name: DeleteUser :execrows
|
||||
DELETE FROM users WHERE id = $1;
|
||||
|
||||
-- name: SetUserLocale :exec
|
||||
UPDATE users SET locale = $2, updated_at = now() WHERE id = $1;
|
||||
@@ -0,0 +1,55 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: recovery_codes.sql
|
||||
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const countUnusedRecoveryCodes = `-- name: CountUnusedRecoveryCodes :one
|
||||
SELECT count(*) FROM recovery_codes WHERE user_id = $1 AND used_at IS NULL
|
||||
`
|
||||
|
||||
func (q *Queries) CountUnusedRecoveryCodes(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, countUnusedRecoveryCodes, userID)
|
||||
var count int64
|
||||
err := row.Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
const deleteRecoveryCodes = `-- name: DeleteRecoveryCodes :exec
|
||||
DELETE FROM recovery_codes WHERE user_id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteRecoveryCodes(ctx context.Context, userID uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, deleteRecoveryCodes, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
type InsertRecoveryCodesParams struct {
|
||||
UserID uuid.UUID
|
||||
CodeHash []byte
|
||||
}
|
||||
|
||||
const useRecoveryCode = `-- name: UseRecoveryCode :execrows
|
||||
UPDATE recovery_codes SET used_at = now()
|
||||
WHERE user_id = $1 AND code_hash = $2 AND used_at IS NULL
|
||||
`
|
||||
|
||||
type UseRecoveryCodeParams struct {
|
||||
UserID uuid.UUID
|
||||
CodeHash []byte
|
||||
}
|
||||
|
||||
func (q *Queries) UseRecoveryCode(ctx context.Context, arg UseRecoveryCodeParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, useRecoveryCode, arg.UserID, arg.CodeHash)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: sso.sql
|
||||
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const createIdentity = `-- name: CreateIdentity :exec
|
||||
INSERT INTO user_identities (provider_id, subject, org_id, user_id, email)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`
|
||||
|
||||
type CreateIdentityParams struct {
|
||||
ProviderID uuid.UUID
|
||||
Subject string
|
||||
OrgID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
Email *string
|
||||
}
|
||||
|
||||
func (q *Queries) CreateIdentity(ctx context.Context, arg CreateIdentityParams) error {
|
||||
_, err := q.db.Exec(ctx, createIdentity,
|
||||
arg.ProviderID,
|
||||
arg.Subject,
|
||||
arg.OrgID,
|
||||
arg.UserID,
|
||||
arg.Email,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const createSSOProvider = `-- name: CreateSSOProvider :one
|
||||
INSERT INTO sso_providers (id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
RETURNING id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at
|
||||
`
|
||||
|
||||
type CreateSSOProviderParams struct {
|
||||
ID uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
Name string
|
||||
Issuer string
|
||||
ClientID string
|
||||
ClientSecret []byte
|
||||
Scopes []string
|
||||
AllowedDomains []string
|
||||
AutoProvision bool
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
func (q *Queries) CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error) {
|
||||
row := q.db.QueryRow(ctx, createSSOProvider,
|
||||
arg.ID,
|
||||
arg.OrgID,
|
||||
arg.Name,
|
||||
arg.Issuer,
|
||||
arg.ClientID,
|
||||
arg.ClientSecret,
|
||||
arg.Scopes,
|
||||
arg.AllowedDomains,
|
||||
arg.AutoProvision,
|
||||
arg.Enabled,
|
||||
)
|
||||
var i SsoProvider
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Name,
|
||||
&i.Issuer,
|
||||
&i.ClientID,
|
||||
&i.ClientSecret,
|
||||
&i.Scopes,
|
||||
&i.AllowedDomains,
|
||||
&i.AutoProvision,
|
||||
&i.Enabled,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const deleteSSOProvider = `-- name: DeleteSSOProvider :execrows
|
||||
DELETE FROM sso_providers WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteSSOProvider(ctx context.Context, id uuid.UUID) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, deleteSSOProvider, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const getIdentity = `-- name: GetIdentity :one
|
||||
SELECT provider_id, subject, org_id, user_id, email, created_at, last_login_at FROM user_identities WHERE provider_id = $1 AND subject = $2
|
||||
`
|
||||
|
||||
type GetIdentityParams struct {
|
||||
ProviderID uuid.UUID
|
||||
Subject string
|
||||
}
|
||||
|
||||
func (q *Queries) GetIdentity(ctx context.Context, arg GetIdentityParams) (UserIdentity, error) {
|
||||
row := q.db.QueryRow(ctx, getIdentity, arg.ProviderID, arg.Subject)
|
||||
var i UserIdentity
|
||||
err := row.Scan(
|
||||
&i.ProviderID,
|
||||
&i.Subject,
|
||||
&i.OrgID,
|
||||
&i.UserID,
|
||||
&i.Email,
|
||||
&i.CreatedAt,
|
||||
&i.LastLoginAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getSSOProvider = `-- name: GetSSOProvider :one
|
||||
SELECT id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at FROM sso_providers WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetSSOProvider(ctx context.Context, id uuid.UUID) (SsoProvider, error) {
|
||||
row := q.db.QueryRow(ctx, getSSOProvider, id)
|
||||
var i SsoProvider
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Name,
|
||||
&i.Issuer,
|
||||
&i.ClientID,
|
||||
&i.ClientSecret,
|
||||
&i.Scopes,
|
||||
&i.AllowedDomains,
|
||||
&i.AutoProvision,
|
||||
&i.Enabled,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const isMember = `-- name: IsMember :one
|
||||
SELECT EXISTS (SELECT 1 FROM memberships WHERE org_id = $1 AND user_id = $2)
|
||||
`
|
||||
|
||||
type IsMemberParams struct {
|
||||
OrgID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) IsMember(ctx context.Context, arg IsMemberParams) (bool, error) {
|
||||
row := q.db.QueryRow(ctx, isMember, arg.OrgID, arg.UserID)
|
||||
var exists bool
|
||||
err := row.Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
const listEnabledSSOProviders = `-- name: ListEnabledSSOProviders :many
|
||||
SELECT id, name FROM sso_providers WHERE enabled ORDER BY name
|
||||
`
|
||||
|
||||
type ListEnabledSSOProvidersRow struct {
|
||||
ID uuid.UUID
|
||||
Name string
|
||||
}
|
||||
|
||||
func (q *Queries) ListEnabledSSOProviders(ctx context.Context) ([]ListEnabledSSOProvidersRow, error) {
|
||||
rows, err := q.db.Query(ctx, listEnabledSSOProviders)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListEnabledSSOProvidersRow{}
|
||||
for rows.Next() {
|
||||
var i ListEnabledSSOProvidersRow
|
||||
if err := rows.Scan(&i.ID, &i.Name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listSSOProviders = `-- name: ListSSOProviders :many
|
||||
SELECT id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at FROM sso_providers ORDER BY name
|
||||
`
|
||||
|
||||
func (q *Queries) ListSSOProviders(ctx context.Context) ([]SsoProvider, error) {
|
||||
rows, err := q.db.Query(ctx, listSSOProviders)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []SsoProvider{}
|
||||
for rows.Next() {
|
||||
var i SsoProvider
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Name,
|
||||
&i.Issuer,
|
||||
&i.ClientID,
|
||||
&i.ClientSecret,
|
||||
&i.Scopes,
|
||||
&i.AllowedDomains,
|
||||
&i.AutoProvision,
|
||||
&i.Enabled,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listUserIdentitiesInOrg = `-- name: ListUserIdentitiesInOrg :many
|
||||
SELECT p.name AS provider_name, i.email, i.created_at, i.last_login_at
|
||||
FROM user_identities i
|
||||
JOIN sso_providers p ON p.id = i.provider_id
|
||||
WHERE i.user_id = $1
|
||||
ORDER BY p.name
|
||||
`
|
||||
|
||||
type ListUserIdentitiesInOrgRow struct {
|
||||
ProviderName string
|
||||
Email *string
|
||||
CreatedAt time.Time
|
||||
LastLoginAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) ListUserIdentitiesInOrg(ctx context.Context, userID uuid.UUID) ([]ListUserIdentitiesInOrgRow, error) {
|
||||
rows, err := q.db.Query(ctx, listUserIdentitiesInOrg, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListUserIdentitiesInOrgRow{}
|
||||
for rows.Next() {
|
||||
var i ListUserIdentitiesInOrgRow
|
||||
if err := rows.Scan(
|
||||
&i.ProviderName,
|
||||
&i.Email,
|
||||
&i.CreatedAt,
|
||||
&i.LastLoginAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const orgIDBySlug = `-- name: OrgIDBySlug :one
|
||||
SELECT coalesce(org_id_by_slug($1::citext), '00000000-0000-0000-0000-000000000000')::uuid AS id
|
||||
`
|
||||
|
||||
func (q *Queries) OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, orgIDBySlug, slug)
|
||||
var id uuid.UUID
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
const touchIdentity = `-- name: TouchIdentity :exec
|
||||
UPDATE user_identities SET email = $3, last_login_at = now()
|
||||
WHERE provider_id = $1 AND subject = $2
|
||||
`
|
||||
|
||||
type TouchIdentityParams struct {
|
||||
ProviderID uuid.UUID
|
||||
Subject string
|
||||
Email *string
|
||||
}
|
||||
|
||||
func (q *Queries) TouchIdentity(ctx context.Context, arg TouchIdentityParams) error {
|
||||
_, err := q.db.Exec(ctx, touchIdentity, arg.ProviderID, arg.Subject, arg.Email)
|
||||
return err
|
||||
}
|
||||
|
||||
const updateSSOProvider = `-- name: UpdateSSOProvider :one
|
||||
UPDATE sso_providers SET
|
||||
name = $2,
|
||||
issuer = $3,
|
||||
client_id = $4,
|
||||
client_secret = coalesce($9, client_secret),
|
||||
scopes = $5,
|
||||
allowed_domains = $6,
|
||||
auto_provision = $7,
|
||||
enabled = $8,
|
||||
updated_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at
|
||||
`
|
||||
|
||||
type UpdateSSOProviderParams struct {
|
||||
ID uuid.UUID
|
||||
Name string
|
||||
Issuer string
|
||||
ClientID string
|
||||
Scopes []string
|
||||
AllowedDomains []string
|
||||
AutoProvision bool
|
||||
Enabled bool
|
||||
ClientSecret []byte
|
||||
}
|
||||
|
||||
func (q *Queries) UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error) {
|
||||
row := q.db.QueryRow(ctx, updateSSOProvider,
|
||||
arg.ID,
|
||||
arg.Name,
|
||||
arg.Issuer,
|
||||
arg.ClientID,
|
||||
arg.Scopes,
|
||||
arg.AllowedDomains,
|
||||
arg.AutoProvision,
|
||||
arg.Enabled,
|
||||
arg.ClientSecret,
|
||||
)
|
||||
var i SsoProvider
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Name,
|
||||
&i.Issuer,
|
||||
&i.ClientID,
|
||||
&i.ClientSecret,
|
||||
&i.Scopes,
|
||||
&i.AllowedDomains,
|
||||
&i.AutoProvision,
|
||||
&i.Enabled,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: users.sql
|
||||
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const anyUserExists = `-- name: AnyUserExists :one
|
||||
SELECT EXISTS (SELECT 1 FROM users)
|
||||
`
|
||||
|
||||
func (q *Queries) AnyUserExists(ctx context.Context) (bool, error) {
|
||||
row := q.db.QueryRow(ctx, anyUserExists)
|
||||
var exists bool
|
||||
err := row.Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
const createUser = `-- name: CreateUser :one
|
||||
INSERT INTO users (email, display_name, password_hash, locale) VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at, locale
|
||||
`
|
||||
|
||||
type CreateUserParams struct {
|
||||
Email string
|
||||
DisplayName string
|
||||
PasswordHash *string
|
||||
Locale *string
|
||||
}
|
||||
|
||||
func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, error) {
|
||||
row := q.db.QueryRow(ctx, createUser,
|
||||
arg.Email,
|
||||
arg.DisplayName,
|
||||
arg.PasswordHash,
|
||||
arg.Locale,
|
||||
)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Email,
|
||||
&i.DisplayName,
|
||||
&i.PasswordHash,
|
||||
&i.DisabledAt,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.TotpSecret,
|
||||
&i.TotpEnabledAt,
|
||||
&i.Locale,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const deleteUser = `-- name: DeleteUser :execrows
|
||||
DELETE FROM users WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteUser(ctx context.Context, id uuid.UUID) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, deleteUser, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const disableTOTP = `-- name: DisableTOTP :exec
|
||||
UPDATE users SET totp_secret = NULL, totp_enabled_at = NULL, updated_at = now() WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) DisableTOTP(ctx context.Context, id uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, disableTOTP, id)
|
||||
return err
|
||||
}
|
||||
|
||||
const enableTOTP = `-- name: EnableTOTP :exec
|
||||
UPDATE users SET totp_secret = $2, totp_enabled_at = now(), updated_at = now() WHERE id = $1
|
||||
`
|
||||
|
||||
type EnableTOTPParams struct {
|
||||
ID uuid.UUID
|
||||
TotpSecret []byte
|
||||
}
|
||||
|
||||
func (q *Queries) EnableTOTP(ctx context.Context, arg EnableTOTPParams) error {
|
||||
_, err := q.db.Exec(ctx, enableTOTP, arg.ID, arg.TotpSecret)
|
||||
return err
|
||||
}
|
||||
|
||||
const getUser = `-- name: GetUser :one
|
||||
SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at, locale FROM users WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (User, error) {
|
||||
row := q.db.QueryRow(ctx, getUser, id)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Email,
|
||||
&i.DisplayName,
|
||||
&i.PasswordHash,
|
||||
&i.DisabledAt,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.TotpSecret,
|
||||
&i.TotpEnabledAt,
|
||||
&i.Locale,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getUserByEmail = `-- name: GetUserByEmail :one
|
||||
SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at, locale FROM users WHERE email = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error) {
|
||||
row := q.db.QueryRow(ctx, getUserByEmail, email)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Email,
|
||||
&i.DisplayName,
|
||||
&i.PasswordHash,
|
||||
&i.DisabledAt,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.TotpSecret,
|
||||
&i.TotpEnabledAt,
|
||||
&i.Locale,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const setPasswordHash = `-- name: SetPasswordHash :exec
|
||||
UPDATE users SET password_hash = $2, updated_at = now() WHERE id = $1
|
||||
`
|
||||
|
||||
type SetPasswordHashParams struct {
|
||||
ID uuid.UUID
|
||||
PasswordHash *string
|
||||
}
|
||||
|
||||
func (q *Queries) SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error {
|
||||
_, err := q.db.Exec(ctx, setPasswordHash, arg.ID, arg.PasswordHash)
|
||||
return err
|
||||
}
|
||||
|
||||
const setUserLocale = `-- name: SetUserLocale :exec
|
||||
UPDATE users SET locale = $2, updated_at = now() WHERE id = $1
|
||||
`
|
||||
|
||||
type SetUserLocaleParams struct {
|
||||
ID uuid.UUID
|
||||
Locale *string
|
||||
}
|
||||
|
||||
func (q *Queries) SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error {
|
||||
_, err := q.db.Exec(ctx, setUserLocale, arg.ID, arg.Locale)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Package tenant runs queries inside a row-level-security context. All
|
||||
// database access from request handlers must go through DB.Tx.
|
||||
package tenant
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
)
|
||||
|
||||
// Scope is the row-level-security context of one transaction. The zero value
|
||||
// sees nothing.
|
||||
type Scope struct {
|
||||
OrgID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
system bool
|
||||
global bool
|
||||
}
|
||||
|
||||
// Org scopes to one organization. user may be uuid.Nil for background work.
|
||||
func Org(org, user uuid.UUID) Scope { return Scope{OrgID: org, UserID: user} }
|
||||
|
||||
// User grants access to the user's own memberships and the orgs behind them,
|
||||
// which is what login and the org switcher need before an org is chosen.
|
||||
func User(user uuid.UUID) Scope { return Scope{UserID: user} }
|
||||
|
||||
// Global carries no tenant context: only tables without row-level security,
|
||||
// such as users, are usable. Login runs here before the user is known.
|
||||
func Global() Scope { return Scope{global: true} }
|
||||
|
||||
// System bypasses tenant isolation. Reserve it for work that is inherently
|
||||
// cross-tenant, never for request handling.
|
||||
func System() Scope { return Scope{system: true} }
|
||||
|
||||
// ErrNoScope is returned by Tx for the zero Scope.
|
||||
var ErrNoScope = errors.New("tenant: empty scope")
|
||||
|
||||
// DB wraps a pool so that every transaction carries a Scope.
|
||||
type DB struct{ pool *pgxpool.Pool }
|
||||
|
||||
// New returns a DB using pool.
|
||||
func New(pool *pgxpool.Pool) *DB { return &DB{pool: pool} }
|
||||
|
||||
// Tx runs fn in a transaction whose row-level-security settings come from s.
|
||||
// The transaction commits if fn returns nil and rolls back otherwise.
|
||||
func (d *DB) Tx(ctx context.Context, s Scope, fn func(*store.Queries) error) error {
|
||||
if s == (Scope{}) {
|
||||
return ErrNoScope
|
||||
}
|
||||
return pgx.BeginFunc(ctx, d.pool, func(tx pgx.Tx) error {
|
||||
if _, err := tx.Exec(ctx,
|
||||
`SELECT set_config('app.org_id', $1, true), set_config('app.user_id', $2, true), set_config('app.scope', $3, true)`,
|
||||
idOrEmpty(s.OrgID), idOrEmpty(s.UserID), scopeName(s),
|
||||
); err != nil {
|
||||
return fmt.Errorf("tenant: %w", err)
|
||||
}
|
||||
return fn(store.New(tx))
|
||||
})
|
||||
}
|
||||
|
||||
func idOrEmpty(id uuid.UUID) string {
|
||||
if id == uuid.Nil {
|
||||
return ""
|
||||
}
|
||||
return id.String()
|
||||
}
|
||||
|
||||
func scopeName(s Scope) string {
|
||||
if s.system {
|
||||
return "system"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package tenant_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/migrations"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
func setup(t *testing.T) (*tenant.DB, *pgxpool.Pool) {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("UPTIME_TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("UPTIME_TEST_DATABASE_URL not set")
|
||||
}
|
||||
ctx := context.Background()
|
||||
if _, err := migrations.Up(ctx, dsn); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pool, err := pgxpool.New(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
var bypass bool
|
||||
if err := pool.QueryRow(ctx, `SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user`).Scan(&bypass); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bypass {
|
||||
t.Fatal("test database role bypasses row-level security; connect as a non-superuser role")
|
||||
}
|
||||
return tenant.New(pool), pool
|
||||
}
|
||||
|
||||
type fixture struct {
|
||||
orgA, orgB store.Org
|
||||
alice, bob store.User
|
||||
}
|
||||
|
||||
func seed(t *testing.T, db *tenant.DB) fixture {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
var f fixture
|
||||
suffix := uuid.NewString()[:8]
|
||||
err := db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if f.orgA, err = q.CreateOrg(ctx, store.CreateOrgParams{ID: uuid.New(), Slug: "a-" + suffix, Name: "A"}); err != nil {
|
||||
return err
|
||||
}
|
||||
if f.orgB, err = q.CreateOrg(ctx, store.CreateOrgParams{ID: uuid.New(), Slug: "b-" + suffix, Name: "B"}); err != nil {
|
||||
return err
|
||||
}
|
||||
if f.alice, err = q.CreateUser(ctx, store.CreateUserParams{Email: "alice-" + suffix + "@example.test"}); err != nil {
|
||||
return err
|
||||
}
|
||||
if f.bob, err = q.CreateUser(ctx, store.CreateUserParams{Email: "bob-" + suffix + "@example.test"}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: f.orgA.ID, UserID: f.alice.ID, IsOwner: true}); err != nil {
|
||||
return err
|
||||
}
|
||||
return q.AddMembership(ctx, store.AddMembershipParams{OrgID: f.orgB.ID, UserID: f.bob.ID, IsOwner: true})
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = db.Tx(context.Background(), tenant.System(), func(q *store.Queries) error {
|
||||
for _, id := range []uuid.UUID{f.orgA.ID, f.orgB.ID} {
|
||||
if _, err := q.DeleteOrg(context.Background(), id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, id := range []uuid.UUID{f.alice.ID, f.bob.ID} {
|
||||
if _, err := q.DeleteUser(context.Background(), id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
})
|
||||
return f
|
||||
}
|
||||
|
||||
func TestOrgScopeHidesOtherTenants(t *testing.T) {
|
||||
db, _ := setup(t)
|
||||
f := seed(t, db)
|
||||
ctx := context.Background()
|
||||
|
||||
err := db.Tx(ctx, tenant.Org(f.orgA.ID, f.alice.ID), func(q *store.Queries) error {
|
||||
if _, err := q.GetOrg(ctx, f.orgA.ID); err != nil {
|
||||
t.Errorf("GetOrg(own org) error = %v, want nil", err)
|
||||
}
|
||||
if own, err := q.ListOrgMembers(ctx, f.orgA.ID); err != nil || len(own) != 1 {
|
||||
t.Errorf("ListOrgMembers(own org) = %d members, %v; want 1, nil", len(own), err)
|
||||
}
|
||||
if _, err := q.GetOrg(ctx, f.orgB.ID); !errors.Is(err, pgx.ErrNoRows) {
|
||||
t.Errorf("GetOrg(other org) error = %v, want %v", err, pgx.ErrNoRows)
|
||||
}
|
||||
members, err := q.ListOrgMembers(ctx, f.orgB.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(members) != 0 {
|
||||
t.Errorf("ListOrgMembers(other org) = %v, want none", members)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrgScopeCannotWriteIntoOtherTenant(t *testing.T) {
|
||||
db, _ := setup(t)
|
||||
f := seed(t, db)
|
||||
ctx := context.Background()
|
||||
|
||||
err := db.Tx(ctx, tenant.Org(f.orgA.ID, f.alice.ID), func(q *store.Queries) error {
|
||||
return q.AddMembership(ctx, store.AddMembershipParams{OrgID: f.orgB.ID, UserID: f.alice.ID})
|
||||
})
|
||||
if err == nil {
|
||||
t.Error("AddMembership(other org) error = nil, want row-level security violation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserScopeSeesOnlyOwnOrgs(t *testing.T) {
|
||||
db, _ := setup(t)
|
||||
f := seed(t, db)
|
||||
ctx := context.Background()
|
||||
|
||||
err := db.Tx(ctx, tenant.User(f.alice.ID), func(q *store.Queries) error {
|
||||
orgs, err := q.ListUserOrgs(ctx, f.alice.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(orgs) != 1 || orgs[0].ID != f.orgA.ID {
|
||||
t.Errorf("ListUserOrgs(self) = %v, want only org A", orgs)
|
||||
}
|
||||
bobs, err := q.ListUserOrgs(ctx, f.bob.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(bobs) != 0 {
|
||||
t.Errorf("ListUserOrgs(other user) = %v, want none", bobs)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnscopedConnectionSeesNothing(t *testing.T) {
|
||||
db, pool := setup(t)
|
||||
seed(t, db)
|
||||
var n int
|
||||
if err := pool.QueryRow(context.Background(), `SELECT count(*) FROM orgs`).Scan(&n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != 0 {
|
||||
t.Errorf("SELECT count(*) FROM orgs without scope = %d, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyScopeIsRejected(t *testing.T) {
|
||||
db, _ := setup(t)
|
||||
err := db.Tx(context.Background(), tenant.Scope{}, func(*store.Queries) error { return nil })
|
||||
if !errors.Is(err, tenant.ErrNoScope) {
|
||||
t.Errorf("Tx(zero Scope) error = %v, want %v", err, tenant.ErrNoScope)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSingleOwnerPerOrg(t *testing.T) {
|
||||
db, _ := setup(t)
|
||||
f := seed(t, db)
|
||||
ctx := context.Background()
|
||||
err := db.Tx(ctx, tenant.Org(f.orgA.ID, f.alice.ID), func(q *store.Queries) error {
|
||||
return q.AddMembership(ctx, store.AddMembershipParams{OrgID: f.orgA.ID, UserID: f.bob.ID, IsOwner: true})
|
||||
})
|
||||
if err == nil {
|
||||
t.Error("AddMembership(second owner) error = nil, want unique violation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGlobalScopeSeesNoTenantRows(t *testing.T) {
|
||||
db, _ := setup(t)
|
||||
f := seed(t, db)
|
||||
ctx := context.Background()
|
||||
err := db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
if _, err := q.GetOrg(ctx, f.orgA.ID); !errors.Is(err, pgx.ErrNoRows) {
|
||||
t.Errorf("GetOrg() in global scope error = %v, want %v", err, pgx.ErrNoRows)
|
||||
}
|
||||
if _, err := q.GetUser(ctx, f.alice.ID); err != nil {
|
||||
t.Errorf("GetUser() in global scope error = %v, want nil", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewOrgCanBeCreatedInItsOwnScope(t *testing.T) {
|
||||
db, _ := setup(t)
|
||||
ctx := context.Background()
|
||||
id := uuid.New()
|
||||
err := db.Tx(ctx, tenant.Org(id, uuid.Nil), func(q *store.Queries) error {
|
||||
_, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: id, Slug: "n-" + id.String()[:8], Name: "N"})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = db.Tx(ctx, tenant.Org(id, uuid.Nil), func(q *store.Queries) error {
|
||||
_, err := q.DeleteOrg(ctx, id)
|
||||
return err
|
||||
})
|
||||
err = db.Tx(ctx, tenant.Org(uuid.New(), uuid.Nil), func(q *store.Queries) error {
|
||||
_, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: uuid.New(), Slug: "x-" + id.String()[:8], Name: "X"})
|
||||
return err
|
||||
})
|
||||
if err == nil {
|
||||
t.Error("CreateOrg(other id) error = nil, want row-level security violation")
|
||||
}
|
||||
}
|
||||
+110
-5
@@ -1,8 +1,113 @@
|
||||
(() => {
|
||||
const token = document.querySelector('meta[name="csrf-token"]')?.content;
|
||||
window.api = axios.create({
|
||||
baseURL: "/api/v1",
|
||||
headers: token ? { "X-CSRF-Token": token } : {},
|
||||
withCredentials: true,
|
||||
const meta = document.querySelector('meta[name="csrf-token"]');
|
||||
const api = axios.create({ baseURL: "/api/v1", withCredentials: true });
|
||||
api.interceptors.request.use((cfg) => {
|
||||
if (meta?.content) cfg.headers["X-CSRF-Token"] = meta.content;
|
||||
return cfg;
|
||||
});
|
||||
window.api = api;
|
||||
|
||||
const message = (err) =>
|
||||
err.response?.data?.message ?? document.body.dataset.msgNetwork;
|
||||
|
||||
const showError = (form, text) => {
|
||||
const el = form.querySelector("[data-error]");
|
||||
if (!el) return;
|
||||
el.textContent = text;
|
||||
el.classList.toggle("hidden", !text);
|
||||
};
|
||||
|
||||
// Inputs inside a hidden [data-step] are skipped, checkboxes become
|
||||
// booleans and [data-list] inputs become comma-separated arrays.
|
||||
const serialize = (form) => {
|
||||
const out = {};
|
||||
for (const el of form.elements) {
|
||||
if (!el.name || el.disabled || el.closest("[data-step]")?.hidden) continue;
|
||||
if (el.type === "checkbox") out[el.name] = el.checked;
|
||||
else if (el.dataset.list !== undefined)
|
||||
out[el.name] = el.value.split(",").map((v) => v.trim()).filter(Boolean);
|
||||
else out[el.name] = el.value;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
document.addEventListener("submit", async (ev) => {
|
||||
const form = ev.target.closest("form[data-api]");
|
||||
if (!form) return;
|
||||
ev.preventDefault();
|
||||
const button = form.querySelector("button[type=submit]");
|
||||
const body = serialize(form);
|
||||
const totpStep = form.querySelector('[data-step="totp"]');
|
||||
const url = totpStep && !totpStep.hidden ? `${form.dataset.api}/totp` : form.dataset.api;
|
||||
|
||||
showError(form, "");
|
||||
button && (button.disabled = true);
|
||||
try {
|
||||
const res = await api.request({ method: form.dataset.method || "post", url, data: body });
|
||||
if (form.dataset.showCodes !== undefined && res.data?.recovery_codes) {
|
||||
const out = form.querySelector("[data-recovery-output]");
|
||||
const list = out.querySelector("[data-recovery-list]");
|
||||
list.replaceChildren(
|
||||
...res.data.recovery_codes.map((c) => Object.assign(document.createElement("li"), { textContent: c })),
|
||||
);
|
||||
for (const el of form.elements) el.disabled = true;
|
||||
out.hidden = false;
|
||||
return;
|
||||
}
|
||||
if (res.data?.status === "totp_required" && totpStep) {
|
||||
form.querySelector('[data-step="password"]').hidden = true;
|
||||
totpStep.hidden = false;
|
||||
totpStep.querySelector("input")?.focus();
|
||||
return;
|
||||
}
|
||||
location.assign(form.dataset.next || location.href);
|
||||
} catch (err) {
|
||||
showError(form, message(err));
|
||||
} finally {
|
||||
button && (button.disabled = false);
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener("click", async (ev) => {
|
||||
const locale = ev.target.closest("[data-locale]");
|
||||
if (locale) {
|
||||
await api.post("/locale", { locale: locale.dataset.locale }).catch(() => {});
|
||||
location.reload();
|
||||
return;
|
||||
}
|
||||
const del = ev.target.closest("[data-delete]");
|
||||
if (del) {
|
||||
if (del.dataset.confirm && !confirm(del.dataset.confirm)) return;
|
||||
try {
|
||||
await api.delete(del.dataset.delete);
|
||||
location.reload();
|
||||
} catch (err) {
|
||||
alert(message(err));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (ev.target.closest("[data-logout]")) {
|
||||
await api.post("/auth/logout").catch(() => {});
|
||||
location.assign("/login");
|
||||
}
|
||||
if (ev.target.closest("[data-totp-start]")) {
|
||||
const root = ev.target.closest("[data-totp-setup]");
|
||||
try {
|
||||
const { data } = await api.post("/me/totp/setup");
|
||||
root.querySelector("[data-totp-qr]").src = data.qr;
|
||||
root.querySelector("[data-totp-secret]").textContent = data.secret;
|
||||
root.querySelector("[data-totp-panel]").hidden = false;
|
||||
ev.target.hidden = true;
|
||||
} catch (err) {
|
||||
alert(message(err));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener("change", async (ev) => {
|
||||
const sel = ev.target.closest("[data-switch-org]");
|
||||
if (!sel) return;
|
||||
await api.post("/me/org", { org_id: sel.value });
|
||||
location.reload();
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,59 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
)
|
||||
|
||||
templ Login(p Page, signupAllowed bool) {
|
||||
@authShell(p) {
|
||||
<form data-api="/auth/login" data-next="/">
|
||||
@formError()
|
||||
<div data-step="password">
|
||||
@field(i18n.T(ctx, "auth.field.email"), "email", "email", "username", true)
|
||||
@field(i18n.T(ctx, "auth.field.password"), "password", "password", "current-password", true)
|
||||
</div>
|
||||
<div data-step="totp" hidden>
|
||||
<p class="mb-4 text-sm text-muted">{ i18n.T(ctx, "auth.login.totp_hint") }</p>
|
||||
@field(i18n.T(ctx, "auth.field.code"), "code", "text", "one-time-code", false)
|
||||
</div>
|
||||
@submit(i18n.T(ctx, "auth.login.submit"))
|
||||
</form>
|
||||
<form action="/sso" method="get" class="mt-10 border-t border-rule pt-6">
|
||||
<p class="mb-3 text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "auth.sso.heading") }</p>
|
||||
<div class="flex gap-2">
|
||||
<input
|
||||
class="min-w-0 flex-1 border border-rule bg-transparent px-2.5 py-1.5 font-mono text-sm outline-none focus:border-ink"
|
||||
name="org"
|
||||
placeholder={ i18n.T(ctx, "auth.sso.org_placeholder") }
|
||||
aria-label={ i18n.T(ctx, "auth.sso.org_placeholder") }
|
||||
autocomplete="organization"
|
||||
required
|
||||
/>
|
||||
<button type="submit" class="border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "auth.sso.submit") }</button>
|
||||
</div>
|
||||
</form>
|
||||
if signupAllowed {
|
||||
<p class="mt-8 text-sm text-muted">
|
||||
{ i18n.T(ctx, "auth.login.no_account") }
|
||||
<a class="text-ink underline underline-offset-2" href="/signup">{ i18n.T(ctx, "auth.login.to_signup") }</a>
|
||||
</p>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
templ Signup(p Page) {
|
||||
@authShell(p) {
|
||||
<form data-api="/auth/signup" data-next="/">
|
||||
@formError()
|
||||
@field(i18n.T(ctx, "auth.field.name"), "display_name", "text", "name", false)
|
||||
@field(i18n.T(ctx, "auth.field.email"), "email", "email", "username", true)
|
||||
@field(i18n.T(ctx, "auth.field.new_password", "Min", auth.MinPasswordLength), "password", "password", "new-password", true)
|
||||
<hr class="my-6 border-rule"/>
|
||||
@field(i18n.T(ctx, "auth.field.org_name"), "org_name", "text", "organization", true)
|
||||
@field(i18n.T(ctx, "auth.field.org_slug"), "org_slug", "text", "off", true)
|
||||
@submit(i18n.T(ctx, "auth.signup.submit"))
|
||||
</form>
|
||||
<p class="mt-8 text-sm text-muted"><a class="text-ink underline underline-offset-2" href="/login">{ i18n.T(ctx, "auth.signup.to_login") }</a></p>
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.1118
|
||||
|
||||
package web
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
|
||||
import "github.com/a-h/templ"
|
||||
import templruntime "github.com/a-h/templ/runtime"
|
||||
|
||||
import (
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
)
|
||||
|
||||
func Login(p Page, signupAllowed bool) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Var2 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<form data-api=\"/auth/login\" data-next=\"/\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "<div data-step=\"password\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.email"), "email", "email", "username", true).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.password"), "password", "password", "current-password", true).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "</div><div data-step=\"totp\" hidden><p class=\"mb-4 text-sm text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.totp_hint"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 17, Col: 76}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "</p>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.code"), "code", "text", "one-time-code", false).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = submit(i18n.T(ctx, "auth.login.submit")).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "</form><form action=\"/sso\" method=\"get\" class=\"mt-10 border-t border-rule pt-6\"><p class=\"mb-3 text-xs font-medium uppercase tracking-wider text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.sso.heading"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 23, Col: 108}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "</p><div class=\"flex gap-2\"><input class=\"min-w-0 flex-1 border border-rule bg-transparent px-2.5 py-1.5 font-mono text-sm outline-none focus:border-ink\" name=\"org\" placeholder=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "auth.sso.org_placeholder")).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 28, Col: 58}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var5)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "\" aria-label=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "auth.sso.org_placeholder")).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 29, Col: 57}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var6)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "\" autocomplete=\"organization\" required> <button type=\"submit\" class=\"border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.sso.submit"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 33, Col: 134}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "</button></div></form>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if signupAllowed {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "<p class=\"mt-8 text-sm text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.no_account"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 38, Col: 42}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, " <a class=\"text-ink underline underline-offset-2\" href=\"/signup\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.to_signup"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 39, Col: 105}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "</a></p>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func Signup(p Page) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Var11 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "<form data-api=\"/auth/signup\" data-next=\"/\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.name"), "display_name", "text", "name", false).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.email"), "email", "email", "username", true).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.new_password", "Min", auth.MinPasswordLength), "password", "password", "new-password", true).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "<hr class=\"my-6 border-rule\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.org_name"), "org_name", "text", "organization", true).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.org_slug"), "org_slug", "text", "off", true).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = submit(i18n.T(ctx, "auth.signup.submit")).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "</form><p class=\"mt-8 text-sm text-muted\"><a class=\"text-ink underline underline-offset-2\" href=\"/login\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.signup.to_login"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 57, Col: 137}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "</a></p>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var11), templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
var _ = templruntime.GeneratedTemplate
|
||||
@@ -0,0 +1,152 @@
|
||||
package web
|
||||
|
||||
import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
|
||||
// Me is the signed-in user as the console templates see it.
|
||||
type Me struct {
|
||||
// IsOwner refers to the active organization.
|
||||
IsOwner bool
|
||||
ActiveSlug string
|
||||
Email string
|
||||
DisplayName string
|
||||
TOTP bool
|
||||
ActiveOrg string
|
||||
Orgs []Org
|
||||
TOTPMissing bool
|
||||
// RecoveryCodesLeft counts unused TOTP recovery codes.
|
||||
RecoveryCodesLeft int
|
||||
}
|
||||
|
||||
// Org is one entry of the organization switcher.
|
||||
type Org struct {
|
||||
ID string
|
||||
Name string
|
||||
Slug string
|
||||
IsOwner bool
|
||||
}
|
||||
|
||||
templ consoleShell(p Page, me Me) {
|
||||
@Layout(p) {
|
||||
<header class="border-b border-rule">
|
||||
<div class="mx-auto flex max-w-5xl items-center gap-6 px-6 py-3 text-sm">
|
||||
<a href="/" class="font-mono text-xs tracking-wide">uptimesebi</a>
|
||||
if len(me.Orgs) > 1 {
|
||||
<select data-switch-org class="border border-rule bg-transparent px-1.5 py-0.5 text-sm">
|
||||
for _, o := range me.Orgs {
|
||||
<option value={ o.ID } selected?={ o.ID == me.ActiveOrg }>{ o.Name }</option>
|
||||
}
|
||||
</select>
|
||||
} else if len(me.Orgs) == 1 {
|
||||
<span class="text-muted">{ me.Orgs[0].Name }</span>
|
||||
}
|
||||
<nav class="ml-auto flex items-center gap-5">
|
||||
if me.IsOwner {
|
||||
<a href="/settings/sso" class="text-muted hover:text-ink">{ i18n.T(ctx, "console.nav.sso") }</a>
|
||||
}
|
||||
<a href="/settings/security" class="text-muted hover:text-ink">{ i18n.T(ctx, "console.nav.security") }</a>
|
||||
<button data-logout class="text-muted hover:text-ink">{ i18n.T(ctx, "console.nav.logout") }</button>
|
||||
@languageSwitch(p.Languages)
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
if me.TOTPMissing {
|
||||
<div class="border-b border-degraded/40 bg-degraded/10">
|
||||
<p class="mx-auto max-w-5xl px-6 py-2 text-sm">
|
||||
{ i18n.T(ctx, "console.totp_missing") }
|
||||
<a href="/settings/security" class="underline underline-offset-2">{ i18n.T(ctx, "console.totp_missing_action") }</a>
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
<main class="mx-auto max-w-5xl px-6 py-10">
|
||||
@flash(p)
|
||||
{ children... }
|
||||
</main>
|
||||
}
|
||||
}
|
||||
|
||||
templ Dashboard(p Page, me Me) {
|
||||
@consoleShell(p, me) {
|
||||
<h1 class="text-lg font-semibold">{ i18n.T(ctx, "console.monitors.title") }</h1>
|
||||
<p class="mt-2 text-sm text-muted">{ i18n.T(ctx, "console.monitors.empty") }</p>
|
||||
}
|
||||
}
|
||||
|
||||
// Identity is an SSO sign-in linked to the user in the active organization.
|
||||
type Identity struct {
|
||||
Provider string
|
||||
Email string
|
||||
}
|
||||
|
||||
templ Security(p Page, me Me, identities []Identity, canLink bool) {
|
||||
@consoleShell(p, me) {
|
||||
<h1 class="mb-8 text-lg font-semibold">{ i18n.T(ctx, "security.title") }</h1>
|
||||
<section class="max-w-md">
|
||||
<h2 class="mb-1 text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "security.totp.heading") }</h2>
|
||||
if me.TOTP {
|
||||
<p class="mb-1 text-sm"><span class="text-up">●</span> { i18n.T(ctx, "security.totp.active") }</p>
|
||||
<p class={ "mb-6 text-sm", templ.KV("text-down", me.RecoveryCodesLeft < 3), templ.KV("text-muted", me.RecoveryCodesLeft >= 3) }>
|
||||
{ i18n.T(ctx, "security.recovery.left", "Count", me.RecoveryCodesLeft) }
|
||||
</p>
|
||||
<details class="mb-6">
|
||||
<summary class="cursor-pointer text-sm text-muted hover:text-ink">{ i18n.T(ctx, "security.recovery.regenerate") }</summary>
|
||||
<form data-api="/me/totp/recovery-codes" data-show-codes class="mt-4">
|
||||
@formError()
|
||||
@field(i18n.T(ctx, "auth.field.password"), "password", "password", "current-password", true)
|
||||
@field(i18n.T(ctx, "security.totp.current_code"), "code", "text", "one-time-code", true)
|
||||
@submit(i18n.T(ctx, "security.recovery.regenerate"))
|
||||
@recoveryOutput()
|
||||
</form>
|
||||
</details>
|
||||
<details>
|
||||
<summary class="cursor-pointer text-sm text-muted hover:text-ink">{ i18n.T(ctx, "security.totp.disable") }</summary>
|
||||
<form data-api="/me/totp/disable" data-next="/settings/security" class="mt-4">
|
||||
@formError()
|
||||
@field(i18n.T(ctx, "auth.field.password"), "password", "password", "current-password", true)
|
||||
@field(i18n.T(ctx, "security.totp.current_code"), "code", "text", "one-time-code", true)
|
||||
@submit(i18n.T(ctx, "security.totp.disable"))
|
||||
</form>
|
||||
</details>
|
||||
} else {
|
||||
<p class="mb-6 text-sm"><span class="text-unknown">●</span> { i18n.T(ctx, "security.totp.inactive") }</p>
|
||||
<div data-totp-setup>
|
||||
<button data-totp-start class="border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "security.totp.start") }</button>
|
||||
<div data-totp-panel hidden>
|
||||
<img data-totp-qr alt={ i18n.T(ctx, "security.totp.qr_alt") } class="mb-3 h-48 w-48 border border-rule bg-white p-2"/>
|
||||
<p class="mb-6 break-all font-mono text-xs text-muted" data-totp-secret></p>
|
||||
<form data-api="/me/totp/enable" data-show-codes>
|
||||
@formError()
|
||||
@field(i18n.T(ctx, "security.totp.app_code"), "code", "text", "one-time-code", true)
|
||||
@submit(i18n.T(ctx, "security.totp.confirm"))
|
||||
@recoveryOutput()
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
<section class="mt-12 max-w-md">
|
||||
<h2 class="mb-3 text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "security.sso.heading") }</h2>
|
||||
if len(identities) == 0 {
|
||||
<p class="mb-4 text-sm text-muted">{ i18n.T(ctx, "security.sso.none") }</p>
|
||||
} else {
|
||||
<ul class="mb-4 divide-y divide-rule border-y border-rule text-sm">
|
||||
for _, id := range identities {
|
||||
<li class="flex justify-between gap-4 py-2"><span>{ id.Provider }</span><span class="font-mono text-xs text-muted">{ id.Email }</span></li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
if canLink {
|
||||
<a href={ templ.SafeURL("/sso/" + me.ActiveSlug + "?link=1") } class="inline-block border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "security.sso.link") }</a>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
}
|
||||
|
||||
// recoveryOutput is filled by app.js with codes returned by the API; they
|
||||
// are shown once and never rendered by the server.
|
||||
templ recoveryOutput() {
|
||||
<div data-recovery-output hidden class="mt-6 border border-ink p-4">
|
||||
<p class="mb-3 text-sm">{ i18n.T(ctx, "security.recovery.save_now") }</p>
|
||||
<ol data-recovery-list class="mb-4 grid grid-cols-2 gap-x-6 gap-y-1 font-mono text-sm"></ol>
|
||||
<a href="/settings/security" class="text-sm underline underline-offset-2">{ i18n.T(ctx, "security.recovery.saved") }</a>
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,776 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.1118
|
||||
|
||||
package web
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
|
||||
import "github.com/a-h/templ"
|
||||
import templruntime "github.com/a-h/templ/runtime"
|
||||
|
||||
import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
|
||||
// Me is the signed-in user as the console templates see it.
|
||||
type Me struct {
|
||||
// IsOwner refers to the active organization.
|
||||
IsOwner bool
|
||||
ActiveSlug string
|
||||
Email string
|
||||
DisplayName string
|
||||
TOTP bool
|
||||
ActiveOrg string
|
||||
Orgs []Org
|
||||
TOTPMissing bool
|
||||
// RecoveryCodesLeft counts unused TOTP recovery codes.
|
||||
RecoveryCodesLeft int
|
||||
}
|
||||
|
||||
// Org is one entry of the organization switcher.
|
||||
type Org struct {
|
||||
ID string
|
||||
Name string
|
||||
Slug string
|
||||
IsOwner bool
|
||||
}
|
||||
|
||||
func consoleShell(p Page, me Me) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
templ_7745c5c3_Var1 := templ.GetChildren(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Var2 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<header class=\"border-b border-rule\"><div class=\"mx-auto flex max-w-5xl items-center gap-6 px-6 py-3 text-sm\"><a href=\"/\" class=\"font-mono text-xs tracking-wide\">uptimesebi</a> ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if len(me.Orgs) > 1 {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "<select data-switch-org class=\"border border-rule bg-transparent px-1.5 py-0.5 text-sm\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
for _, o := range me.Orgs {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "<option value=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templruntime.NewAttributeExpression(o.ID).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 36, Col: 27}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var3)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if o.ID == me.ActiveOrg {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, " selected")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, ">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(o.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 36, Col: 73}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "</option>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "</select>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else if len(me.Orgs) == 1 {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "<span class=\"text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(me.Orgs[0].Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 40, Col: 47}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "</span>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "<nav class=\"ml-auto flex items-center gap-5\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if me.IsOwner {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "<a href=\"/settings/sso\" class=\"text-muted hover:text-ink\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.sso"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 44, Col: 96}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "</a> ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "<a href=\"/settings/security\" class=\"text-muted hover:text-ink\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.security"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 46, Col: 105}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</a> <button data-logout class=\"text-muted hover:text-ink\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.logout"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 47, Col: 94}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "</button>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = languageSwitch(p.Languages).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "</nav></div></header>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if me.TOTPMissing {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "<div class=\"border-b border-degraded/40 bg-degraded/10\"><p class=\"mx-auto max-w-5xl px-6 py-2 text-sm\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.totp_missing"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 55, Col: 42}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, " <a href=\"/settings/security\" class=\"underline underline-offset-2\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.totp_missing_action"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 56, Col: 115}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "</a></p></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, " <main class=\"mx-auto max-w-5xl px-6 py-10\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = flash(p).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templ_7745c5c3_Var1.Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "</main>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
templ_7745c5c3_Err = Layout(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func Dashboard(p Page, me Me) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Var12 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "<h1 class=\"text-lg font-semibold\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.title"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 69, Col: 75}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "</h1><p class=\"mt-2 text-sm text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.empty"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 70, Col: 76}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "</p>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var12), templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// Identity is an SSO sign-in linked to the user in the active organization.
|
||||
type Identity struct {
|
||||
Provider string
|
||||
Email string
|
||||
}
|
||||
|
||||
func Security(p Page, me Me, identities []Identity, canLink bool) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Var16 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "<h1 class=\"mb-8 text-lg font-semibold\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var17 string
|
||||
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.title"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 82, Col: 72}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "</h1><section class=\"max-w-md\"><h2 class=\"mb-1 text-xs font-medium uppercase tracking-wider text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var18 string
|
||||
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.heading"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 84, Col: 114}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "</h2>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if me.TOTP {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "<p class=\"mb-1 text-sm\"><span class=\"text-up\">●</span> ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var19 string
|
||||
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.active"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 86, Col: 98}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "</p>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
{
|
||||
templ_7745c5c3_ElementWriter := templ_7745c5c3_Buffer
|
||||
templ_7745c5c3_Buffer := templ.GetBuffer()
|
||||
var templ_7745c5c3_ElementScripts []templ.ComponentScript
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "<p class=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var20 = []any{"mb-6 text-sm", templ.KV("text-down", me.RecoveryCodesLeft < 3), templ.KV("text-muted", me.RecoveryCodesLeft >= 3)}
|
||||
templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_ElementWriter, templ_7745c5c3_Var20...)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var21 string
|
||||
templ_7745c5c3_Var21, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.CSSClasses(templ_7745c5c3_Var20).String()).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 1, Col: 0}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var21)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templ.RenderScriptItems(ctx, templ_7745c5c3_ElementWriter, templ_7745c5c3_ElementScripts...)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteTo(templ_7745c5c3_ElementWriter)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, ">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var22 string
|
||||
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.left", "Count", me.RecoveryCodesLeft))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 88, Col: 75}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "</p><details class=\"mb-6\"><summary class=\"cursor-pointer text-sm text-muted hover:text-ink\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var23 string
|
||||
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.regenerate"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 91, Col: 116}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "</summary><form data-api=\"/me/totp/recovery-codes\" data-show-codes class=\"mt-4\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.password"), "password", "password", "current-password", true).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = field(i18n.T(ctx, "security.totp.current_code"), "code", "text", "one-time-code", true).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = submit(i18n.T(ctx, "security.recovery.regenerate")).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = recoveryOutput().Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "</form></details> <details><summary class=\"cursor-pointer text-sm text-muted hover:text-ink\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var24 string
|
||||
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.disable"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 101, Col: 109}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "</summary><form data-api=\"/me/totp/disable\" data-next=\"/settings/security\" class=\"mt-4\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.password"), "password", "password", "current-password", true).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = field(i18n.T(ctx, "security.totp.current_code"), "code", "text", "one-time-code", true).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = submit(i18n.T(ctx, "security.totp.disable")).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "</form></details>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "<p class=\"mb-6 text-sm\"><span class=\"text-unknown\">●</span> ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var25 string
|
||||
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.inactive"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 110, Col: 105}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "</p><div data-totp-setup><button data-totp-start class=\"border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var26 string
|
||||
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.start"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 112, Col: 141}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "</button><div data-totp-panel hidden><img data-totp-qr alt=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var27 string
|
||||
templ_7745c5c3_Var27, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "security.totp.qr_alt")).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 114, Col: 65}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var27)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "\" class=\"mb-3 h-48 w-48 border border-rule bg-white p-2\"><p class=\"mb-6 break-all font-mono text-xs text-muted\" data-totp-secret></p><form data-api=\"/me/totp/enable\" data-show-codes>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = field(i18n.T(ctx, "security.totp.app_code"), "code", "text", "one-time-code", true).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = submit(i18n.T(ctx, "security.totp.confirm")).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = recoveryOutput().Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "</form></div></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "</section><section class=\"mt-12 max-w-md\"><h2 class=\"mb-3 text-xs font-medium uppercase tracking-wider text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var28 string
|
||||
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.heading"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 127, Col: 113}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "</h2>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if len(identities) == 0 {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "<p class=\"mb-4 text-sm text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var29 string
|
||||
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.none"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 129, Col: 73}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "</p>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "<ul class=\"mb-4 divide-y divide-rule border-y border-rule text-sm\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
for _, id := range identities {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "<li class=\"flex justify-between gap-4 py-2\"><span>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var30 string
|
||||
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(id.Provider)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 133, Col: 69}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "</span><span class=\"font-mono text-xs text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var31 string
|
||||
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(id.Email)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 133, Col: 131}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "</span></li>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "</ul>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
if canLink {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "<a href=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var32 string
|
||||
templ_7745c5c3_Var32, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL("/sso/" + me.ActiveSlug + "?link=1")).ResolveURL(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 138, Col: 64}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var32)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "\" class=\"inline-block border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var33 string
|
||||
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.link"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 138, Col: 190}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "</a>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "</section>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var16), templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// recoveryOutput is filled by app.js with codes returned by the API; they
|
||||
// are shown once and never rendered by the server.
|
||||
func recoveryOutput() templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "<div data-recovery-output hidden class=\"mt-6 border border-ink p-4\"><p class=\"mb-3 text-sm\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var35 string
|
||||
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.save_now"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 148, Col: 69}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "</p><ol data-recovery-list class=\"mb-4 grid grid-cols-2 gap-x-6 gap-y-1 font-mono text-sm\"></ol><a href=\"/settings/security\" class=\"text-sm underline underline-offset-2\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var36 string
|
||||
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.recovery.saved"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 150, Col: 116}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, "</a></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
var _ = templruntime.GeneratedTemplate
|
||||
@@ -1,9 +0,0 @@
|
||||
package web
|
||||
|
||||
templ Index() {
|
||||
@Layout("uptimesebi") {
|
||||
<main class="mx-auto max-w-3xl px-6 py-16">
|
||||
<p class="font-mono text-sm text-muted">uptimesebi</p>
|
||||
</main>
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.1118
|
||||
|
||||
package web
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
|
||||
import "github.com/a-h/templ"
|
||||
import templruntime "github.com/a-h/templ/runtime"
|
||||
|
||||
func Index() templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Var2 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<main class=\"mx-auto max-w-3xl px-6 py-16\"><p class=\"font-mono text-sm text-muted\">uptimesebi</p></main>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
templ_7745c5c3_Err = Layout("uptimesebi").Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
var _ = templruntime.GeneratedTemplate
|
||||
@@ -1,18 +1,92 @@
|
||||
package web
|
||||
|
||||
templ Layout(title string) {
|
||||
import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
|
||||
// Page carries what every rendered page needs besides its own content.
|
||||
type Page struct {
|
||||
TitleID string
|
||||
CSRF string
|
||||
Languages []string
|
||||
// ErrorID and NoticeID name catalog messages shown above the content,
|
||||
// typically after a redirect back from an SSO flow.
|
||||
ErrorID string
|
||||
NoticeID string
|
||||
}
|
||||
|
||||
templ Layout(p Page) {
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<html lang={ i18n.Lang(ctx) }>
|
||||
<head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<title>{ title }</title>
|
||||
if p.CSRF != "" {
|
||||
<meta name="csrf-token" content={ p.CSRF }/>
|
||||
}
|
||||
<title>{ i18n.T(ctx, p.TitleID) } · uptimesebi</title>
|
||||
<link rel="stylesheet" href="/static/dist/app.css"/>
|
||||
<script src="/static/dist/axios.min.js" defer></script>
|
||||
<script src="/static/dist/app.js" defer></script>
|
||||
</head>
|
||||
<body class="min-h-screen">
|
||||
<body class="min-h-screen" data-msg-network={ i18n.T(ctx, "app.network_error") }>
|
||||
{ children... }
|
||||
</body>
|
||||
</html>
|
||||
}
|
||||
|
||||
templ languageSwitch(langs []string) {
|
||||
<span class="flex gap-2 font-mono text-xs">
|
||||
for _, l := range langs {
|
||||
if l == i18n.Lang(ctx) {
|
||||
<span class="text-ink" aria-current="true">{ l }</span>
|
||||
} else {
|
||||
<button type="button" data-locale={ l } class="text-muted hover:text-ink" title={ i18n.T(ctx, "lang."+l) }>{ l }</button>
|
||||
}
|
||||
}
|
||||
</span>
|
||||
}
|
||||
|
||||
templ authShell(p Page) {
|
||||
@Layout(p) {
|
||||
<main class="mx-auto mt-[12vh] w-full max-w-sm px-6">
|
||||
<div class="mb-10 flex items-baseline justify-between">
|
||||
<p class="font-mono text-xs tracking-wide text-muted">uptimesebi</p>
|
||||
@languageSwitch(p.Languages)
|
||||
</div>
|
||||
<h1 class="mb-6 text-xl font-semibold">{ i18n.T(ctx, p.TitleID) }</h1>
|
||||
@flash(p)
|
||||
{ children... }
|
||||
</main>
|
||||
}
|
||||
}
|
||||
|
||||
templ field(label, name, typ, autocomplete string, required bool) {
|
||||
<label class="mb-4 block">
|
||||
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ label }</span>
|
||||
<input
|
||||
class="w-full border border-rule bg-transparent px-2.5 py-1.5 outline-none focus:border-ink"
|
||||
type={ typ }
|
||||
name={ name }
|
||||
autocomplete={ autocomplete }
|
||||
required?={ required }
|
||||
/>
|
||||
</label>
|
||||
}
|
||||
|
||||
templ submit(label string) {
|
||||
<button type="submit" class="mt-2 w-full bg-ink px-3 py-2 text-sm font-medium text-paper hover:opacity-90 disabled:opacity-50">
|
||||
{ label }
|
||||
</button>
|
||||
}
|
||||
|
||||
templ flash(p Page) {
|
||||
if p.ErrorID != "" {
|
||||
<p class="mb-6 border-l-2 border-down pl-2 text-sm text-down">{ i18n.T(ctx, p.ErrorID) }</p>
|
||||
}
|
||||
if p.NoticeID != "" {
|
||||
<p class="mb-6 border-l-2 border-up pl-2 text-sm">{ i18n.T(ctx, p.NoticeID) }</p>
|
||||
}
|
||||
}
|
||||
|
||||
templ formError() {
|
||||
<p data-error class="mb-4 hidden border-l-2 border-down pl-2 text-sm text-down"></p>
|
||||
}
|
||||
@@ -9,7 +9,20 @@ package web
|
||||
import "github.com/a-h/templ"
|
||||
import templruntime "github.com/a-h/templ/runtime"
|
||||
|
||||
func Layout(title string) templ.Component {
|
||||
import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
|
||||
// Page carries what every rendered page needs besides its own content.
|
||||
type Page struct {
|
||||
TitleID string
|
||||
CSRF string
|
||||
Languages []string
|
||||
// ErrorID and NoticeID name catalog messages shown above the content,
|
||||
// typically after a redirect back from an SSO flow.
|
||||
ErrorID string
|
||||
NoticeID string
|
||||
}
|
||||
|
||||
func Layout(p Page) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
@@ -27,20 +40,69 @@ func Layout(title string) templ.Component {
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
templ_7745c5c3_Var1 := templ.GetChildren(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<!doctype html><html lang=\"de\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<!doctype html><html lang=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(title)
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.Lang(ctx)).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 9, Col: 17}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 18, Col: 28}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var2)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "</title><link rel=\"stylesheet\" href=\"/static/dist/app.css\"><script src=\"/static/dist/axios.min.js\" defer></script><script src=\"/static/dist/app.js\" defer></script></head><body class=\"min-h-screen\">")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if p.CSRF != "" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "<meta name=\"csrf-token\" content=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templruntime.NewAttributeExpression(p.CSRF).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 23, Col: 44}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var3)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "<title>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, p.TitleID))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 25, Col: 34}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, " · uptimesebi</title><link rel=\"stylesheet\" href=\"/static/dist/app.css\"><script src=\"/static/dist/axios.min.js\" defer></script><script src=\"/static/dist/app.js\" defer></script></head><body class=\"min-h-screen\" data-msg-network=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "app.network_error")).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 30, Col: 80}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var5)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
@@ -48,7 +110,387 @@ func Layout(title string) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "</body></html>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "</body></html>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func languageSwitch(langs []string) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "<span class=\"flex gap-2 font-mono text-xs\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
for _, l := range langs {
|
||||
if l == i18n.Lang(ctx) {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "<span class=\"text-ink\" aria-current=\"true\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(l)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 40, Col: 50}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "</span>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "<button type=\"button\" data-locale=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templruntime.NewAttributeExpression(l).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 42, Col: 41}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var8)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "\" class=\"text-muted hover:text-ink\" title=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "lang."+l)).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 42, Col: 108}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var9)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(l)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 42, Col: 114}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</button>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "</span>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func authShell(p Page) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
templ_7745c5c3_Var11 := templ.GetChildren(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Var12 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "<main class=\"mx-auto mt-[12vh] w-full max-w-sm px-6\"><div class=\"mb-10 flex items-baseline justify-between\"><p class=\"font-mono text-xs tracking-wide text-muted\">uptimesebi</p>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = languageSwitch(p.Languages).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "</div><h1 class=\"mb-6 text-xl font-semibold\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, p.TitleID))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 55, Col: 66}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "</h1>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = flash(p).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templ_7745c5c3_Var11.Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "</main>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
templ_7745c5c3_Err = Layout(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var12), templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func field(label, name, typ, autocomplete string, required bool) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "<label class=\"mb-4 block\"><span class=\"mb-1 block text-xs font-medium uppercase tracking-wider text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var15 string
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(label)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 64, Col: 90}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "</span> <input class=\"w-full border border-rule bg-transparent px-2.5 py-1.5 outline-none focus:border-ink\" type=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var16 string
|
||||
templ_7745c5c3_Var16, templ_7745c5c3_Err = templruntime.NewAttributeExpression(typ).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 67, Col: 13}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var16)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "\" name=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var17 string
|
||||
templ_7745c5c3_Var17, templ_7745c5c3_Err = templruntime.NewAttributeExpression(name).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 68, Col: 14}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var17)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "\" autocomplete=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var18 string
|
||||
templ_7745c5c3_Var18, templ_7745c5c3_Err = templruntime.NewAttributeExpression(autocomplete).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 69, Col: 30}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var18)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if required {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, " required")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "></label>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func submit(label string) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "<button type=\"submit\" class=\"mt-2 w-full bg-ink px-3 py-2 text-sm font-medium text-paper hover:opacity-90 disabled:opacity-50\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var20 string
|
||||
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(label)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 77, Col: 9}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "</button>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func flash(p Page) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
if p.ErrorID != "" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "<p class=\"mb-6 border-l-2 border-down pl-2 text-sm text-down\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var22 string
|
||||
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, p.ErrorID))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 83, Col: 88}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "</p>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
if p.NoticeID != "" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "<p class=\"mb-6 border-l-2 border-up pl-2 text-sm\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var23 string
|
||||
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, p.NoticeID))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 86, Col: 77}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "</p>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func formError() templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "<p data-error class=\"mb-4 hidden border-l-2 border-down pl-2 text-sm text-down\"></p>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package web
|
||||
|
||||
import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
|
||||
// SSOOption is one provider on the chooser page.
|
||||
type SSOOption struct {
|
||||
Name string
|
||||
URL string
|
||||
}
|
||||
|
||||
templ SSOChooser(p Page, opts []SSOOption) {
|
||||
@authShell(p) {
|
||||
<ul class="divide-y divide-rule border-y border-rule">
|
||||
for _, o := range opts {
|
||||
<li><a href={ templ.SafeURL(o.URL) } class="block py-2.5 hover:underline">{ o.Name }</a></li>
|
||||
}
|
||||
</ul>
|
||||
<p class="mt-8 text-sm text-muted"><a class="text-ink underline underline-offset-2" href="/login">{ i18n.T(ctx, "auth.signup.to_login") }</a></p>
|
||||
}
|
||||
}
|
||||
|
||||
// SSOProvider is a provider row on the settings page.
|
||||
type SSOProvider struct {
|
||||
ID string
|
||||
Name string
|
||||
Issuer string
|
||||
ClientID string
|
||||
HasSecret bool
|
||||
AllowedDomains string
|
||||
AutoProvision bool
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
// SSOSettings is the data of the organization SSO page.
|
||||
type SSOSettings struct {
|
||||
Providers []SSOProvider
|
||||
RedirectURL string
|
||||
LoginURL string
|
||||
}
|
||||
|
||||
templ SSOSettingsPage(p Page, me Me, s SSOSettings) {
|
||||
@consoleShell(p, me) {
|
||||
<h1 class="mb-2 text-lg font-semibold">{ i18n.T(ctx, "sso.settings.title") }</h1>
|
||||
<p class="mb-8 max-w-2xl text-sm text-muted">{ i18n.T(ctx, "sso.settings.intro") }</p>
|
||||
<dl class="mb-10 grid max-w-2xl grid-cols-[max-content_1fr] gap-x-6 gap-y-2 text-sm">
|
||||
<dt class="text-muted">{ i18n.T(ctx, "sso.settings.redirect_url") }</dt>
|
||||
<dd class="break-all font-mono text-xs leading-5">{ s.RedirectURL }</dd>
|
||||
<dt class="text-muted">{ i18n.T(ctx, "sso.settings.login_url") }</dt>
|
||||
<dd class="break-all font-mono text-xs leading-5">{ s.LoginURL }</dd>
|
||||
</dl>
|
||||
if len(s.Providers) > 0 {
|
||||
<table class="mb-12 w-full max-w-4xl text-left text-sm">
|
||||
<thead class="border-b border-rule text-xs uppercase tracking-wider text-muted">
|
||||
<tr>
|
||||
<th class="py-2 pr-4 font-medium">{ i18n.T(ctx, "sso.field.name") }</th>
|
||||
<th class="py-2 pr-4 font-medium">{ i18n.T(ctx, "sso.field.issuer") }</th>
|
||||
<th class="py-2 pr-4 font-medium">{ i18n.T(ctx, "sso.field.auto_provision") }</th>
|
||||
<th class="py-2 pr-4 font-medium">{ i18n.T(ctx, "sso.field.enabled") }</th>
|
||||
<th class="py-2"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-rule">
|
||||
for _, pr := range s.Providers {
|
||||
<tr class="align-top">
|
||||
<td class="py-2.5 pr-4">{ pr.Name }</td>
|
||||
<td class="py-2.5 pr-4 break-all font-mono text-xs">{ pr.Issuer }</td>
|
||||
<td class="py-2.5 pr-4">@yesNo(pr.AutoProvision)</td>
|
||||
<td class="py-2.5 pr-4">@yesNo(pr.Enabled)</td>
|
||||
<td class="py-2.5 text-right">
|
||||
<details class="inline-block text-left">
|
||||
<summary class="cursor-pointer text-muted hover:text-ink">{ i18n.T(ctx, "sso.action.edit") }</summary>
|
||||
<div class="mt-4 w-80">
|
||||
@ssoForm(pr, "put", "/org/sso/"+pr.ID)
|
||||
<button
|
||||
type="button"
|
||||
data-delete={ "/org/sso/" + pr.ID }
|
||||
data-confirm={ i18n.T(ctx, "sso.action.delete_confirm") }
|
||||
class="mt-4 text-sm text-down hover:underline"
|
||||
>{ i18n.T(ctx, "sso.action.delete") }</button>
|
||||
</div>
|
||||
</details>
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
}
|
||||
<section class="max-w-md">
|
||||
<h2 class="mb-4 text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "sso.settings.add") }</h2>
|
||||
@ssoForm(SSOProvider{Enabled: true}, "post", "/org/sso")
|
||||
</section>
|
||||
}
|
||||
}
|
||||
|
||||
templ yesNo(v bool) {
|
||||
if v {
|
||||
<span class="text-up">●</span> { i18n.T(ctx, "common.yes") }
|
||||
} else {
|
||||
<span class="text-unknown">●</span> { i18n.T(ctx, "common.no") }
|
||||
}
|
||||
}
|
||||
|
||||
templ ssoForm(pr SSOProvider, method, action string) {
|
||||
<form data-api={ action } data-method={ method } data-next="/settings/sso">
|
||||
@formError()
|
||||
@valueField(i18n.T(ctx, "sso.field.name"), "name", pr.Name, "", true)
|
||||
@valueField(i18n.T(ctx, "sso.field.issuer"), "issuer", pr.Issuer, "https://login.example.com/realms/acme", true)
|
||||
@valueField(i18n.T(ctx, "sso.field.client_id"), "client_id", pr.ClientID, "", true)
|
||||
<label class="mb-4 block">
|
||||
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "sso.field.client_secret") }</span>
|
||||
<input
|
||||
class="w-full border border-rule bg-transparent px-2.5 py-1.5 outline-none focus:border-ink"
|
||||
type="password"
|
||||
name="client_secret"
|
||||
autocomplete="off"
|
||||
if pr.HasSecret {
|
||||
placeholder={ i18n.T(ctx, "sso.field.client_secret_keep") }
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label class="mb-4 block">
|
||||
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "sso.field.allowed_domains") }</span>
|
||||
<input
|
||||
class="w-full border border-rule bg-transparent px-2.5 py-1.5 font-mono text-sm outline-none focus:border-ink"
|
||||
name="allowed_domains"
|
||||
data-list
|
||||
value={ pr.AllowedDomains }
|
||||
placeholder="example.com, example.org"
|
||||
/>
|
||||
<span class="mt-1 block text-xs text-muted">{ i18n.T(ctx, "sso.field.allowed_domains_hint") }</span>
|
||||
</label>
|
||||
@checkbox(i18n.T(ctx, "sso.field.auto_provision"), "auto_provision", pr.AutoProvision)
|
||||
@checkbox(i18n.T(ctx, "sso.field.enabled"), "enabled", pr.Enabled)
|
||||
@submit(i18n.T(ctx, "common.save"))
|
||||
</form>
|
||||
}
|
||||
|
||||
templ valueField(label, name, value, placeholder string, required bool) {
|
||||
<label class="mb-4 block">
|
||||
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ label }</span>
|
||||
<input
|
||||
class="w-full border border-rule bg-transparent px-2.5 py-1.5 outline-none focus:border-ink"
|
||||
name={ name }
|
||||
value={ value }
|
||||
placeholder={ placeholder }
|
||||
required?={ required }
|
||||
/>
|
||||
</label>
|
||||
}
|
||||
|
||||
templ checkbox(label, name string, checked bool) {
|
||||
<label class="mb-3 flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" name={ name } checked?={ checked } class="accent-ink"/>
|
||||
{ label }
|
||||
</label>
|
||||
}
|
||||
@@ -0,0 +1,807 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.1118
|
||||
|
||||
package web
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
|
||||
import "github.com/a-h/templ"
|
||||
import templruntime "github.com/a-h/templ/runtime"
|
||||
|
||||
import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
|
||||
// SSOOption is one provider on the chooser page.
|
||||
type SSOOption struct {
|
||||
Name string
|
||||
URL string
|
||||
}
|
||||
|
||||
func SSOChooser(p Page, opts []SSOOption) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Var2 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<ul class=\"divide-y divide-rule border-y border-rule\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
for _, o := range opts {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "<li><a href=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL(o.URL)).ResolveURL(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 15, Col: 38}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var3)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "\" class=\"block py-2.5 hover:underline\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(o.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 15, Col: 86}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "</a></li>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</ul><p class=\"mt-8 text-sm text-muted\"><a class=\"text-ink underline underline-offset-2\" href=\"/login\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.signup.to_login"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 18, Col: 137}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "</a></p>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// SSOProvider is a provider row on the settings page.
|
||||
type SSOProvider struct {
|
||||
ID string
|
||||
Name string
|
||||
Issuer string
|
||||
ClientID string
|
||||
HasSecret bool
|
||||
AllowedDomains string
|
||||
AutoProvision bool
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
// SSOSettings is the data of the organization SSO page.
|
||||
type SSOSettings struct {
|
||||
Providers []SSOProvider
|
||||
RedirectURL string
|
||||
LoginURL string
|
||||
}
|
||||
|
||||
func SSOSettingsPage(p Page, me Me, s SSOSettings) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Var7 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "<h1 class=\"mb-2 text-lg font-semibold\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.settings.title"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 43, Col: 76}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "</h1><p class=\"mb-8 max-w-2xl text-sm text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.settings.intro"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 44, Col: 82}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "</p><dl class=\"mb-10 grid max-w-2xl grid-cols-[max-content_1fr] gap-x-6 gap-y-2 text-sm\"><dt class=\"text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.settings.redirect_url"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 46, Col: 68}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "</dt><dd class=\"break-all font-mono text-xs leading-5\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(s.RedirectURL)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 47, Col: 68}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "</dd><dt class=\"text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.settings.login_url"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 48, Col: 65}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "</dt><dd class=\"break-all font-mono text-xs leading-5\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(s.LoginURL)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 49, Col: 65}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "</dd></dl>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if len(s.Providers) > 0 {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "<table class=\"mb-12 w-full max-w-4xl text-left text-sm\"><thead class=\"border-b border-rule text-xs uppercase tracking-wider text-muted\"><tr><th class=\"py-2 pr-4 font-medium\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.field.name"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 55, Col: 71}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</th><th class=\"py-2 pr-4 font-medium\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var15 string
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.field.issuer"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 56, Col: 73}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "</th><th class=\"py-2 pr-4 font-medium\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var16 string
|
||||
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.field.auto_provision"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 57, Col: 81}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "</th><th class=\"py-2 pr-4 font-medium\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var17 string
|
||||
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.field.enabled"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 58, Col: 74}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "</th><th class=\"py-2\"></th></tr></thead> <tbody class=\"divide-y divide-rule\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
for _, pr := range s.Providers {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "<tr class=\"align-top\"><td class=\"py-2.5 pr-4\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var18 string
|
||||
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(pr.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 65, Col: 40}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "</td><td class=\"py-2.5 pr-4 break-all font-mono text-xs\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var19 string
|
||||
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(pr.Issuer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 66, Col: 70}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "</td><td class=\"py-2.5 pr-4\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = yesNo(pr.AutoProvision).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "</td><td class=\"py-2.5 pr-4\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = yesNo(pr.Enabled).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "</td><td class=\"py-2.5 text-right\"><details class=\"inline-block text-left\"><summary class=\"cursor-pointer text-muted hover:text-ink\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var20 string
|
||||
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.action.edit"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 71, Col: 99}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "</summary><div class=\"mt-4 w-80\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = ssoForm(pr, "put", "/org/sso/"+pr.ID).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "<button type=\"button\" data-delete=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var21 string
|
||||
templ_7745c5c3_Var21, templ_7745c5c3_Err = templruntime.NewAttributeExpression("/org/sso/" + pr.ID).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 76, Col: 44}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var21)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "\" data-confirm=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var22 string
|
||||
templ_7745c5c3_Var22, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "sso.action.delete_confirm")).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 77, Col: 66}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var22)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "\" class=\"mt-4 text-sm text-down hover:underline\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var23 string
|
||||
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.action.delete"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 79, Col: 45}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "</button></div></details></td></tr>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "</tbody></table>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, " <section class=\"max-w-md\"><h2 class=\"mb-4 text-xs font-medium uppercase tracking-wider text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var24 string
|
||||
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.settings.add"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 89, Col: 109}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "</h2>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = ssoForm(SSOProvider{Enabled: true}, "post", "/org/sso").Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "</section>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var7), templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func yesNo(v bool) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
if v {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "<span class=\"text-up\">●</span> ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var26 string
|
||||
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "common.yes"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 97, Col: 62}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "<span class=\"text-unknown\">●</span> ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var27 string
|
||||
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "common.no"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 99, Col: 66}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func ssoForm(pr SSOProvider, method, action string) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "<form data-api=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var29 string
|
||||
templ_7745c5c3_Var29, templ_7745c5c3_Err = templruntime.NewAttributeExpression(action).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 104, Col: 24}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var29)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "\" data-method=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var30 string
|
||||
templ_7745c5c3_Var30, templ_7745c5c3_Err = templruntime.NewAttributeExpression(method).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 104, Col: 47}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var30)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "\" data-next=\"/settings/sso\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = valueField(i18n.T(ctx, "sso.field.name"), "name", pr.Name, "", true).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = valueField(i18n.T(ctx, "sso.field.issuer"), "issuer", pr.Issuer, "https://login.example.com/realms/acme", true).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = valueField(i18n.T(ctx, "sso.field.client_id"), "client_id", pr.ClientID, "", true).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "<label class=\"mb-4 block\"><span class=\"mb-1 block text-xs font-medium uppercase tracking-wider text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var31 string
|
||||
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.field.client_secret"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 110, Col: 124}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "</span> <input class=\"w-full border border-rule bg-transparent px-2.5 py-1.5 outline-none focus:border-ink\" type=\"password\" name=\"client_secret\" autocomplete=\"off\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if pr.HasSecret {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, " placeholder=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var32 string
|
||||
templ_7745c5c3_Var32, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "sso.field.client_secret_keep")).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 117, Col: 62}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var32)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "></label> <label class=\"mb-4 block\"><span class=\"mb-1 block text-xs font-medium uppercase tracking-wider text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var33 string
|
||||
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.field.allowed_domains"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 122, Col: 126}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "</span> <input class=\"w-full border border-rule bg-transparent px-2.5 py-1.5 font-mono text-sm outline-none focus:border-ink\" name=\"allowed_domains\" data-list value=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var34 string
|
||||
templ_7745c5c3_Var34, templ_7745c5c3_Err = templruntime.NewAttributeExpression(pr.AllowedDomains).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 127, Col: 29}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var34)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "\" placeholder=\"example.com, example.org\"> <span class=\"mt-1 block text-xs text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var35 string
|
||||
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "sso.field.allowed_domains_hint"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 130, Col: 94}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "</span></label>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = checkbox(i18n.T(ctx, "sso.field.auto_provision"), "auto_provision", pr.AutoProvision).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = checkbox(i18n.T(ctx, "sso.field.enabled"), "enabled", pr.Enabled).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = submit(i18n.T(ctx, "common.save")).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "</form>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func valueField(label, name, value, placeholder string, required bool) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "<label class=\"mb-4 block\"><span class=\"mb-1 block text-xs font-medium uppercase tracking-wider text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var37 string
|
||||
templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(label)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 140, Col: 90}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "</span> <input class=\"w-full border border-rule bg-transparent px-2.5 py-1.5 outline-none focus:border-ink\" name=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var38 string
|
||||
templ_7745c5c3_Var38, templ_7745c5c3_Err = templruntime.NewAttributeExpression(name).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 143, Col: 14}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var38)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "\" value=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var39 string
|
||||
templ_7745c5c3_Var39, templ_7745c5c3_Err = templruntime.NewAttributeExpression(value).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 144, Col: 16}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var39)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "\" placeholder=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var40 string
|
||||
templ_7745c5c3_Var40, templ_7745c5c3_Err = templruntime.NewAttributeExpression(placeholder).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 145, Col: 28}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var40)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if required {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, " required")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, "></label>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func checkbox(label, name string, checked bool) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "<label class=\"mb-3 flex items-center gap-2 text-sm\"><input type=\"checkbox\" name=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var42 string
|
||||
templ_7745c5c3_Var42, templ_7745c5c3_Err = templruntime.NewAttributeExpression(name).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 153, Col: 36}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var42)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if checked {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, " checked")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, " class=\"accent-ink\"> ")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var43 string
|
||||
templ_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinStringErrs(label)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/sso.templ`, Line: 154, Col: 9}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "</label>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
var _ = templruntime.GeneratedTemplate
|
||||
@@ -1,3 +1,5 @@
|
||||
// Package web contains the templ components and static assets shared by
|
||||
// the console and status pages.
|
||||
package web
|
||||
|
||||
import (
|
||||
@@ -12,6 +14,7 @@ import (
|
||||
//go:embed all:static
|
||||
var static embed.FS
|
||||
|
||||
// Static serves the embedded build output of npm run build.
|
||||
func Static() http.FileSystem {
|
||||
sub, err := fs.Sub(static, "static")
|
||||
if err != nil {
|
||||
@@ -20,6 +23,8 @@ func Static() http.FileSystem {
|
||||
return http.FS(sub)
|
||||
}
|
||||
|
||||
// Render writes comp as HTML. Rendering errors are attached to c so the
|
||||
// access log records them; the status has already been sent.
|
||||
func Render(c *gin.Context, status int, comp templ.Component) {
|
||||
c.Status(status)
|
||||
c.Header("Content-Type", "text/html; charset=utf-8")
|
||||
|
||||
@@ -16,5 +16,21 @@ sql:
|
||||
go_type: github.com/google/uuid.UUID
|
||||
- db_type: citext
|
||||
go_type: string
|
||||
- db_type: citext
|
||||
nullable: true
|
||||
go_type:
|
||||
type: string
|
||||
pointer: true
|
||||
- db_type: timestamptz
|
||||
go_type: time.Time
|
||||
- db_type: timestamptz
|
||||
nullable: true
|
||||
go_type:
|
||||
type: time.Time
|
||||
pointer: true
|
||||
- db_type: uuid
|
||||
nullable: true
|
||||
go_type:
|
||||
import: github.com/google/uuid
|
||||
type: UUID
|
||||
pointer: true
|
||||
Reference in new issue
Block a user