From d167b9216aae7dc82cb139f51ac21660e698a57b Mon Sep 17 00:00:00 2001 From: codegirl-007 Date: Fri, 21 Aug 2026 23:30:15 -0700 Subject: [PATCH 01/17] Initial commit: runnable Ask a Plumber First server. --- .air.toml | 33 ++ .env.example | 18 + .gitignore | 8 + cmd/server/main.go | 74 +++ embed.go | 12 + go.mod | 42 ++ go.sum | 110 +++++ internal/blob/spaces.go | 88 ++++ internal/geo/us.go | 56 +++ internal/pacific/pacific.go | 53 +++ internal/store/db.go | 33 ++ internal/store/migrate.go | 28 ++ internal/store/postgres.go | 130 ++++++ internal/store/postgres_test.go | 41 ++ internal/store/sessions.go | 154 +++++++ internal/store/store.go | 406 ++++++++++++++++ internal/web/admin.go | 70 +++ internal/web/auth.go | 112 +++++ internal/web/memstore_test.go | 330 +++++++++++++ internal/web/profile.go | 142 ++++++ internal/web/server.go | 518 +++++++++++++++++++++ internal/web/server_test.go | 468 +++++++++++++++++++ schema.sql | 40 ++ static/app.css | 789 ++++++++++++++++++++++++++++++++ static/htmx.min.js | 1 + templates/admin_users.html | 45 ++ templates/base.html | 73 +++ templates/hunt.html | 21 + templates/login.html | 19 + templates/partials/_answer.html | 12 + templates/partials/_list.html | 37 ++ templates/partials/_signin.html | 8 + templates/partials/_vote.html | 37 ++ templates/profile.html | 57 +++ templates/question.html | 37 ++ templates/register.html | 20 + templates/submit.html | 19 + todo.md | 33 ++ 38 files changed, 4174 insertions(+) create mode 100644 .air.toml create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 cmd/server/main.go create mode 100644 embed.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/blob/spaces.go create mode 100644 internal/geo/us.go create mode 100644 internal/pacific/pacific.go create mode 100644 internal/store/db.go create mode 100644 internal/store/migrate.go create mode 100644 internal/store/postgres.go create mode 100644 internal/store/postgres_test.go create mode 100644 internal/store/sessions.go create mode 100644 internal/store/store.go create mode 100644 internal/web/admin.go create mode 100644 internal/web/auth.go create mode 100644 internal/web/memstore_test.go create mode 100644 internal/web/profile.go create mode 100644 internal/web/server.go create mode 100644 internal/web/server_test.go create mode 100644 schema.sql create mode 100644 static/app.css create mode 100644 static/htmx.min.js create mode 100644 templates/admin_users.html create mode 100644 templates/base.html create mode 100644 templates/hunt.html create mode 100644 templates/login.html create mode 100644 templates/partials/_answer.html create mode 100644 templates/partials/_list.html create mode 100644 templates/partials/_signin.html create mode 100644 templates/partials/_vote.html create mode 100644 templates/profile.html create mode 100644 templates/question.html create mode 100644 templates/register.html create mode 100644 templates/submit.html create mode 100644 todo.md diff --git a/.air.toml b/.air.toml new file mode 100644 index 0000000..2214178 --- /dev/null +++ b/.air.toml @@ -0,0 +1,33 @@ +# Hot reload for local development: air +# https://github.com/air-verse/air + +root = "." +tmp_dir = "tmp" + +[build] + cmd = "go build -o ./tmp/server ./cmd/server" + bin = "./tmp/server" + full_bin = "./tmp/server" + include_ext = ["go", "html", "css", "js", "sql"] + exclude_dir = ["tmp", "vendor", "testdata", "bin"] + exclude_file = [] + exclude_regex = ["_test\\.go"] + exclude_unchanged = true + follow_symlink = false + delay = 500 + stop_on_error = true + send_interrupt = true + kill_delay = "1s" + +[log] + time = false + main_only = false + +[color] + main = "magenta" + watcher = "cyan" + build = "yellow" + runner = "green" + +[misc] + clean_on_exit = true diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..e6941bb --- /dev/null +++ b/.env.example @@ -0,0 +1,18 @@ +# Local listen address (ignored when PORT is set, e.g. on App Platform) +LISTEN=:8080 +DATA_PATH=data.db +# Optional: first matching registrant becomes admin only if no admin exists yet. +# Later promote/demote via /admin/users (admins only). +ADMIN_USERNAME=yourusername +# Set to 1 when serving over HTTPS +SECURE_COOKIE=0 +# Prod (PlanetScale Postgres): paste the dashboard URI. When set, SQLite is ignored. +# Use port 5432 so the app can create tables on boot. Switch to 6432 (PgBouncer) later if you need pooling. +# DATABASE_URL=postgresql://user:password@host.example.com:5432/postgres?sslmode=verify-full +# DigitalOcean Spaces (profile avatars). Leave unset to disable uploads. +# SPACES_KEY= +# SPACES_SECRET= +# SPACES_REGION=nyc3 +# SPACES_BUCKET=your-bucket +# SPACES_ENDPOINT=https://nyc3.digitaloceanspaces.com +# SPACES_CDN_BASE=https://your-bucket.nyc3.cdn.digitaloceanspaces.com diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3f6b01e --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +/data.db +/data.db-* +/.test.db +/.test.db-* +/bin/ +/tmp/ +.env +*.exe diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 0000000..169fa9a --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,74 @@ +package main + +import ( + "log" + "net/http" + "os" + "strings" + + "github.com/joho/godotenv" + + "plumber" + "plumber/internal/blob" + "plumber/internal/store" + "plumber/internal/web" +) + +func main() { + _ = godotenv.Load() + listen := listenAddr() + st, err := store.Connect(os.Getenv("DATABASE_URL"), env("DATA_PATH", "data.db"), plumber.SchemaSQL) + if err != nil { + log.Fatalf("database: %v", err) + } + defer st.Close() + if os.Getenv("DATABASE_URL") != "" { + log.Printf("database: postgres") + } else { + log.Printf("database: sqlite") + } + uploader := blob.NewSpaces(blob.SpacesConfig{ + Key: os.Getenv("SPACES_KEY"), + Secret: os.Getenv("SPACES_SECRET"), + Region: os.Getenv("SPACES_REGION"), + Bucket: os.Getenv("SPACES_BUCKET"), + Endpoint: os.Getenv("SPACES_ENDPOINT"), + CDNBase: os.Getenv("SPACES_CDN_BASE"), + }) + if uploader.Enabled() { + log.Printf("avatars: digitalocean spaces") + } else { + log.Printf("avatars: uploads disabled (set SPACES_* to enable)") + } + srv, err := web.New(st, st.SessionStore(), plumber.TemplateFS, plumber.StaticFS, web.Config{ + AdminUsername: os.Getenv("ADMIN_USERNAME"), + SecureCookie: os.Getenv("SECURE_COOKIE") == "1", + Blob: uploader, + }) + if err != nil { + log.Fatalf("server: %v", err) + } + log.Printf("listening on %s", listen) + if err := http.ListenAndServe(listen, srv.Handler()); err != nil { + log.Fatal(err) + } +} + +// listenAddr prefers PORT (App Platform / PaaS), then LISTEN, then :8080. +func listenAddr() string { + if p := strings.TrimSpace(os.Getenv("PORT")); p != "" { + if strings.HasPrefix(p, ":") { + return p + } + return ":" + p + } + return env("LISTEN", ":8080") +} + +func env(key, fallback string) string { + v := strings.TrimSpace(os.Getenv(key)) + if v == "" { + return fallback + } + return v +} diff --git a/embed.go b/embed.go new file mode 100644 index 0000000..d74be85 --- /dev/null +++ b/embed.go @@ -0,0 +1,12 @@ +package plumber + +import "embed" + +//go:embed templates/*.html templates/partials/*.html +var TemplateFS embed.FS + +//go:embed static +var StaticFS embed.FS + +//go:embed schema.sql +var SchemaSQL string diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..a4ba585 --- /dev/null +++ b/go.mod @@ -0,0 +1,42 @@ +module plumber + +go 1.25.0 + +require ( + github.com/alexedwards/scs/postgresstore v0.0.0-20251002162104-209de6e426de + github.com/alexedwards/scs/v2 v2.9.0 + github.com/aws/aws-sdk-go-v2 v1.43.7 + github.com/aws/aws-sdk-go-v2/credentials v1.19.37 + github.com/aws/aws-sdk-go-v2/service/s3 v1.107.3 + github.com/go-chi/chi/v5 v5.3.1 + github.com/google/uuid v1.6.0 + github.com/jackc/pgx/v5 v5.10.0 + github.com/joho/godotenv v1.5.1 + golang.org/x/crypto v0.55.0 + modernc.org/sqlite v1.57.0 +) + +require ( + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.18 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.38 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.38 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.39 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.17 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.31 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.38 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.39 // indirect + github.com/aws/smithy-go v1.27.8 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/mattn/go-isatty v0.0.24 // indirect + github.com/ncruces/go-strftime v1.0.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + golang.org/x/sync v0.22.0 // indirect + golang.org/x/sys v0.47.0 // indirect + golang.org/x/text v0.41.0 // indirect + modernc.org/libc v1.74.4 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.11.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..66a4c4b --- /dev/null +++ b/go.sum @@ -0,0 +1,110 @@ +github.com/alexedwards/scs/postgresstore v0.0.0-20251002162104-209de6e426de h1:LDrMkjj4OCCQsq9SvIPQV1l3leMxqXZTCTxDFwMrqTE= +github.com/alexedwards/scs/postgresstore v0.0.0-20251002162104-209de6e426de/go.mod h1:TDDdV/xnjj+/4zBQ9a2k+i2AbuAdY7SQjPUh5zoTZ3M= +github.com/alexedwards/scs/v2 v2.9.0 h1:xa05mVpwTBm1iLeTMNFfAWpKUm4fXAW7CeAViqBVS90= +github.com/alexedwards/scs/v2 v2.9.0/go.mod h1:ToaROZxyKukJKT/xLcVQAChi5k6+Pn1Gvmdl7h3RRj8= +github.com/aws/aws-sdk-go-v2 v1.43.7 h1:msCzvkeYJA9ehbV8mRRmkZLo/zJg/+yDVLNtflg83hQ= +github.com/aws/aws-sdk-go-v2 v1.43.7/go.mod h1:tXpPM+v0D1lndmga+HqqLDIzUFJlEeR21aspVklHF00= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.18 h1:LAfOuhAH331fmOjTQpAaOlH+Ftn7RzSDJ2VFwjdMMy4= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.18/go.mod h1:4e5xhuXHx1e4U9EthvbPP1r/DIMp5c2823OL8karzcM= +github.com/aws/aws-sdk-go-v2/credentials v1.19.37 h1:FJ8Iz4/xISMB/rwLlgfWujfGDFWr0oneQgtA6KPcYLY= +github.com/aws/aws-sdk-go-v2/credentials v1.19.37/go.mod h1:Q6pWOgVUp49x4g5QVi29wHofUoICnZ+Zq4jHbRN/7ec= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.38 h1:MBMg0zJ6i4TkAJ0dVFLKKn2cOkY6FkicmUDM67BRr6g= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.38/go.mod h1:9MWuJbyiUyj6eA7W1/zm1zuePDPSB3g+xcgRQeMWsXc= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.38 h1:lHm4jPf3k1Lz5ZWc+Vcn3MKVwym+26kWCba9FkJ4f0Y= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.38/go.mod h1:Rn+P2XR+FbyZzjmWKjg/KUZNxmGfr5oZwh5jQiE+CzI= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.39 h1:vo4xvMRs/F6h1E52qsgLqCQgWIQXgIJUauG6rlZEh4U= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.39/go.mod h1:jB03R1ij/A+OE2e1dz6vgj076gd7vlYcfstAzj3HcnU= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.17 h1:OvYZOB3qA6zvfdRFiRFRzVSiElMYrz3GdntkXZxlp1o= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.17/go.mod h1:JgR/2Ew50ACfIWau1oeMRX59tMtC0kM+PYQGEaT04cY= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.31 h1:uZOinZb+h7lZw8IYzP1z1IuEnueB76/EFkcf/fEW4Ag= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.31/go.mod h1:NRtwAM/p5VRt03TlEUs0pH3TeWamWdf4YyJpSrzPYLc= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.38 h1:H/5TI1jqaHsNoDQ60UwvPvJBg4GURkinXI3Qga29t2w= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.38/go.mod h1:PTVFf+XH++7NJOky+RLBYQx0QA5NcaeEYFQ2fsi0nwo= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.39 h1:HLPAVrlLDaN2boN0xJx7MgaQDNEO3Q+c9L6kl/8m47Q= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.39/go.mod h1:Pg/dVfsNkm1hsIDK/gMvCKtmyNfNTV12mrgHqVE/6Oo= +github.com/aws/aws-sdk-go-v2/service/s3 v1.107.3 h1:IKoCZqfWfZzSBi16QFQ+QcbQ3LRQ7QgB1S5tDAyPBQQ= +github.com/aws/aws-sdk-go-v2/service/s3 v1.107.3/go.mod h1:RBpRcXiM4s2pOInVs32GsBonnje+fiAj4mcrStRmlCA= +github.com/aws/smithy-go v1.27.8 h1:FR0dxZfIlV7Z8eh2iHfIofdunw382XsDV3Mxt9nUvRY= +github.com/aws/smithy-go v1.27.8/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= +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= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8= +github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= +github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo= +github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0= +github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/lib/pq v1.4.0 h1:TmtCFbH+Aw0AixwyttznSMQDgbR5Yed/Gg6S8Funrhc= +github.com/lib/pq v1.4.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= +github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= +golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= +golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= +golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= +golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= +golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE= +golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/cc/v4 v4.29.1 h1:MKgdCV3WykTSPqpVrnxdEDS0HEd2FHpKZDzxzU5LyeI= +modernc.org/cc/v4 v4.29.1/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= +modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU= +modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk= +modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= +modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI= +modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= +modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= +modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= +modernc.org/libc v1.74.4 h1:fX1Omw4o2/1C2iRkkIsrQTasJQldLhRmuPreXLoWs9k= +modernc.org/libc v1.74.4/go.mod h1:eeQAS9W3sZeKYMFubydxJpII9ybHWshk+7or7bLG9co= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= +modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= +modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.57.0 h1:qNQP6xnx5M0ISNtlnxoOX0+cD5bJ0/gr9aMmndFczzg= +modernc.org/sqlite v1.57.0/go.mod h1:yCJ2cmAaIkHQ25oXWrF8H4O1lIfPYPR26yCEDj2P3pQ= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/internal/blob/spaces.go b/internal/blob/spaces.go new file mode 100644 index 0000000..69df506 --- /dev/null +++ b/internal/blob/spaces.go @@ -0,0 +1,88 @@ +package blob + +import ( + "context" + "fmt" + "io" + "strings" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/aws/aws-sdk-go-v2/service/s3/types" +) + +// Uploader stores public avatar objects. +type Uploader interface { + Enabled() bool + Upload(ctx context.Context, key string, body io.Reader, contentType string, size int64) (publicURL string, err error) +} + +// Disabled is a no-op uploader used when Spaces is not configured. +type Disabled struct{} + +func (Disabled) Enabled() bool { return false } + +func (Disabled) Upload(context.Context, string, io.Reader, string, int64) (string, error) { + return "", fmt.Errorf("avatar uploads are not configured") +} + +// SpacesConfig holds DigitalOcean Spaces settings. +type SpacesConfig struct { + Key string + Secret string + Region string + Bucket string + Endpoint string // e.g. https://nyc3.digitaloceanspaces.com + CDNBase string // optional public base URL without trailing slash +} + +// NewSpaces returns an Uploader when required env is present; otherwise Disabled. +func NewSpaces(cfg SpacesConfig) Uploader { + cfg.Key = strings.TrimSpace(cfg.Key) + cfg.Secret = strings.TrimSpace(cfg.Secret) + cfg.Region = strings.TrimSpace(cfg.Region) + cfg.Bucket = strings.TrimSpace(cfg.Bucket) + cfg.Endpoint = strings.TrimSpace(cfg.Endpoint) + cfg.CDNBase = strings.TrimRight(strings.TrimSpace(cfg.CDNBase), "/") + if cfg.Key == "" || cfg.Secret == "" || cfg.Region == "" || cfg.Bucket == "" || cfg.Endpoint == "" { + return Disabled{} + } + client := s3.New(s3.Options{ + Region: cfg.Region, + Credentials: credentials.NewStaticCredentialsProvider(cfg.Key, cfg.Secret, ""), + BaseEndpoint: aws.String(cfg.Endpoint), + }) + return &spaces{client: client, cfg: cfg} +} + +type spaces struct { + client *s3.Client + cfg SpacesConfig +} + +func (s *spaces) Enabled() bool { return true } + +func (s *spaces) Upload(ctx context.Context, key string, body io.Reader, contentType string, size int64) (string, error) { + key = strings.TrimPrefix(key, "/") + input := &s3.PutObjectInput{ + Bucket: aws.String(s.cfg.Bucket), + Key: aws.String(key), + Body: body, + ContentType: aws.String(contentType), + ACL: types.ObjectCannedACLPublicRead, + } + if size > 0 { + input.ContentLength = aws.Int64(size) + } + if _, err := s.client.PutObject(ctx, input); err != nil { + return "", err + } + if s.cfg.CDNBase != "" { + return s.cfg.CDNBase + "/" + key, nil + } + // Virtual-hosted–style Spaces URL. + host := strings.TrimPrefix(s.cfg.Endpoint, "https://") + host = strings.TrimPrefix(host, "http://") + return fmt.Sprintf("https://%s.%s/%s", s.cfg.Bucket, host, key), nil +} diff --git a/internal/geo/us.go b/internal/geo/us.go new file mode 100644 index 0000000..ff77702 --- /dev/null +++ b/internal/geo/us.go @@ -0,0 +1,56 @@ +package geo + +import "strings" + +// States is the US states + DC allowlist (code -> name). +var States = []struct { + Code string + Name string +}{ + {"AL", "Alabama"}, {"AK", "Alaska"}, {"AZ", "Arizona"}, {"AR", "Arkansas"}, {"CA", "California"}, + {"CO", "Colorado"}, {"CT", "Connecticut"}, {"DE", "Delaware"}, {"DC", "District of Columbia"}, + {"FL", "Florida"}, {"GA", "Georgia"}, {"HI", "Hawaii"}, {"ID", "Idaho"}, {"IL", "Illinois"}, + {"IN", "Indiana"}, {"IA", "Iowa"}, {"KS", "Kansas"}, {"KY", "Kentucky"}, {"LA", "Louisiana"}, + {"ME", "Maine"}, {"MD", "Maryland"}, {"MA", "Massachusetts"}, {"MI", "Michigan"}, {"MN", "Minnesota"}, + {"MS", "Mississippi"}, {"MO", "Missouri"}, {"MT", "Montana"}, {"NE", "Nebraska"}, {"NV", "Nevada"}, + {"NH", "New Hampshire"}, {"NJ", "New Jersey"}, {"NM", "New Mexico"}, {"NY", "New York"}, + {"NC", "North Carolina"}, {"ND", "North Dakota"}, {"OH", "Ohio"}, {"OK", "Oklahoma"}, {"OR", "Oregon"}, + {"PA", "Pennsylvania"}, {"RI", "Rhode Island"}, {"SC", "South Carolina"}, {"SD", "South Dakota"}, + {"TN", "Tennessee"}, {"TX", "Texas"}, {"UT", "Utah"}, {"VT", "Vermont"}, {"VA", "Virginia"}, + {"WA", "Washington"}, {"WV", "West Virginia"}, {"WI", "Wisconsin"}, {"WY", "Wyoming"}, +} + +var codes map[string]struct{} + +func init() { + codes = make(map[string]struct{}, len(States)) + for _, s := range States { + codes[s.Code] = struct{}{} + } +} + +// ValidState reports whether state is empty or a known US code. +func ValidState(state string) bool { + state = strings.ToUpper(strings.TrimSpace(state)) + if state == "" { + return true + } + _, ok := codes[state] + return ok +} + +// NormalizeState returns "" or an uppercase 2-letter code. +func NormalizeState(state string) string { + return strings.ToUpper(strings.TrimSpace(state)) +} + +// StateName returns the full name for a US state code, or "" if unknown. +func StateName(code string) string { + code = NormalizeState(code) + for _, s := range States { + if s.Code == code { + return s.Name + } + } + return "" +} diff --git a/internal/pacific/pacific.go b/internal/pacific/pacific.go new file mode 100644 index 0000000..ab7eae1 --- /dev/null +++ b/internal/pacific/pacific.go @@ -0,0 +1,53 @@ +package pacific + +import ( + "time" + + _ "time/tzdata" +) + +const Layout = "2006-01-02" + +var Loc *time.Location + +func init() { + loc, err := time.LoadLocation("America/Los_Angeles") + if err != nil { + panic(err) + } + Loc = loc +} + +func HuntDate(t time.Time) string { + return t.In(Loc).Format(Layout) +} + +func Today() string { + return HuntDate(time.Now()) +} + +func Yesterday() string { + now := time.Now().In(Loc) + y := time.Date(now.Year(), now.Month(), now.Day()-1, 0, 0, 0, 0, Loc) + return y.Format(Layout) +} + +func Parse(date string) (time.Time, error) { + return time.ParseInLocation(Layout, date, Loc) +} + +func Label(date string) string { + t, err := Parse(date) + if err != nil { + return date + } + return t.Format("January 2, 2006") +} + +func IsToday(date string) bool { + return date == Today() +} + +func IsYesterday(date string) bool { + return date == Yesterday() +} diff --git a/internal/store/db.go b/internal/store/db.go new file mode 100644 index 0000000..00febb9 --- /dev/null +++ b/internal/store/db.go @@ -0,0 +1,33 @@ +package store + +import ( + "context" + "errors" +) + +// ErrLastAdmin is returned when demoting the only remaining admin. +var ErrLastAdmin = errors.New("cannot demote the last admin") + +// DB is the persistence API used by the web layer. +// Named DB to avoid colliding with scs.Store. +type DB interface { + CreateUser(ctx context.Context, username, passwordHash string, asAdmin bool) (*User, error) + UserByID(ctx context.Context, id string) (*User, error) + UserByUsername(ctx context.Context, username string) (*User, error) + CountAdmins(ctx context.Context) (int, error) + ListUsers(ctx context.Context) ([]User, error) + SetRole(ctx context.Context, userID, role string) error + CreateQuestion(ctx context.Context, authorID, title, body, city string) (*RankedQuestion, error) + ListHunt(ctx context.Context, huntDate, viewerID string) ([]RankedQuestion, error) + GetQuestion(ctx context.Context, id, viewerID string) (*RankedQuestion, error) + Vote(ctx context.Context, userID, questionID string, value int) error + GetAnswer(ctx context.Context, questionID string) (*Answer, error) + UpsertAnswer(ctx context.Context, questionID, authorID, body string) error + HideQuestion(ctx context.Context, id string) error + UpdateProfile(ctx context.Context, userID, state, avatarURL string) error + ListQuestionsByAuthor(ctx context.Context, authorID string) ([]RankedQuestion, error) + ListQuestionsAnsweredBy(ctx context.Context, adminID string) ([]RankedQuestion, error) +} + +// Compile-time check: *Store implements DB. +var _ DB = (*Store)(nil) diff --git a/internal/store/migrate.go b/internal/store/migrate.go new file mode 100644 index 0000000..0c247cb --- /dev/null +++ b/internal/store/migrate.go @@ -0,0 +1,28 @@ +package store + +import ( + "database/sql" + "fmt" + "strings" +) + +func migrateUserProfileColumns(db *sql.DB, dialect string) error { + cols := []string{"avatar_url", "state"} + for _, col := range cols { + var stmt string + switch dialect { + case dialectPostgres: + stmt = fmt.Sprintf(`ALTER TABLE users ADD COLUMN IF NOT EXISTS %s TEXT NOT NULL DEFAULT ''`, col) + default: + stmt = fmt.Sprintf(`ALTER TABLE users ADD COLUMN %s TEXT NOT NULL DEFAULT ''`, col) + } + if _, err := db.Exec(stmt); err != nil { + // SQLite errors when the column already exists. + if dialect == dialectSQLite && strings.Contains(strings.ToLower(err.Error()), "duplicate column") { + continue + } + return fmt.Errorf("add column %s: %w", col, err) + } + } + return nil +} diff --git a/internal/store/postgres.go b/internal/store/postgres.go new file mode 100644 index 0000000..878e2d0 --- /dev/null +++ b/internal/store/postgres.go @@ -0,0 +1,130 @@ +package store + +import ( + "database/sql" + "fmt" + "net/url" + "strconv" + "strings" + "time" + + _ "github.com/jackc/pgx/v5/stdlib" +) + +const ( + dialectSQLite = "sqlite" + dialectPostgres = "postgres" +) + +func rebind(query string) string { + n := 0 + var b strings.Builder + for i := 0; i < len(query); i++ { + if query[i] == '?' { + n++ + b.WriteByte('$') + b.WriteString(strconv.Itoa(n)) + continue + } + b.WriteByte(query[i]) + } + return b.String() +} + +func (s *Store) q(query string) string { + if s.dialect == dialectPostgres { + return rebind(query) + } + return query +} + +func applySchema(db *sql.DB, schema string) error { + for _, stmt := range strings.Split(schema, ";") { + stmt = strings.TrimSpace(stmt) + if stmt == "" { + continue + } + upper := strings.ToUpper(stmt) + if strings.HasPrefix(upper, "PRAGMA") { + continue + } + if _, err := db.Exec(stmt); err != nil { + return fmt.Errorf("%w: %s", err, stmt) + } + } + return nil +} + +func postgresDSN(raw string) (string, error) { + u, err := url.Parse(raw) + if err != nil { + return "", fmt.Errorf("DATABASE_URL: %w", err) + } + switch u.Scheme { + case "postgres", "postgresql": + default: + return "", fmt.Errorf("DATABASE_URL must be a postgres URL") + } + q := u.Query() + if strings.EqualFold(q.Get("sslrootcert"), "system") { + q.Del("sslrootcert") + } + q.Del("sslnegotiation") + if q.Get("sslmode") == "" { + q.Set("sslmode", "verify-full") + } + u.RawQuery = q.Encode() + return u.String(), nil +} + +func OpenPostgres(databaseURL, schema string) (*Store, error) { + return openPostgres(databaseURL, schema, 5*time.Minute) +} + +// OpenPostgresWithoutSessionCleanup opens Postgres without a session cleanup goroutine (for tests). +func OpenPostgresWithoutSessionCleanup(databaseURL, schema string) (*Store, error) { + return openPostgres(databaseURL, schema, 0) +} + +func openPostgres(databaseURL, schema string, sessionCleanup time.Duration) (*Store, error) { + dsn, err := postgresDSN(databaseURL) + if err != nil { + return nil, err + } + db, err := sql.Open("pgx", dsn) + if err != nil { + return nil, err + } + db.SetMaxOpenConns(20) + db.SetMaxIdleConns(5) + if err := db.Ping(); err != nil { + _ = db.Close() + return nil, fmt.Errorf("postgres ping: %w", err) + } + if err := applySchema(db, schema); err != nil { + _ = db.Close() + return nil, fmt.Errorf("apply schema: %w", err) + } + if err := applySessionsSchema(db, dialectPostgres); err != nil { + _ = db.Close() + return nil, fmt.Errorf("apply sessions schema: %w", err) + } + if err := migrateUserProfileColumns(db, dialectPostgres); err != nil { + _ = db.Close() + return nil, fmt.Errorf("migrate profile columns: %w", err) + } + st := &Store{db: db, dialect: dialectPostgres} + st.initSessionStore(sessionCleanup) + return st, nil +} + +// Connect uses PlanetScale Postgres when DATABASE_URL is set, otherwise SQLite. +func Connect(databaseURL, sqlitePath, schema string) (*Store, error) { + if strings.TrimSpace(databaseURL) != "" { + return OpenPostgres(databaseURL, schema) + } + if sqlitePath == "" { + sqlitePath = "data.db" + } + return Open(sqlitePath, schema) +} diff --git a/internal/store/postgres_test.go b/internal/store/postgres_test.go new file mode 100644 index 0000000..f297d14 --- /dev/null +++ b/internal/store/postgres_test.go @@ -0,0 +1,41 @@ +package store + +import "testing" + +func TestRebindPostgresPlaceholders(t *testing.T) { + got := rebind(`SELECT a FROM t WHERE x = ? AND y = ?`) + want := `SELECT a FROM t WHERE x = $1 AND y = $2` + if got != want { + t.Fatalf("got %q", got) + } +} + +func TestNormalizeUsername(t *testing.T) { + if got := NormalizeUsername(" Alice_1 "); got != "alice_1" { + t.Fatalf("got %q", got) + } +} + +func TestPostgresDSNDefaultsSSLMode(t *testing.T) { + in := "postgresql://user:pass@db.example.com:5432/postgres" + out, err := postgresDSN(in) + if err != nil { + t.Fatal(err) + } + if !containsAny(out, "sslmode=verify-full") { + t.Fatalf("missing default sslmode: %s", out) + } +} + +func containsAny(s string, parts ...string) bool { + for _, p := range parts { + if len(p) > 0 && (len(s) >= len(p)) { + for i := 0; i+len(p) <= len(s); i++ { + if s[i:i+len(p)] == p { + return true + } + } + } + } + return false +} diff --git a/internal/store/sessions.go b/internal/store/sessions.go new file mode 100644 index 0000000..1e4041f --- /dev/null +++ b/internal/store/sessions.go @@ -0,0 +1,154 @@ +package store + +import ( + "database/sql" + "log" + "time" + + "github.com/alexedwards/scs/postgresstore" + "github.com/alexedwards/scs/v2" +) + +const sessionsSchemaSQLite = ` +CREATE TABLE IF NOT EXISTS sessions ( + token TEXT PRIMARY KEY, + data BLOB NOT NULL, + expiry REAL NOT NULL +); +CREATE INDEX IF NOT EXISTS sessions_expiry_idx ON sessions(expiry); +` + +const sessionsSchemaPostgres = ` +CREATE TABLE IF NOT EXISTS sessions ( + token TEXT PRIMARY KEY, + data BYTEA NOT NULL, + expiry TIMESTAMPTZ NOT NULL +); +CREATE INDEX IF NOT EXISTS sessions_expiry_idx ON sessions (expiry); +` + +func applySessionsSchema(db *sql.DB, dialect string) error { + schema := sessionsSchemaSQLite + if dialect == dialectPostgres { + schema = sessionsSchemaPostgres + } + return applySchema(db, schema) +} + +type sessionStopper interface { + StopCleanup() +} + +// SessionStore returns the scs store backed by this database. +func (s *Store) SessionStore() scs.Store { + return s.sessionStore +} + +func (s *Store) initSessionStore(cleanupInterval time.Duration) { + switch s.dialect { + case dialectPostgres: + ps := postgresstore.NewWithCleanupInterval(s.db, cleanupInterval) + s.sessionStore = ps + s.sessionStopper = ps + default: + ss := newSQLiteSessionStore(s.db, cleanupInterval) + s.sessionStore = ss + s.sessionStopper = ss + } +} + +// sqliteSessionStore is a modernc-safe scs.Store (uses ? placeholders). +type sqliteSessionStore struct { + db *sql.DB + stopCleanup chan bool +} + +func newSQLiteSessionStore(db *sql.DB, cleanupInterval time.Duration) *sqliteSessionStore { + s := &sqliteSessionStore{db: db} + if cleanupInterval > 0 { + s.stopCleanup = make(chan bool) + go s.startCleanup(cleanupInterval) + } + return s +} + +func (s *sqliteSessionStore) Find(token string) ([]byte, bool, error) { + var b []byte + err := s.db.QueryRow( + `SELECT data FROM sessions WHERE token = ? AND julianday('now') < expiry`, + token, + ).Scan(&b) + if err == sql.ErrNoRows { + return nil, false, nil + } + if err != nil { + return nil, false, err + } + return b, true, nil +} + +func (s *sqliteSessionStore) Commit(token string, b []byte, expiry time.Time) error { + _, err := s.db.Exec( + `REPLACE INTO sessions (token, data, expiry) VALUES (?, ?, julianday(?))`, + token, + b, + expiry.UTC().Format("2006-01-02T15:04:05.999"), + ) + return err +} + +func (s *sqliteSessionStore) Delete(token string) error { + _, err := s.db.Exec(`DELETE FROM sessions WHERE token = ?`, token) + return err +} + +func (s *sqliteSessionStore) All() (map[string][]byte, error) { + rows, err := s.db.Query(`SELECT token, data FROM sessions WHERE julianday('now') < expiry`) + if err != nil { + return nil, err + } + defer rows.Close() + out := make(map[string][]byte) + for rows.Next() { + var token string + var data []byte + if err := rows.Scan(&token, &data); err != nil { + return nil, err + } + out[token] = data + } + return out, rows.Err() +} + +func (s *sqliteSessionStore) startCleanup(interval time.Duration) { + ticker := time.NewTicker(interval) + for { + select { + case <-ticker.C: + if err := s.deleteExpired(); err != nil { + log.Println(err) + } + case <-s.stopCleanup: + ticker.Stop() + return + } + } +} + +func (s *sqliteSessionStore) StopCleanup() { + if s.stopCleanup != nil { + s.stopCleanup <- true + } +} + +func (s *sqliteSessionStore) deleteExpired() error { + _, err := s.db.Exec(`DELETE FROM sessions WHERE expiry < julianday('now')`) + return err +} + +// Ensure interface compliance. +var ( + _ scs.Store = (*sqliteSessionStore)(nil) + _ scs.IterableStore = (*sqliteSessionStore)(nil) + _ sessionStopper = (*sqliteSessionStore)(nil) +) diff --git a/internal/store/store.go b/internal/store/store.go new file mode 100644 index 0000000..778dfc8 --- /dev/null +++ b/internal/store/store.go @@ -0,0 +1,406 @@ +package store + +import ( + "context" + "database/sql" + "fmt" + "strings" + "time" + + "github.com/alexedwards/scs/v2" + "github.com/google/uuid" + _ "modernc.org/sqlite" + + "plumber/internal/pacific" +) + +type Store struct { + db *sql.DB + dialect string + sessionStore scs.Store + sessionStopper sessionStopper +} + +type User struct { + ID string + Username string + Name string + Role string + AvatarURL string + State string + CreatedAt string + PasswordHash string +} + +func (u *User) Admin() bool { + return u != nil && u.Role == "admin" +} + +type RankedQuestion struct { + ID string + AuthorID string + AuthorName string + Title string + Body string + City string + HuntDate string + Hidden bool + CreatedAt string + Score int + Answered bool + UserVote int +} + +type Answer struct { + QuestionID string + AuthorID string + AuthorName string + Body string + CreatedAt string + UpdatedAt string +} + +func Open(path, schema string) (*Store, error) { + return openSQLite(path, schema, 5*time.Minute) +} + +// OpenWithoutSessionCleanup opens SQLite without a session cleanup goroutine (for tests). +func OpenWithoutSessionCleanup(path, schema string) (*Store, error) { + return openSQLite(path, schema, 0) +} + +func openSQLite(path, schema string, sessionCleanup time.Duration) (*Store, error) { + dsn := path + if !strings.Contains(dsn, "?") { + dsn += "?_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)" + } + db, err := sql.Open("sqlite", dsn) + if err != nil { + return nil, err + } + db.SetMaxOpenConns(1) + if _, err := db.Exec(schema); err != nil { + _ = db.Close() + return nil, fmt.Errorf("apply schema: %w", err) + } + if err := applySessionsSchema(db, dialectSQLite); err != nil { + _ = db.Close() + return nil, fmt.Errorf("apply sessions schema: %w", err) + } + if err := migrateUserProfileColumns(db, dialectSQLite); err != nil { + _ = db.Close() + return nil, fmt.Errorf("migrate profile columns: %w", err) + } + st := &Store{db: db, dialect: dialectSQLite} + st.initSessionStore(sessionCleanup) + return st, nil +} + +func (s *Store) Close() error { + if s.sessionStopper != nil { + s.sessionStopper.StopCleanup() + s.sessionStopper = nil + } + return s.db.Close() +} + +func (s *Store) CreateUser(ctx context.Context, username, passwordHash string, asAdmin bool) (*User, error) { + username = NormalizeUsername(username) + role := "user" + if asAdmin { + role = "admin" + } + u := &User{ + ID: uuid.NewString(), + Username: username, + Name: username, + Role: role, + PasswordHash: passwordHash, + CreatedAt: time.Now().UTC().Format(time.RFC3339), + } + _, err := s.db.ExecContext(ctx, s.q(`INSERT INTO users (id, username, name, password_hash, role, avatar_url, state, created_at) VALUES (?, ?, ?, ?, ?, '', '', ?)`), + u.ID, u.Username, u.Name, u.PasswordHash, u.Role, u.CreatedAt) + if err != nil { + return nil, err + } + return u, nil +} + +func (s *Store) CountAdmins(ctx context.Context) (int, error) { + var n int + err := s.db.QueryRowContext(ctx, s.q(`SELECT COUNT(*) FROM users WHERE role = ?`), "admin").Scan(&n) + return n, err +} + +func (s *Store) ListUsers(ctx context.Context) ([]User, error) { + rows, err := s.db.QueryContext(ctx, s.q(`SELECT id, username, name, role, avatar_url, state, created_at FROM users ORDER BY created_at ASC`)) + if err != nil { + return nil, err + } + defer rows.Close() + var out []User + for rows.Next() { + var u User + if err := rows.Scan(&u.ID, &u.Username, &u.Name, &u.Role, &u.AvatarURL, &u.State, &u.CreatedAt); err != nil { + return nil, err + } + out = append(out, u) + } + return out, rows.Err() +} + +func (s *Store) SetRole(ctx context.Context, userID, role string) error { + if role != "user" && role != "admin" { + return fmt.Errorf("invalid role") + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + + var current string + err = tx.QueryRowContext(ctx, s.q(`SELECT role FROM users WHERE id = ?`), userID).Scan(¤t) + if err != nil { + return err + } + if current == "admin" && role == "user" { + var n int + if err := tx.QueryRowContext(ctx, s.q(`SELECT COUNT(*) FROM users WHERE role = ?`), "admin").Scan(&n); err != nil { + return err + } + if n <= 1 { + return ErrLastAdmin + } + } + res, err := tx.ExecContext(ctx, s.q(`UPDATE users SET role = ? WHERE id = ?`), role, userID) + if err != nil { + return err + } + aff, err := res.RowsAffected() + if err != nil { + return err + } + if aff == 0 { + return sql.ErrNoRows + } + return tx.Commit() +} + +func (s *Store) UserByID(ctx context.Context, id string) (*User, error) { + return scanUser(s.db.QueryRowContext(ctx, s.q(`SELECT id, username, name, role, avatar_url, state, created_at FROM users WHERE id = ?`), id), false) +} + +func (s *Store) UserByUsername(ctx context.Context, username string) (*User, error) { + return scanUser(s.db.QueryRowContext(ctx, s.q(`SELECT id, username, name, role, avatar_url, state, created_at, password_hash FROM users WHERE username = ?`), NormalizeUsername(username)), true) +} + +func scanUser(row *sql.Row, withSecrets bool) (*User, error) { + var u User + var err error + if withSecrets { + err = row.Scan(&u.ID, &u.Username, &u.Name, &u.Role, &u.AvatarURL, &u.State, &u.CreatedAt, &u.PasswordHash) + } else { + err = row.Scan(&u.ID, &u.Username, &u.Name, &u.Role, &u.AvatarURL, &u.State, &u.CreatedAt) + } + if err != nil { + return nil, err + } + return &u, nil +} + +func NormalizeUsername(s string) string { + return strings.ToLower(strings.TrimSpace(s)) +} + +func (s *Store) CreateQuestion(ctx context.Context, authorID, title, body, city string) (*RankedQuestion, error) { + q := &RankedQuestion{ + ID: uuid.NewString(), + AuthorID: authorID, + Title: strings.TrimSpace(title), + Body: strings.TrimSpace(body), + City: strings.TrimSpace(city), + HuntDate: pacific.Today(), + CreatedAt: time.Now().UTC().Format(time.RFC3339), + } + _, err := s.db.ExecContext(ctx, s.q(`INSERT INTO questions (id, author_id, title, body, city, hunt_date, hidden, created_at) VALUES (?, ?, ?, ?, ?, ?, 0, ?)`), + q.ID, q.AuthorID, q.Title, q.Body, q.City, q.HuntDate, q.CreatedAt) + if err != nil { + return nil, err + } + return q, nil +} + +func (s *Store) ListHunt(ctx context.Context, huntDate, viewerID string) ([]RankedQuestion, error) { + rows, err := s.db.QueryContext(ctx, s.q(` +SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE(SUM(v.value), 0) AS score, + CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END AS answered, + COALESCE((SELECT value FROM votes WHERE user_id = ? AND question_id = q.id), 0) AS user_vote +FROM questions q +JOIN users u ON u.id = q.author_id +LEFT JOIN votes v ON v.question_id = q.id +LEFT JOIN answers a ON a.question_id = q.id +WHERE q.hunt_date = ? AND q.hidden = 0 +GROUP BY q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, a.question_id +ORDER BY score DESC, q.created_at ASC`), viewerID, huntDate) + if err != nil { + return nil, err + } + defer rows.Close() + var out []RankedQuestion + for rows.Next() { + q, err := scanRanked(rows) + if err != nil { + return nil, err + } + out = append(out, q) + } + return out, rows.Err() +} + +func (s *Store) GetQuestion(ctx context.Context, id, viewerID string) (*RankedQuestion, error) { + row := s.db.QueryRowContext(ctx, s.q(` +SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE((SELECT SUM(value) FROM votes WHERE question_id = q.id), 0) AS score, + CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END AS answered, + COALESCE((SELECT value FROM votes WHERE user_id = ? AND question_id = q.id), 0) AS user_vote +FROM questions q +JOIN users u ON u.id = q.author_id +LEFT JOIN answers a ON a.question_id = q.id +WHERE q.id = ?`), viewerID, id) + q, err := scanRankedRow(row) + if err != nil { + return nil, err + } + return &q, nil +} + +type scanned interface { + Scan(dest ...any) error +} + +func scanRanked(rows scanned) (RankedQuestion, error) { + var q RankedQuestion + var hidden, answered int + err := rows.Scan(&q.ID, &q.AuthorID, &q.AuthorName, &q.Title, &q.Body, &q.City, &q.HuntDate, &hidden, &q.CreatedAt, &q.Score, &answered, &q.UserVote) + q.Hidden = hidden != 0 + q.Answered = answered != 0 + return q, err +} + +func scanRankedRow(row *sql.Row) (RankedQuestion, error) { + return scanRanked(row) +} + +func (s *Store) Vote(ctx context.Context, userID, questionID string, value int) error { + if value != 1 && value != -1 { + return fmt.Errorf("invalid vote") + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var current sql.NullInt64 + err = tx.QueryRowContext(ctx, s.q(`SELECT value FROM votes WHERE user_id = ? AND question_id = ?`), userID, questionID).Scan(¤t) + if err != nil && err != sql.ErrNoRows { + return err + } + if err == nil && current.Valid && int(current.Int64) == value { + _, err = tx.ExecContext(ctx, s.q(`DELETE FROM votes WHERE user_id = ? AND question_id = ?`), userID, questionID) + } else { + _, err = tx.ExecContext(ctx, s.q(`INSERT INTO votes (user_id, question_id, value) VALUES (?, ?, ?) +ON CONFLICT (user_id, question_id) DO UPDATE SET value = excluded.value`), userID, questionID, value) + } + if err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) GetAnswer(ctx context.Context, questionID string) (*Answer, error) { + var a Answer + err := s.db.QueryRowContext(ctx, s.q(` +SELECT a.question_id, a.author_id, u.name, a.body, a.created_at, a.updated_at +FROM answers a +JOIN users u ON u.id = a.author_id +WHERE a.question_id = ?`), questionID).Scan(&a.QuestionID, &a.AuthorID, &a.AuthorName, &a.Body, &a.CreatedAt, &a.UpdatedAt) + if err != nil { + return nil, err + } + return &a, nil +} + +func (s *Store) UpsertAnswer(ctx context.Context, questionID, authorID, body string) error { + body = strings.TrimSpace(body) + now := time.Now().UTC().Format(time.RFC3339) + _, err := s.db.ExecContext(ctx, s.q(` +INSERT INTO answers (question_id, author_id, body, created_at, updated_at) VALUES (?, ?, ?, ?, ?) +ON CONFLICT (question_id) DO UPDATE SET body = excluded.body, author_id = excluded.author_id, updated_at = excluded.updated_at`), + questionID, authorID, body, now, now) + return err +} + +func (s *Store) HideQuestion(ctx context.Context, id string) error { + _, err := s.db.ExecContext(ctx, s.q(`UPDATE questions SET hidden = 1 WHERE id = ?`), id) + return err +} + +func (s *Store) UpdateProfile(ctx context.Context, userID, state, avatarURL string) error { + state = strings.TrimSpace(state) + if avatarURL == "" { + _, err := s.db.ExecContext(ctx, s.q(`UPDATE users SET state = ? WHERE id = ?`), state, userID) + return err + } + _, err := s.db.ExecContext(ctx, s.q(`UPDATE users SET state = ?, avatar_url = ? WHERE id = ?`), state, avatarURL, userID) + return err +} + +func (s *Store) ListQuestionsByAuthor(ctx context.Context, authorID string) ([]RankedQuestion, error) { + rows, err := s.db.QueryContext(ctx, s.q(` +SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE((SELECT SUM(value) FROM votes WHERE question_id = q.id), 0) AS score, + CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END AS answered, + 0 AS user_vote +FROM questions q +JOIN users u ON u.id = q.author_id +LEFT JOIN answers a ON a.question_id = q.id +WHERE q.author_id = ? AND q.hidden = 0 +ORDER BY q.created_at DESC`), authorID) + if err != nil { + return nil, err + } + defer rows.Close() + return scanRankedList(rows) +} + +func (s *Store) ListQuestionsAnsweredBy(ctx context.Context, adminID string) ([]RankedQuestion, error) { + rows, err := s.db.QueryContext(ctx, s.q(` +SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE((SELECT SUM(value) FROM votes WHERE question_id = q.id), 0) AS score, + 1 AS answered, + 0 AS user_vote +FROM answers ans +JOIN questions q ON q.id = ans.question_id +JOIN users u ON u.id = q.author_id +WHERE ans.author_id = ? AND q.hidden = 0 +ORDER BY ans.updated_at DESC`), adminID) + if err != nil { + return nil, err + } + defer rows.Close() + return scanRankedList(rows) +} + +func scanRankedList(rows *sql.Rows) ([]RankedQuestion, error) { + var out []RankedQuestion + for rows.Next() { + q, err := scanRanked(rows) + if err != nil { + return nil, err + } + out = append(out, q) + } + return out, rows.Err() +} diff --git a/internal/web/admin.go b/internal/web/admin.go new file mode 100644 index 0000000..2e955d3 --- /dev/null +++ b/internal/web/admin.go @@ -0,0 +1,70 @@ +package web + +import ( + "errors" + "net/http" + + "github.com/go-chi/chi/v5" + + "plumber/internal/store" +) + +type adminUsersPage struct { + page + Users []store.User + Error string +} + +func (s *Server) requireAdmin(w http.ResponseWriter, r *http.Request) *store.User { + u := currentUser(r) + if !u.Admin() { + http.Error(w, "forbidden", http.StatusForbidden) + return nil + } + return u +} + +func (s *Server) handleAdminUsers(w http.ResponseWriter, r *http.Request) { + if s.requireAdmin(w, r) == nil { + return + } + users, err := s.store.ListUsers(r.Context()) + if err != nil { + http.Error(w, "could not load users", http.StatusInternalServerError) + return + } + s.exec(w, "admin-users", adminUsersPage{ + page: s.basePage(r, "Users"), + Users: users, + }) +} + +func (s *Server) handleAdminSetRole(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRF(w, r) { + return + } + if s.requireAdmin(w, r) == nil { + return + } + id := chi.URLParam(r, "id") + role := r.PostFormValue("role") + err := s.store.SetRole(r.Context(), id, role) + if errors.Is(err, store.ErrLastAdmin) { + users, listErr := s.store.ListUsers(r.Context()) + if listErr != nil { + http.Error(w, "could not demote last admin", http.StatusBadRequest) + return + } + s.exec(w, "admin-users", adminUsersPage{ + page: s.basePage(r, "Users"), + Users: users, + Error: "Cannot demote the last admin.", + }) + return + } + if err != nil { + http.Error(w, "could not update role", http.StatusBadRequest) + return + } + http.Redirect(w, r, "/admin/users", http.StatusSeeOther) +} diff --git a/internal/web/auth.go b/internal/web/auth.go new file mode 100644 index 0000000..4bfcb00 --- /dev/null +++ b/internal/web/auth.go @@ -0,0 +1,112 @@ +package web + +import ( + "net/http" + "net/url" + "regexp" + "strings" + "unicode/utf8" + + "golang.org/x/crypto/bcrypt" + + "plumber/internal/store" +) + +var usernameRe = regexp.MustCompile(`^[a-zA-Z0-9_]{3,20}$`) + +func safeNext(raw string) string { + if raw == "" { + return "/" + } + u, err := url.Parse(raw) + if err != nil || u.IsAbs() || !strings.HasPrefix(u.Path, "/") || strings.HasPrefix(u.Path, "//") { + return "/" + } + return u.RequestURI() +} + +func (s *Server) handleLoginForm(w http.ResponseWriter, r *http.Request) { + if currentUser(r) != nil { + http.Redirect(w, r, safeNext(r.URL.Query().Get("next")), http.StatusSeeOther) + return + } + s.exec(w, "login", authPage{ + page: s.basePage(r, "Sign in"), + Next: r.URL.Query().Get("next"), + }) +} + +func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRF(w, r) { + return + } + username := strings.TrimSpace(r.PostFormValue("username")) + password := r.PostFormValue("password") + next := safeNext(r.PostFormValue("next")) + u, err := s.store.UserByUsername(r.Context(), username) + if err != nil || bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password)) != nil { + w.WriteHeader(http.StatusUnauthorized) + s.exec(w, "login", authPage{ + page: s.basePage(r, "Sign in"), + Username: username, + Next: next, + Error: "Wrong username or password.", + }) + return + } + s.sessions.Put(r.Context(), "user_id", u.ID) + http.Redirect(w, r, next, http.StatusSeeOther) +} + +func (s *Server) handleRegisterForm(w http.ResponseWriter, r *http.Request) { + if currentUser(r) != nil { + http.Redirect(w, r, "/", http.StatusSeeOther) + return + } + s.exec(w, "register", authPage{page: s.basePage(r, "Create account")}) +} + +func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRF(w, r) { + return + } + username := strings.TrimSpace(r.PostFormValue("username")) + password := r.PostFormValue("password") + p := authPage{page: s.basePage(r, "Create account"), Username: username} + if !usernameRe.MatchString(username) { + p.Error = "Username must be 3–20 letters, numbers, or underscores." + s.exec(w, "register", p) + return + } + if utf8.RuneCountInString(password) < 8 { + p.Error = "Password must be at least 8 characters." + s.exec(w, "register", p) + return + } + hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + http.Error(w, "could not save password", http.StatusInternalServerError) + return + } + asAdmin := false + if s.cfg.AdminUsername != "" && store.NormalizeUsername(username) == store.NormalizeUsername(s.cfg.AdminUsername) { + n, err := s.store.CountAdmins(r.Context()) + if err != nil { + http.Error(w, "could not create account", http.StatusInternalServerError) + return + } + asAdmin = n == 0 + } + u, err := s.store.CreateUser(r.Context(), username, string(hash), asAdmin) + if err != nil { + p.Error = "That username is taken." + s.exec(w, "register", p) + return + } + s.sessions.Put(r.Context(), "user_id", u.ID) + http.Redirect(w, r, "/", http.StatusSeeOther) +} + +func (s *Server) handleAuthPrompt(w http.ResponseWriter, r *http.Request) { + s.exec(w, "signin-prompt", s.basePage(r, "")) +} diff --git a/internal/web/memstore_test.go b/internal/web/memstore_test.go new file mode 100644 index 0000000..0eb62d4 --- /dev/null +++ b/internal/web/memstore_test.go @@ -0,0 +1,330 @@ +package web + +import ( + "context" + "database/sql" + "fmt" + "sort" + "strings" + "sync" + "time" + + "github.com/google/uuid" + + "plumber/internal/pacific" + "plumber/internal/store" +) + +// memDB is an in-memory store.DB for tests. +type memDB struct { + mu sync.Mutex + users map[string]*store.User // id -> user + byName map[string]string // username -> id + questions map[string]*store.RankedQuestion // id -> question + votes map[string]int // userID|questionID -> value + answers map[string]*store.Answer // questionID -> answer +} + +func newMemDB() *memDB { + return &memDB{ + users: map[string]*store.User{}, + byName: map[string]string{}, + questions: map[string]*store.RankedQuestion{}, + votes: map[string]int{}, + answers: map[string]*store.Answer{}, + } +} + +func voteKey(userID, questionID string) string { + return userID + "|" + questionID +} + +func (m *memDB) CreateUser(_ context.Context, username, passwordHash string, asAdmin bool) (*store.User, error) { + m.mu.Lock() + defer m.mu.Unlock() + username = store.NormalizeUsername(username) + if _, ok := m.byName[username]; ok { + return nil, fmt.Errorf("username taken") + } + role := "user" + if asAdmin { + role = "admin" + } + u := &store.User{ + ID: uuid.NewString(), + Username: username, + Name: username, + Role: role, + PasswordHash: passwordHash, + CreatedAt: time.Now().UTC().Format(time.RFC3339), + } + m.users[u.ID] = u + m.byName[username] = u.ID + cp := *u + return &cp, nil +} + +func (m *memDB) UserByID(_ context.Context, id string) (*store.User, error) { + m.mu.Lock() + defer m.mu.Unlock() + u, ok := m.users[id] + if !ok { + return nil, sql.ErrNoRows + } + cp := *u + cp.PasswordHash = "" + return &cp, nil +} + +func (m *memDB) UserByUsername(_ context.Context, username string) (*store.User, error) { + m.mu.Lock() + defer m.mu.Unlock() + id, ok := m.byName[store.NormalizeUsername(username)] + if !ok { + return nil, sql.ErrNoRows + } + cp := *m.users[id] + return &cp, nil +} + +func (m *memDB) CountAdmins(_ context.Context) (int, error) { + m.mu.Lock() + defer m.mu.Unlock() + n := 0 + for _, u := range m.users { + if u.Role == "admin" { + n++ + } + } + return n, nil +} + +func (m *memDB) ListUsers(_ context.Context) ([]store.User, error) { + m.mu.Lock() + defer m.mu.Unlock() + out := make([]store.User, 0, len(m.users)) + for _, u := range m.users { + cp := *u + cp.PasswordHash = "" + out = append(out, cp) + } + sort.Slice(out, func(i, j int) bool { + return out[i].CreatedAt < out[j].CreatedAt + }) + return out, nil +} + +func (m *memDB) SetRole(_ context.Context, userID, role string) error { + if role != "user" && role != "admin" { + return fmt.Errorf("invalid role") + } + m.mu.Lock() + defer m.mu.Unlock() + u, ok := m.users[userID] + if !ok { + return sql.ErrNoRows + } + if u.Role == "admin" && role == "user" { + n := 0 + for _, x := range m.users { + if x.Role == "admin" { + n++ + } + } + if n <= 1 { + return store.ErrLastAdmin + } + } + u.Role = role + return nil +} + +func (m *memDB) CreateQuestion(_ context.Context, authorID, title, body, city string) (*store.RankedQuestion, error) { + m.mu.Lock() + defer m.mu.Unlock() + author, ok := m.users[authorID] + if !ok { + return nil, fmt.Errorf("unknown author") + } + q := &store.RankedQuestion{ + ID: uuid.NewString(), + AuthorID: authorID, + AuthorName: author.Name, + Title: strings.TrimSpace(title), + Body: strings.TrimSpace(body), + City: strings.TrimSpace(city), + HuntDate: pacific.Today(), + CreatedAt: time.Now().UTC().Format(time.RFC3339), + } + m.questions[q.ID] = q + cp := *q + return &cp, nil +} + +func (m *memDB) rankedLocked(q *store.RankedQuestion, viewerID string) store.RankedQuestion { + out := *q + score := 0 + for k, v := range m.votes { + _, qid, ok := strings.Cut(k, "|") + if ok && qid == q.ID { + score += v + } + } + out.Score = score + out.Answered = m.answers[q.ID] != nil + if viewerID != "" { + out.UserVote = m.votes[voteKey(viewerID, q.ID)] + } + if u, ok := m.users[q.AuthorID]; ok { + out.AuthorName = u.Name + } + return out +} + +func (m *memDB) ListHunt(_ context.Context, huntDate, viewerID string) ([]store.RankedQuestion, error) { + m.mu.Lock() + defer m.mu.Unlock() + var out []store.RankedQuestion + for _, q := range m.questions { + if q.HuntDate != huntDate || q.Hidden { + continue + } + out = append(out, m.rankedLocked(q, viewerID)) + } + sort.Slice(out, func(i, j int) bool { + if out[i].Score != out[j].Score { + return out[i].Score > out[j].Score + } + return out[i].CreatedAt < out[j].CreatedAt + }) + return out, nil +} + +func (m *memDB) GetQuestion(_ context.Context, id, viewerID string) (*store.RankedQuestion, error) { + m.mu.Lock() + defer m.mu.Unlock() + q, ok := m.questions[id] + if !ok { + return nil, sql.ErrNoRows + } + out := m.rankedLocked(q, viewerID) + return &out, nil +} + +func (m *memDB) Vote(_ context.Context, userID, questionID string, value int) error { + if value != 1 && value != -1 { + return fmt.Errorf("invalid vote") + } + m.mu.Lock() + defer m.mu.Unlock() + if _, ok := m.questions[questionID]; !ok { + return fmt.Errorf("unknown question") + } + k := voteKey(userID, questionID) + if cur, ok := m.votes[k]; ok && cur == value { + delete(m.votes, k) + return nil + } + m.votes[k] = value + return nil +} + +func (m *memDB) GetAnswer(_ context.Context, questionID string) (*store.Answer, error) { + m.mu.Lock() + defer m.mu.Unlock() + a, ok := m.answers[questionID] + if !ok { + return nil, sql.ErrNoRows + } + cp := *a + if u, ok := m.users[a.AuthorID]; ok { + cp.AuthorName = u.Name + } + return &cp, nil +} + +func (m *memDB) UpsertAnswer(_ context.Context, questionID, authorID, body string) error { + m.mu.Lock() + defer m.mu.Unlock() + body = strings.TrimSpace(body) + now := time.Now().UTC().Format(time.RFC3339) + if existing, ok := m.answers[questionID]; ok { + existing.Body = body + existing.AuthorID = authorID + existing.UpdatedAt = now + return nil + } + m.answers[questionID] = &store.Answer{ + QuestionID: questionID, + AuthorID: authorID, + Body: body, + CreatedAt: now, + UpdatedAt: now, + } + return nil +} + +func (m *memDB) HideQuestion(_ context.Context, id string) error { + m.mu.Lock() + defer m.mu.Unlock() + q, ok := m.questions[id] + if !ok { + return sql.ErrNoRows + } + q.Hidden = true + return nil +} + +func (m *memDB) UpdateProfile(_ context.Context, userID, state, avatarURL string) error { + m.mu.Lock() + defer m.mu.Unlock() + u, ok := m.users[userID] + if !ok { + return sql.ErrNoRows + } + u.State = state + if avatarURL != "" { + u.AvatarURL = avatarURL + } + return nil +} + +func (m *memDB) ListQuestionsByAuthor(_ context.Context, authorID string) ([]store.RankedQuestion, error) { + m.mu.Lock() + defer m.mu.Unlock() + var out []store.RankedQuestion + for _, q := range m.questions { + if q.AuthorID != authorID || q.Hidden { + continue + } + out = append(out, m.rankedLocked(q, "")) + } + sort.Slice(out, func(i, j int) bool { + return out[i].CreatedAt > out[j].CreatedAt + }) + return out, nil +} + +func (m *memDB) ListQuestionsAnsweredBy(_ context.Context, adminID string) ([]store.RankedQuestion, error) { + m.mu.Lock() + defer m.mu.Unlock() + var out []store.RankedQuestion + for qid, a := range m.answers { + if a.AuthorID != adminID { + continue + } + q, ok := m.questions[qid] + if !ok || q.Hidden { + continue + } + rq := m.rankedLocked(q, "") + rq.Answered = true + out = append(out, rq) + } + sort.Slice(out, func(i, j int) bool { + return out[i].CreatedAt > out[j].CreatedAt + }) + return out, nil +} + +var _ store.DB = (*memDB)(nil) diff --git a/internal/web/profile.go b/internal/web/profile.go new file mode 100644 index 0000000..1c214ec --- /dev/null +++ b/internal/web/profile.go @@ -0,0 +1,142 @@ +package web + +import ( + "io" + "net/http" + "path" + "strings" + + "github.com/google/uuid" + + "plumber/internal/geo" + "plumber/internal/store" +) + +type profilePage struct { + page + States []struct{ Code, Name string } + Questions []store.RankedQuestion + QuestionsLabel string + UploadsEnabled bool + Error string + StateVal string +} + +func (s *Server) handleProfileForm(w http.ResponseWriter, r *http.Request) { + u := currentUser(r) + if u == nil { + http.Redirect(w, r, "/login?next=/profile", http.StatusSeeOther) + return + } + s.renderProfile(w, r, u, "", u.State) +} + +func (s *Server) handleProfile(w http.ResponseWriter, r *http.Request) { + u := currentUser(r) + if u == nil { + http.Redirect(w, r, "/login?next=/profile", http.StatusSeeOther) + return + } + if err := r.ParseMultipartForm(3 << 20); err != nil { + s.renderProfile(w, r, u, "Could not read form (max 2MB for images).", u.State) + return + } + want := s.sessions.GetString(r.Context(), "csrf") + got := r.FormValue("_csrf") + if want == "" || got != want { + http.Error(w, "invalid csrf token", http.StatusForbidden) + return + } + + state := geo.NormalizeState(r.FormValue("state")) + if !geo.ValidState(state) { + s.renderProfile(w, r, u, "Choose a valid US state or leave it blank.", state) + return + } + + avatarURL := "" + file, hdr, err := r.FormFile("avatar") + if err == nil { + defer file.Close() + if !s.cfg.Blob.Enabled() { + s.renderProfile(w, r, u, "Avatar uploads are not configured on this server.", state) + return + } + ct := hdr.Header.Get("Content-Type") + ext, contentType, ok := avatarType(hdr.Filename, ct) + if !ok { + s.renderProfile(w, r, u, "Avatar must be a JPEG, PNG, or WebP image.", state) + return + } + if hdr.Size > 2<<20 { + s.renderProfile(w, r, u, "Avatar must be 2MB or smaller.", state) + return + } + key := path.Join("avatars", u.ID, uuid.NewString()+ext) + limited := io.LimitReader(file, (2<<20)+1) + url, upErr := s.cfg.Blob.Upload(r.Context(), key, limited, contentType, hdr.Size) + if upErr != nil { + s.renderProfile(w, r, u, "Could not upload avatar. Try again later.", state) + return + } + avatarURL = url + } else if err != http.ErrMissingFile { + s.renderProfile(w, r, u, "Could not read avatar file.", state) + return + } + + if err := s.store.UpdateProfile(r.Context(), u.ID, state, avatarURL); err != nil { + http.Error(w, "could not save profile", http.StatusInternalServerError) + return + } + s.sessions.Put(r.Context(), "flash", "Profile saved.") + http.Redirect(w, r, "/profile", http.StatusSeeOther) +} + +func avatarType(filename, contentType string) (ext, normalized string, ok bool) { + contentType = strings.ToLower(strings.TrimSpace(contentType)) + filename = strings.ToLower(filename) + switch { + case strings.HasPrefix(contentType, "image/jpeg"), strings.HasSuffix(filename, ".jpg"), strings.HasSuffix(filename, ".jpeg"): + return ".jpg", "image/jpeg", true + case strings.HasPrefix(contentType, "image/png"), strings.HasSuffix(filename, ".png"): + return ".png", "image/png", true + case strings.HasPrefix(contentType, "image/webp"), strings.HasSuffix(filename, ".webp"): + return ".webp", "image/webp", true + default: + return "", "", false + } +} + +func (s *Server) renderProfile(w http.ResponseWriter, r *http.Request, u *store.User, errMsg, stateVal string) { + var ( + questions []store.RankedQuestion + label string + err error + ) + if u.Admin() { + label = "Questions you answered" + questions, err = s.store.ListQuestionsAnsweredBy(r.Context(), u.ID) + } else { + label = "Your questions" + questions, err = s.store.ListQuestionsByAuthor(r.Context(), u.ID) + } + if err != nil { + http.Error(w, "could not load questions", http.StatusInternalServerError) + return + } + if fresh, e := s.store.UserByID(r.Context(), u.ID); e == nil { + u = fresh + } + p := s.basePage(r, "Profile") + p.User = u + s.exec(w, "profile", profilePage{ + page: p, + States: geo.States, + Questions: questions, + QuestionsLabel: label, + UploadsEnabled: s.cfg.Blob.Enabled(), + Error: errMsg, + StateVal: stateVal, + }) +} diff --git a/internal/web/server.go b/internal/web/server.go new file mode 100644 index 0000000..154515c --- /dev/null +++ b/internal/web/server.go @@ -0,0 +1,518 @@ +package web + +import ( + "context" + "crypto/rand" + "encoding/hex" + "fmt" + "html/template" + "io/fs" + "log" + "net/http" + "net/url" + "strings" + "time" + + "github.com/alexedwards/scs/v2" + "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" + + "plumber/internal/blob" + "plumber/internal/geo" + "plumber/internal/pacific" + "plumber/internal/store" +) + +type Config struct { + AdminUsername string + SecureCookie bool + Blob blob.Uploader +} + +type Server struct { + store store.DB + sessions *scs.SessionManager + tmpl *template.Template + cfg Config + static http.Handler +} + +type page struct { + User *store.User + CSRF string + Flash string + Title string + Today string + Yesterday string +} + +type huntPage struct { + page + Date string + Label string + IsToday bool + IsYesterday bool + Questions []store.RankedQuestion +} + +type questionPage struct { + page + Question *store.RankedQuestion + Answer *store.Answer +} + +type submitPage struct { + page + TitleVal string + BodyVal string + CityVal string + Error string +} + +type authPage struct { + page + Username string + Error string + Next string +} + +type voteCtx struct { + User *store.User + CSRF string + View string + Date string + Question store.RankedQuestion +} + +func New(st store.DB, sessionStore scs.Store, templateFS fs.FS, staticFS fs.FS, cfg Config) (*Server, error) { + if cfg.Blob == nil { + cfg.Blob = blob.Disabled{} + } + funcMap := template.FuncMap{ + "voteCtx": func(user *store.User, csrf, view, date string, q store.RankedQuestion) voteCtx { + return voteCtx{User: user, CSRF: csrf, View: view, Date: date, Question: q} + }, + "add": func(a, b int) int { return a + b }, + "rank": func(i int) int { return i + 1 }, + "isAdmin": func(u *store.User) bool { return u.Admin() }, + "pacificLabel": pacific.Label, + "locationTag": func(u *store.User) string { + if u != nil { + if name := geo.StateName(u.State); name != "" { + return name + } + } + return "Bay Area" + }, + } + tmpl, err := template.New("").Funcs(funcMap).ParseFS(templateFS, "templates/*.html", "templates/partials/*.html") + if err != nil { + return nil, fmt.Errorf("parse templates: %w", err) + } + sessions := scs.New() + sessions.Store = sessionStore + sessions.Lifetime = 30 * 24 * time.Hour + sessions.Cookie.Name = "plumber_session" + sessions.Cookie.HttpOnly = true + sessions.Cookie.SameSite = http.SameSiteLaxMode + sessions.Cookie.Secure = cfg.SecureCookie + sessions.Cookie.Path = "/" + + sub, err := fs.Sub(staticFS, "static") + if err != nil { + return nil, err + } + + return &Server{ + store: st, + sessions: sessions, + tmpl: tmpl, + cfg: cfg, + static: http.StripPrefix("/static/", http.FileServer(http.FS(sub))), + }, nil +} + +func (s *Server) Handler() http.Handler { + r := chi.NewRouter() + r.Use(middleware.RequestID) + r.Use(middleware.RealIP) + r.Use(middleware.Logger) + r.Use(middleware.Recoverer) + r.Use(func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, 3<<20) + next.ServeHTTP(w, r) + }) + }) + r.Use(s.sessions.LoadAndSave) + r.Use(s.withUser) + r.Handle("/static/*", s.static) + r.Get("/", s.handleToday) + r.Get("/archive", s.handleArchive) + r.Get("/hunt/{date}", s.handleHunt) + r.Get("/submit", s.handleSubmitForm) + r.Post("/submit", s.handleSubmit) + r.Get("/questions/{id}", s.handleQuestion) + r.Post("/questions/{id}/vote", s.handleVote) + r.Post("/questions/{id}/answer", s.handleAnswer) + r.Post("/questions/{id}/hide", s.handleHide) + r.Get("/login", s.handleLoginForm) + r.Post("/login", s.handleLogin) + r.Get("/register", s.handleRegisterForm) + r.Post("/register", s.handleRegister) + r.Get("/auth/prompt", s.handleAuthPrompt) + r.Post("/logout", s.handleLogout) + r.Get("/admin/users", s.handleAdminUsers) + r.Post("/admin/users/{id}/role", s.handleAdminSetRole) + r.Get("/profile", s.handleProfileForm) + r.Post("/profile", s.handleProfile) + return r +} + +type ctxKey int + +const userKey ctxKey = 1 + +func (s *Server) withUser(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if s.sessions.GetString(r.Context(), "csrf") == "" { + s.sessions.Put(r.Context(), "csrf", randomHex(16)) + } + id := s.sessions.GetString(r.Context(), "user_id") + if id != "" { + u, err := s.store.UserByID(r.Context(), id) + if err == nil { + r = r.WithContext(context.WithValue(r.Context(), userKey, u)) + } + } + next.ServeHTTP(w, r) + }) +} + +func currentUser(r *http.Request) *store.User { + u, _ := r.Context().Value(userKey).(*store.User) + return u +} + +func (s *Server) basePage(r *http.Request, title string) page { + return page{ + User: currentUser(r), + CSRF: s.sessions.GetString(r.Context(), "csrf"), + Flash: s.sessions.PopString(r.Context(), "flash"), + Title: title, + Today: pacific.Today(), + Yesterday: pacific.Yesterday(), + } +} + +func isHTMX(r *http.Request) bool { + return r.Header.Get("HX-Request") == "true" +} + +func (s *Server) requireCSRF(w http.ResponseWriter, r *http.Request) bool { + if err := r.ParseForm(); err != nil { + http.Error(w, "bad form", http.StatusBadRequest) + return false + } + want := s.sessions.GetString(r.Context(), "csrf") + got := r.PostFormValue("_csrf") + if want == "" || got != want { + http.Error(w, "invalid csrf token", http.StatusForbidden) + return false + } + return true +} + +func (s *Server) handleToday(w http.ResponseWriter, r *http.Request) { + s.renderHunt(w, r, pacific.Today()) +} + +func (s *Server) handleArchive(w http.ResponseWriter, r *http.Request) { + date := r.URL.Query().Get("date") + if date == "" || date == pacific.Today() { + http.Redirect(w, r, "/", http.StatusSeeOther) + return + } + if _, err := pacific.Parse(date); err != nil || date > pacific.Today() { + http.Redirect(w, r, "/", http.StatusSeeOther) + return + } + http.Redirect(w, r, "/hunt/"+url.PathEscape(date), http.StatusSeeOther) +} + +func (s *Server) handleHunt(w http.ResponseWriter, r *http.Request) { + date := chi.URLParam(r, "date") + if _, err := pacific.Parse(date); err != nil { + http.NotFound(w, r) + return + } + if date >= pacific.Today() { + http.Redirect(w, r, "/", http.StatusSeeOther) + return + } + s.renderHunt(w, r, date) +} + +func (s *Server) renderHunt(w http.ResponseWriter, r *http.Request, date string) { + viewer := "" + if u := currentUser(r); u != nil { + viewer = u.ID + } + questions, err := s.store.ListHunt(r.Context(), date, viewer) + if err != nil { + http.Error(w, "could not load questions", http.StatusInternalServerError) + return + } + label := pacific.Label(date) + title := label + if pacific.IsToday(date) { + title = "Today" + } + s.exec(w, "hunt", huntPage{ + page: s.basePage(r, title), + Date: date, + Label: label, + IsToday: pacific.IsToday(date), + IsYesterday: pacific.IsYesterday(date), + Questions: questions, + }) +} + +func (s *Server) handleSubmitForm(w http.ResponseWriter, r *http.Request) { + if currentUser(r) == nil { + s.sessions.Put(r.Context(), "flash", "Sign in to ask a question.") + http.Redirect(w, r, "/login?next=/submit", http.StatusSeeOther) + return + } + s.exec(w, "submit", submitPage{page: s.basePage(r, "Ask a question")}) +} + +func (s *Server) handleSubmit(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRF(w, r) { + return + } + u := currentUser(r) + if u == nil { + http.Redirect(w, r, "/login?next=/submit", http.StatusSeeOther) + return + } + title := strings.TrimSpace(r.PostFormValue("title")) + body := strings.TrimSpace(r.PostFormValue("body")) + city := strings.TrimSpace(r.PostFormValue("city")) + if title == "" || body == "" { + s.exec(w, "submit", submitPage{ + page: s.basePage(r, "Ask a question"), + TitleVal: title, + BodyVal: body, + CityVal: city, + Error: "Title and description are required.", + }) + return + } + if len(title) > 120 { + title = title[:120] + } + if len(body) > 8000 { + body = body[:8000] + } + if len(city) > 80 { + city = city[:80] + } + q, err := s.store.CreateQuestion(r.Context(), u.ID, title, body, city) + if err != nil { + http.Error(w, "could not save question", http.StatusInternalServerError) + return + } + http.Redirect(w, r, "/questions/"+url.PathEscape(q.ID), http.StatusSeeOther) +} + +func (s *Server) handleQuestion(w http.ResponseWriter, r *http.Request) { + id := chi.URLParam(r, "id") + viewer := "" + if u := currentUser(r); u != nil { + viewer = u.ID + } + q, err := s.store.GetQuestion(r.Context(), id, viewer) + if err != nil || (q.Hidden && !currentUser(r).Admin()) { + http.NotFound(w, r) + return + } + var ans *store.Answer + if q.Answered { + ans, _ = s.store.GetAnswer(r.Context(), q.ID) + } + s.exec(w, "question", questionPage{ + page: s.basePage(r, q.Title), + Question: q, + Answer: ans, + }) +} + +func (s *Server) handleVote(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRF(w, r) { + return + } + u := currentUser(r) + if u == nil { + if isHTMX(r) { + s.exec(w, "signin-prompt", s.basePage(r, "")) + return + } + http.Redirect(w, r, "/login", http.StatusSeeOther) + return + } + id := chi.URLParam(r, "id") + value := 0 + switch r.PostFormValue("value") { + case "1": + value = 1 + case "-1": + value = -1 + default: + http.Error(w, "invalid vote", http.StatusBadRequest) + return + } + if err := s.store.Vote(r.Context(), u.ID, id, value); err != nil { + http.Error(w, "could not vote", http.StatusInternalServerError) + return + } + view := r.PostFormValue("view") + date := r.PostFormValue("date") + if isHTMX(r) { + if view == "list" { + s.renderLeaderboard(w, r, date) + return + } + q, err := s.store.GetQuestion(r.Context(), id, u.ID) + if err != nil { + http.Error(w, "not found", http.StatusNotFound) + return + } + s.exec(w, "vote", voteCtx{ + User: u, + CSRF: s.sessions.GetString(r.Context(), "csrf"), + View: "question", + Date: q.HuntDate, + Question: *q, + }) + return + } + if view == "question" { + http.Redirect(w, r, "/questions/"+url.PathEscape(id), http.StatusSeeOther) + return + } + if date != "" && date != pacific.Today() { + http.Redirect(w, r, "/hunt/"+url.PathEscape(date), http.StatusSeeOther) + return + } + http.Redirect(w, r, "/", http.StatusSeeOther) +} + +func (s *Server) renderLeaderboard(w http.ResponseWriter, r *http.Request, date string) { + if date == "" { + date = pacific.Today() + } + viewer := "" + if u := currentUser(r); u != nil { + viewer = u.ID + } + questions, err := s.store.ListHunt(r.Context(), date, viewer) + if err != nil { + http.Error(w, "could not load questions", http.StatusInternalServerError) + return + } + s.exec(w, "leaderboard", huntPage{ + page: s.basePage(r, ""), + Date: date, + Questions: questions, + }) +} + +func (s *Server) handleAnswer(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRF(w, r) { + return + } + u := currentUser(r) + if !u.Admin() { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + id := chi.URLParam(r, "id") + body := strings.TrimSpace(r.PostFormValue("body")) + if body == "" { + http.Error(w, "answer required", http.StatusBadRequest) + return + } + if len(body) > 12000 { + body = body[:12000] + } + if err := s.store.UpsertAnswer(r.Context(), id, u.ID, body); err != nil { + http.Error(w, "could not save answer", http.StatusInternalServerError) + return + } + ans, err := s.store.GetAnswer(r.Context(), id) + if err != nil { + http.Error(w, "could not load answer", http.StatusInternalServerError) + return + } + if isHTMX(r) { + s.exec(w, "answer", questionPage{page: s.basePage(r, ""), Answer: ans}) + return + } + http.Redirect(w, r, "/questions/"+url.PathEscape(id), http.StatusSeeOther) +} + +func (s *Server) handleHide(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRF(w, r) { + return + } + u := currentUser(r) + if !u.Admin() { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + id := chi.URLParam(r, "id") + q, err := s.store.GetQuestion(r.Context(), id, u.ID) + if err != nil { + http.NotFound(w, r) + return + } + if err := s.store.HideQuestion(r.Context(), id); err != nil { + http.Error(w, "could not hide", http.StatusInternalServerError) + return + } + if isHTMX(r) && r.PostFormValue("view") == "list" { + s.renderLeaderboard(w, r, q.HuntDate) + return + } + if isHTMX(r) { + w.Header().Set("HX-Redirect", "/") + w.WriteHeader(http.StatusSeeOther) + return + } + http.Redirect(w, r, "/", http.StatusSeeOther) +} + +func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRF(w, r) { + return + } + s.sessions.Remove(r.Context(), "user_id") + http.Redirect(w, r, "/", http.StatusSeeOther) +} + +func (s *Server) exec(w http.ResponseWriter, name string, data any) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if err := s.tmpl.ExecuteTemplate(w, name, data); err != nil { + log.Printf("template %s: %v", name, err) + http.Error(w, "template error", http.StatusInternalServerError) + } +} + +func randomHex(n int) string { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + panic(err) + } + return hex.EncodeToString(b) +} diff --git a/internal/web/server_test.go b/internal/web/server_test.go new file mode 100644 index 0000000..aa6f849 --- /dev/null +++ b/internal/web/server_test.go @@ -0,0 +1,468 @@ +package web + +import ( + "bytes" + "context" + "io" + "mime/multipart" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/alexedwards/scs/v2" + + "plumber" +) + +func newTestServer(t *testing.T) (*Server, *memDB, scs.Store) { + t.Helper() + fake := newMemDB() + sessions := scs.New() + srv, err := New(fake, sessions.Store, plumber.TemplateFS, plumber.StaticFS, Config{AdminUsername: "hub"}) + if err != nil { + t.Fatal(err) + } + return srv, fake, sessions.Store +} + +func TestHomeEmptyAndViewport(t *testing.T) { + srv, _, _ := newTestServer(t) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/", nil) + srv.Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("status %d: %s", rec.Code, rec.Body.String()) + } + body := rec.Body.String() + if !strings.Contains(body, "No questions yet") { + t.Fatal("missing empty state") + } + if !strings.Contains(body, "width=device-width") { + t.Fatal("missing mobile viewport") + } + if !strings.Contains(body, "not a substitute for a licensed plumber") { + t.Fatal("missing disclaimer") + } +} + +func TestRegisterLoginAsk(t *testing.T) { + srv, _, _ := newTestServer(t) + h := srv.Handler() + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/register", nil)) + cookie := rec.Result().Cookies() + csrf := csrfFrom(rec.Body.String()) + if csrf == "" { + t.Fatal("no csrf") + } + form := strings.NewReader("_csrf=" + csrf + "&username=hub&password=hunter22") + req := httptest.NewRequest(http.MethodPost, "/register", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range cookie { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("register status %d %s", rec.Code, rec.Body.String()) + } + session := rec.Result().Cookies() + req = httptest.NewRequest(http.MethodGet, "/submit", nil) + for _, c := range session { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("submit form %d", rec.Code) + } + csrf = csrfFrom(rec.Body.String()) + form = strings.NewReader("_csrf=" + csrf + "&title=Leaky+faucet&body=Drip+all+night.&city=Oakland") + req = httptest.NewRequest(http.MethodPost, "/submit", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range session { + req.AddCookie(c) + } + for _, c := range rec.Result().Cookies() { + req.AddCookie(c) + } + rec2 := httptest.NewRecorder() + h.ServeHTTP(rec2, req) + if rec2.Code != http.StatusSeeOther { + t.Fatalf("submit %d %s", rec2.Code, rec2.Body.String()) + } +} + +func TestSessionSurvivesServerRestart(t *testing.T) { + fake := newMemDB() + sessionStore := scs.New().Store + + srv1, err := New(fake, sessionStore, plumber.TemplateFS, plumber.StaticFS, Config{AdminUsername: "hub"}) + if err != nil { + t.Fatal(err) + } + h1 := srv1.Handler() + + rec := httptest.NewRecorder() + h1.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/register", nil)) + preCookies := rec.Result().Cookies() + csrf := csrfFrom(rec.Body.String()) + if csrf == "" { + t.Fatal("no csrf") + } + form := strings.NewReader("_csrf=" + csrf + "&username=hub&password=hunter22") + req := httptest.NewRequest(http.MethodPost, "/register", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range preCookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h1.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("register status %d %s", rec.Code, rec.Body.String()) + } + sessionCookies := mergeCookies(preCookies, rec.Result().Cookies()) + + srv2, err := New(fake, sessionStore, plumber.TemplateFS, plumber.StaticFS, Config{AdminUsername: "hub"}) + if err != nil { + t.Fatal(err) + } + req = httptest.NewRequest(http.MethodGet, "/submit", nil) + for _, c := range sessionCookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + srv2.Handler().ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("expected authenticated submit form after restart, got %d: %s", rec.Code, rec.Body.String()) + } + if !strings.Contains(rec.Body.String(), "Ask a question") { + t.Fatal("session did not survive restart") + } +} + +func registerUser(t *testing.T, h http.Handler, username, password string) []*http.Cookie { + t.Helper() + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/register", nil)) + cookies := rec.Result().Cookies() + csrf := csrfFrom(rec.Body.String()) + form := strings.NewReader("_csrf=" + csrf + "&username=" + username + "&password=" + password) + req := httptest.NewRequest(http.MethodPost, "/register", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range cookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("register %s: %d %s", username, rec.Code, rec.Body.String()) + } + return mergeCookies(cookies, rec.Result().Cookies()) +} + +func TestAdminSeedOnlyWhenNoAdmins(t *testing.T) { + srv, fake, _ := newTestServer(t) + h := srv.Handler() + registerUser(t, h, "hub", "hunter22") + u, err := fake.UserByUsername(context.Background(), "hub") + if err != nil || !u.Admin() { + t.Fatalf("hub should be first admin: %+v %v", u, err) + } + registerUser(t, h, "hub2", "hunter22") + // Create another account that also matches AdminUsername after an admin exists — use a fresh server config with AdminUsername hub2 after hub exists + srv2, err := New(fake, scs.New().Store, plumber.TemplateFS, plumber.StaticFS, Config{AdminUsername: "lateradmin"}) + if err != nil { + t.Fatal(err) + } + registerUser(t, srv2.Handler(), "lateradmin", "hunter22") + u2, err := fake.UserByUsername(context.Background(), "lateradmin") + if err != nil { + t.Fatal(err) + } + if u2.Admin() { + t.Fatal("lateradmin must stay user when an admin already exists") + } +} + +func TestAdminUsersPageAccessAndRoles(t *testing.T) { + srv, fake, _ := newTestServer(t) + h := srv.Handler() + adminCookies := registerUser(t, h, "hub", "hunter22") + registerUser(t, h, "bob", "hunter22") + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/admin/users", nil) + for _, c := range adminCookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("admin list %d", rec.Code) + } + if !strings.Contains(rec.Body.String(), "bob") { + t.Fatal("missing bob on admin page") + } + + bob, err := fake.UserByUsername(context.Background(), "bob") + if err != nil { + t.Fatal(err) + } + csrf := csrfFrom(rec.Body.String()) + form := strings.NewReader("_csrf=" + csrf + "&role=admin") + req = httptest.NewRequest(http.MethodPost, "/admin/users/"+bob.ID+"/role", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range adminCookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("promote %d %s", rec.Code, rec.Body.String()) + } + bob, _ = fake.UserByUsername(context.Background(), "bob") + if !bob.Admin() { + t.Fatal("bob should be admin") + } + + // Non-admin forbidden + bobCookies := registerUser(t, h, "carol", "hunter22") + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/admin/users", nil) + for _, c := range bobCookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Fatalf("non-admin expected 403, got %d", rec.Code) + } + + // Demote last remaining admin after demoting bob first — leave only hub, then demote hub + hub, err := fake.UserByUsername(context.Background(), "hub") + if err != nil { + t.Fatal(err) + } + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/admin/users", nil) + for _, c := range adminCookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + csrf = csrfFrom(rec.Body.String()) + form = strings.NewReader("_csrf=" + csrf + "&role=user") + req = httptest.NewRequest(http.MethodPost, "/admin/users/"+bob.ID+"/role", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range adminCookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("demote bob %d", rec.Code) + } + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/admin/users", nil) + for _, c := range adminCookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + csrf = csrfFrom(rec.Body.String()) + form = strings.NewReader("_csrf=" + csrf + "&role=user") + req = httptest.NewRequest(http.MethodPost, "/admin/users/"+hub.ID+"/role", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range adminCookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("demote last admin expected page with error, got %d", rec.Code) + } + if !strings.Contains(rec.Body.String(), "Cannot demote the last admin") { + t.Fatalf("missing last-admin error: %s", rec.Body.String()) + } + hub, _ = fake.UserByUsername(context.Background(), "hub") + if !hub.Admin() { + t.Fatal("hub must remain admin") + } +} + +type fakeBlob struct { + calls int + last string +} + +func (f *fakeBlob) Enabled() bool { return true } + +func (f *fakeBlob) Upload(_ context.Context, key string, _ io.Reader, _ string, _ int64) (string, error) { + f.calls++ + f.last = key + return "https://cdn.example.com/" + key, nil +} + +func TestProfilePageAndState(t *testing.T) { + srv, fake, _ := newTestServer(t) + h := srv.Handler() + cookies := registerUser(t, h, "alice", "hunter22") + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/profile", nil) + for _, c := range cookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("profile %d", rec.Code) + } + if !strings.Contains(rec.Body.String(), "Your questions") { + t.Fatal("expected user questions label") + } + if !strings.Contains(rec.Body.String(), "local plumbing codes") { + t.Fatal("missing state helper copy") + } + + csrf := csrfFrom(rec.Body.String()) + var buf bytes.Buffer + w := multipart.NewWriter(&buf) + _ = w.WriteField("_csrf", csrf) + _ = w.WriteField("state", "CA") + _ = w.Close() + req = httptest.NewRequest(http.MethodPost, "/profile", &buf) + req.Header.Set("Content-Type", w.FormDataContentType()) + for _, c := range cookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("save profile %d %s", rec.Code, rec.Body.String()) + } + u, err := fake.UserByUsername(context.Background(), "alice") + if err != nil || u.State != "CA" { + t.Fatalf("state not saved: %+v %v", u, err) + } + + // invalid state + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/profile", nil) + for _, c := range cookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + csrf = csrfFrom(rec.Body.String()) + buf.Reset() + w = multipart.NewWriter(&buf) + _ = w.WriteField("_csrf", csrf) + _ = w.WriteField("state", "ZZ") + _ = w.Close() + req = httptest.NewRequest(http.MethodPost, "/profile", &buf) + req.Header.Set("Content-Type", w.FormDataContentType()) + for _, c := range cookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "valid US state") { + t.Fatalf("expected invalid state error, got %d %s", rec.Code, rec.Body.String()) + } +} + +func TestProfileAdminAnsweredListAndAvatarUpload(t *testing.T) { + fake := newMemDB() + blob := &fakeBlob{} + sessions := scs.New() + srv, err := New(fake, sessions.Store, plumber.TemplateFS, plumber.StaticFS, Config{ + AdminUsername: "hub", + Blob: blob, + }) + if err != nil { + t.Fatal(err) + } + h := srv.Handler() + adminCookies := registerUser(t, h, "hub", "hunter22") + userCookies := registerUser(t, h, "alice", "hunter22") + + alice, _ := fake.UserByUsername(context.Background(), "alice") + hub, _ := fake.UserByUsername(context.Background(), "hub") + q, err := fake.CreateQuestion(context.Background(), alice.ID, "Drip", "Under sink", "Oakland") + if err != nil { + t.Fatal(err) + } + if err := fake.UpsertAnswer(context.Background(), q.ID, hub.ID, "Replace the cartridge."); err != nil { + t.Fatal(err) + } + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/profile", nil) + for _, c := range adminCookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("admin profile %d", rec.Code) + } + body := rec.Body.String() + if !strings.Contains(body, "Questions you answered") || !strings.Contains(body, "Drip") { + t.Fatalf("admin answered list missing: %s", body) + } + + csrf := csrfFrom(body) + var buf bytes.Buffer + w := multipart.NewWriter(&buf) + _ = w.WriteField("_csrf", csrf) + _ = w.WriteField("state", "OR") + part, err := w.CreateFormFile("avatar", "pic.png") + if err != nil { + t.Fatal(err) + } + _, _ = part.Write([]byte("fakepngbytes")) + _ = w.Close() + req = httptest.NewRequest(http.MethodPost, "/profile", &buf) + req.Header.Set("Content-Type", w.FormDataContentType()) + for _, c := range adminCookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("avatar upload %d %s", rec.Code, rec.Body.String()) + } + if blob.calls != 1 { + t.Fatalf("expected 1 upload, got %d", blob.calls) + } + hub, _ = fake.UserByUsername(context.Background(), "hub") + if !strings.Contains(hub.AvatarURL, "cdn.example.com/avatars/") { + t.Fatalf("avatar url %q", hub.AvatarURL) + } + _ = userCookies +} + +func mergeCookies(sets ...[]*http.Cookie) []*http.Cookie { + byName := map[string]*http.Cookie{} + for _, set := range sets { + for _, c := range set { + byName[c.Name] = c + } + } + out := make([]*http.Cookie, 0, len(byName)) + for _, c := range byName { + out = append(out, c) + } + return out +} + +func csrfFrom(html string) string { + const needle = `name="_csrf" value="` + i := strings.Index(html, needle) + if i < 0 { + return "" + } + html = html[i+len(needle):] + j := strings.Index(html, `"`) + if j < 0 { + return "" + } + return html[:j] +} diff --git a/schema.sql b/schema.sql new file mode 100644 index 0000000..29bd809 --- /dev/null +++ b/schema.sql @@ -0,0 +1,40 @@ +PRAGMA foreign_keys = ON; + +CREATE TABLE IF NOT EXISTS users ( + id TEXT PRIMARY KEY, + username TEXT NOT NULL UNIQUE, + name TEXT NOT NULL, + password_hash TEXT NOT NULL, + role TEXT NOT NULL DEFAULT 'user' CHECK (role IN ('user', 'admin')), + avatar_url TEXT NOT NULL DEFAULT '', + state TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS questions ( + id TEXT PRIMARY KEY, + author_id TEXT NOT NULL REFERENCES users(id), + title TEXT NOT NULL, + body TEXT NOT NULL, + city TEXT NOT NULL DEFAULT '', + hunt_date TEXT NOT NULL, + hidden INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_questions_hunt_date ON questions(hunt_date, hidden); + +CREATE TABLE IF NOT EXISTS votes ( + user_id TEXT NOT NULL REFERENCES users(id), + question_id TEXT NOT NULL REFERENCES questions(id) ON DELETE CASCADE, + value INTEGER NOT NULL CHECK (value IN (-1, 1)), + PRIMARY KEY (user_id, question_id) +); + +CREATE TABLE IF NOT EXISTS answers ( + question_id TEXT PRIMARY KEY REFERENCES questions(id) ON DELETE CASCADE, + author_id TEXT NOT NULL REFERENCES users(id), + body TEXT NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); diff --git a/static/app.css b/static/app.css new file mode 100644 index 0000000..7fec899 --- /dev/null +++ b/static/app.css @@ -0,0 +1,789 @@ +:root { + --bg: #161719; + --panel: #1e2023; + --ink: #ecebe7; + --muted: #8d9096; + --line: #2e3136; + --zinc: #6b7078; + --signal: #e96a26; + --signal-ink: #161719; + --err: #e24b4b; + --err-bg: #2a1a1a; + --ok: #e96a26; + --sans: "Archivo", "Helvetica Neue", sans-serif; + --mono: "IBM Plex Mono", ui-monospace, monospace; + --pad: env(safe-area-inset-bottom, 0px); +} + +* { box-sizing: border-box; } + +html, body { + margin: 0; + padding: 0; + min-height: 100%; + background: var(--bg); + color: var(--ink); + font: 16px/1.45 var(--sans); + -webkit-text-size-adjust: 100%; + color-scheme: dark; +} + +body { + background-image: + linear-gradient(180deg, #1a1c1f 0%, var(--bg) 180px), + repeating-linear-gradient( + 90deg, + transparent, + transparent 47px, + #1c1e21 47px, + #1c1e21 48px + ); + background-size: 100% 100%, 48px 48px; +} + +img, svg { display: block; } + +a { + color: var(--signal); + text-underline-offset: 0.18em; +} + +.skip { + position: absolute; + left: -999px; +} +.skip:focus { + left: 12px; + top: 12px; + z-index: 20; + background: var(--panel); + padding: 8px 12px; +} + +.top { + position: sticky; + top: 0; + z-index: 20; + background: #141516; + border-bottom: 1px solid var(--line); + box-shadow: inset 0 2px 0 var(--signal); +} + +.top-inner { + width: min(840px, calc(100% - 32px)); + margin: 0 auto; + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 12px 16px; + padding: calc(12px + env(safe-area-inset-top, 0px)) 0 12px; +} + +.logo { + display: flex; + align-items: center; + gap: 12px; + color: var(--signal); + text-decoration: none; +} + +.mark { + width: 32px; + height: 32px; + flex: none; +} + +.logo-text { + display: flex; + flex-direction: column; + gap: 3px; +} + +.logo-name { + font-size: 0.95rem; + font-weight: 600; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--ink); + line-height: 1.15; +} + +.tagline { + color: var(--muted); + font-family: var(--mono); + font-size: 0.65rem; + letter-spacing: 0.12em; + text-transform: uppercase; +} + +.top-nav { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; +} + +.who { + color: var(--muted); + font-family: var(--mono); + font-size: 0.75rem; + max-width: 9rem; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + letter-spacing: 0.04em; +} + +.account-menu { + position: relative; +} + +.account-menu-toggle { + gap: 8px; + list-style: none; + padding-left: 10px; + border-color: transparent; +} + +.account-menu-toggle:hover { + border-color: transparent; +} + +.account-menu-toggle::-webkit-details-marker { display: none; } +.account-menu-toggle::marker { content: ""; } + +.nav-avatar { + width: 28px; + height: 28px; + border-radius: 50%; + object-fit: cover; + flex: none; + border: 1px solid var(--line); + background: var(--panel); +} + +.nav-avatar-ghost { + display: inline-flex; + align-items: center; + justify-content: center; + font-family: var(--mono); + font-size: 0.7rem; + font-weight: 600; + letter-spacing: 0; + text-transform: uppercase; + color: var(--signal); +} + +.account-menu-caret { + width: 0; + height: 0; + border-left: 4px solid transparent; + border-right: 4px solid transparent; + border-top: 5px solid var(--muted); +} + +.account-menu[open] .account-menu-caret { + border-top: none; + border-bottom: 5px solid var(--muted); +} + +.account-menu-panel { + position: absolute; + right: 0; + top: calc(100% + 6px); + z-index: 10; + min-width: 10.5rem; + padding: 6px; + background: var(--panel); + border: 1px solid var(--line); + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35); +} + +.account-menu-item { + display: flex; + align-items: center; + width: 100%; + min-height: 40px; + padding: 0 12px; + border: 0; + border-radius: 2px; + background: transparent; + color: var(--ink); + font: inherit; + font-weight: 600; + font-size: 0.75rem; + letter-spacing: 0.08em; + text-transform: uppercase; + text-decoration: none; + text-align: left; + cursor: pointer; +} + +.account-menu-item:hover, +.account-menu-item:focus-visible { + background: #26282c; + outline: none; +} + +.logout { margin: 0; } + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + min-height: 44px; + padding: 0 16px; + border-radius: 3px; + border: 1px solid transparent; + font: inherit; + font-weight: 600; + font-size: 0.8rem; + letter-spacing: 0.08em; + text-transform: uppercase; + text-decoration: none; + cursor: pointer; + touch-action: manipulation; +} + +.btn-primary { + background: var(--signal); + color: var(--signal-ink); +} + +.btn-primary:hover { filter: brightness(1.08); } + +.btn-ghost { + background: transparent; + color: var(--ink); + border-color: var(--line); +} + +.btn-ghost:hover { border-color: var(--zinc); } + +.wrap { + width: min(840px, calc(100% - 32px)); + margin: 28px auto 56px; +} + +#flash:empty { display: none; } + +.banner { + width: min(840px, calc(100% - 32px)); + margin: 16px auto 0; + padding: 12px 16px; + background: var(--panel); + border: 1px solid var(--line); + border-left: 3px solid var(--signal); + color: var(--ink); +} + +.banner.error { + background: var(--err-bg); + border-left-color: var(--err); + color: #ffd0d0; +} + +.hunt-head { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + align-items: end; + gap: 20px; + margin-bottom: 8px; + padding-bottom: 20px; + border-bottom: 1px solid var(--line); +} + +.eyebrow { + margin: 0; + font-family: var(--mono); + text-transform: uppercase; + letter-spacing: 0.16em; + font-size: 0.68rem; + font-weight: 500; + color: var(--signal); +} + +h1 { + margin: 10px 0 0; + font-size: clamp(1.8rem, 4.5vw, 2.75rem); + font-weight: 500; + letter-spacing: -0.03em; + line-height: 1.05; + text-wrap: pretty; +} + +.date-nav { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; +} + +.chip { + min-height: 40px; + padding: 8px 12px; + border-radius: 3px; + border: 1px solid var(--line); + background: transparent; + color: var(--ink); + text-decoration: none; + font-family: var(--mono); + font-weight: 500; + font-size: 0.72rem; + letter-spacing: 0.06em; + text-transform: uppercase; +} + +.chip.is-on { + background: var(--signal); + border-color: var(--signal); + color: var(--signal-ink); +} + +.date-form { + display: flex; + gap: 6px; + align-items: center; +} + +.date-form input[type="date"] { + min-height: 44px; + padding: 0 10px; + border: 1px solid var(--line); + border-radius: 3px; + font: inherit; + font-family: var(--mono); + font-size: 0.8rem; + background: var(--panel); + color: var(--ink); + color-scheme: dark; +} + +.board { + list-style: none; + margin: 0; + padding: 0; + background: var(--panel); + border: 1px solid var(--line); +} + +.row { + display: grid; + grid-template-columns: 2.8rem 3.25rem 1fr; + gap: 4px 8px; + align-items: start; + padding: 14px 12px; + border-bottom: 1px solid var(--line); +} + +.row:last-child { border-bottom: 0; } + +.row:hover { background: #24262b; } + +.rank { + font-family: var(--mono); + font-weight: 500; + font-size: 1.15rem; + line-height: 1; + color: var(--zinc); + text-align: right; + padding-top: 12px; +} + +.row:first-child .rank { color: var(--signal); } + +.vote { + display: flex; + flex-direction: column; + align-items: center; + gap: 0; +} + +.vote form { margin: 0; } + +.vote-btn { + width: 44px; + height: 40px; + display: inline-flex; + align-items: center; + justify-content: center; + border: 0; + background: transparent; + color: var(--zinc); + cursor: pointer; + text-decoration: none; + touch-action: manipulation; + border-radius: 3px; +} + +.vote-btn:hover { color: var(--ink); background: #2a2d32; } + +.vote-btn.is-up { color: var(--signal); } +.vote-btn.is-down { color: var(--muted); } + +.score { + font-family: var(--mono); + font-variant-numeric: tabular-nums; + font-weight: 500; + font-size: 0.85rem; +} + +.q-title { + color: var(--ink); + font-weight: 500; + text-decoration: none; + font-size: 1.05rem; + text-wrap: pretty; +} + +.q-title:hover { color: var(--signal); } + +.meta { + margin: 6px 0 0; + color: var(--muted); + font-family: var(--mono); + font-size: 0.72rem; + letter-spacing: 0.02em; +} + +.dot { margin: 0 0.35em; } + +.badge { + display: inline-block; + margin-left: 8px; + padding: 2px 6px; + border: 1px solid var(--signal); + color: var(--signal); + font-size: 0.62rem; + font-weight: 600; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.empty { + padding: 48px 16px; + text-align: left; + color: var(--muted); +} + +.empty-kicker { + font-family: var(--mono); + font-size: 0.72rem; + letter-spacing: 0.16em; + text-transform: uppercase; + color: var(--signal); + margin: 0 0 8px; +} + +.inline-hide { margin: 6px 0 0; } + +.linkish { + background: none; + border: 0; + padding: 0; + color: var(--muted); + font: inherit; + font-family: var(--mono); + font-size: 0.72rem; + letter-spacing: 0.06em; + text-transform: uppercase; + text-decoration: underline; + cursor: pointer; + min-height: 44px; +} + +.lede, .hint, .switch { + color: var(--muted); +} + +.lede { margin: 8px 0 0; max-width: 38rem; text-wrap: pretty; } + +.ask, .answer-form { + display: flex; + flex-direction: column; + gap: 8px; + margin-top: 20px; +} + +label { + font-family: var(--mono); + font-weight: 500; + font-size: 0.68rem; + letter-spacing: 0.12em; + text-transform: uppercase; + color: var(--muted); +} + +input[type="text"], +input[type="password"], +textarea { + width: 100%; + font: inherit; + font-size: 16px; + padding: 12px 12px; + border: 1px solid var(--line); + border-radius: 3px; + background: #141516; + color: var(--ink); +} + +input:focus, textarea:focus, .btn:focus-visible, .chip:focus-visible, .vote-btn:focus-visible { + outline: 2px solid var(--signal); + outline-offset: 2px; +} + +.optional { font-weight: 400; letter-spacing: 0.04em; } + +.panel-wrap, .auth-wrap { + background: var(--panel); + border: 1px solid var(--line); + border-radius: 3px; + padding: 24px 20px 28px; +} + +.question-page .q-detail { + display: grid; + grid-template-columns: 3.25rem 1fr; + gap: 8px 14px; + background: var(--panel); + border: 1px solid var(--line); + padding: 18px 14px; +} + +.question-page h1 { + font-size: clamp(1.5rem, 3.5vw, 2.1rem); + line-height: 1.15; +} + +.q-body, .answer-body { + white-space: pre-wrap; + margin: 14px 0 0; + text-wrap: pretty; +} + +.crumb { margin: 0 0 20px; } +.crumb a { + color: var(--muted); + text-decoration: none; + font-family: var(--mono); + font-size: 0.72rem; + letter-spacing: 0.08em; + text-transform: uppercase; +} +.crumb a:hover { color: var(--signal); } + +.answer { + margin-top: 16px; + padding: 20px 18px; + background: var(--panel); + border: 1px solid var(--line); +} + +.answer.is-in { + border-color: var(--signal); +} + +.answer-kicker { + margin: 0 0 6px; + font-family: var(--mono); + text-transform: uppercase; + letter-spacing: 0.16em; + font-size: 0.68rem; + font-weight: 500; + color: var(--signal); +} + +.answer h2 { + margin: 0; + font-size: 1.15rem; + font-weight: 500; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +.byline { + margin: 6px 0 0; + color: var(--muted); + font-family: var(--mono); + font-size: 0.72rem; +} + +.waiting { color: var(--muted); margin: 0; font-family: var(--mono); font-size: 0.8rem; } + +.auth-wrap { + width: min(420px, calc(100% - 32px)); +} + +.auth-wrap h1 { font-size: 1.7rem; } + +.site-footer { + width: min(840px, calc(100% - 32px)); + margin: 0 auto; + padding: 20px 0 calc(36px + var(--pad)); + color: var(--muted); + font-family: var(--mono); + font-size: 0.72rem; + line-height: 1.55; + border-top: 1px solid var(--line); +} + +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + border: 0; +} + +@media (min-width: 640px) { + .row { + grid-template-columns: 3.4rem 3.5rem 1fr; + padding: 16px 18px; + } + .rank { font-size: 1.35rem; } + .panel-wrap { padding: 32px; } +} + +@media (prefers-reduced-motion: reduce) { + .btn-primary:hover { filter: none; } +} + +.admin-users { margin-top: 20px; overflow-x: auto; } + +.user-table { + width: 100%; + border-collapse: collapse; + font-size: 0.95rem; +} + +.user-table th, +.user-table td { + text-align: left; + padding: 12px 10px; + border-bottom: 1px solid var(--line); + vertical-align: middle; +} + +.user-table th { + color: var(--muted); + font-family: var(--mono); + font-size: 0.7rem; + font-weight: 500; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.user-table .mono { + font-family: var(--mono); + font-size: 0.85rem; +} + +.user-actions form { margin: 0; display: inline; } + +.user-actions .btn { + min-height: 36px; + padding: 0 12px; + font-size: 0.7rem; +} + +.profile-page h2 { + margin: 40px 0 16px; + font-size: 1.15rem; + font-weight: 600; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +.profile-form { + display: flex; + flex-direction: column; + gap: 10px; + max-width: 28rem; + margin-top: 24px; +} + +.profile-avatar { + display: flex; + align-items: center; + gap: 16px; + margin-bottom: 8px; +} + +.avatar { + width: 96px; + height: 96px; + border-radius: 50%; + object-fit: cover; + border: 1px solid var(--line); + background: var(--panel); +} + +.avatar-empty { + display: flex; + align-items: center; + justify-content: center; + font-family: var(--mono); + font-size: 1.6rem; + font-weight: 600; + color: var(--signal); + text-transform: uppercase; +} + +.avatar-fields label { margin-bottom: 6px; display: block; } + +.hint, .muted { + margin: 0; + color: var(--muted); + font-family: var(--mono); + font-size: 0.72rem; + line-height: 1.45; +} + +.profile-form select, +.profile-form input[type="file"] { + width: 100%; + min-height: 44px; + padding: 8px 12px; + border: 1px solid var(--line); + border-radius: 3px; + background: var(--panel); + color: var(--ink); + font: inherit; +} + +.profile-form .btn { align-self: flex-start; margin-top: 8px; } + +.profile-q-list { + list-style: none; + margin: 0; + padding: 0; + border-top: 1px solid var(--line); +} + +.profile-q-list li { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + gap: 8px 16px; + padding: 14px 0; + border-bottom: 1px solid var(--line); +} + +.profile-q-list a { + color: var(--ink); + text-decoration: none; + font-weight: 500; +} + +.profile-q-list a:hover { color: var(--signal); } + +.profile-q-list .meta { + color: var(--muted); + font-family: var(--mono); + font-size: 0.72rem; +} diff --git a/static/htmx.min.js b/static/htmx.min.js new file mode 100644 index 0000000..59937d7 --- /dev/null +++ b/static/htmx.min.js @@ -0,0 +1 @@ +var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function D(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e=0}function le(e){return e.getRootNode({composed:true})===document}function F(e){return e.trim().split(/\s+/)}function ce(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){O(e);return null}}function B(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function U(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function e(e){return vn(ne().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function u(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return u(ne(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(ne(),e)}}function E(){return window}function z(e,t){e=y(e);if(t){E().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function $(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function f(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ue(y(e));if(!e){return}if(n){E().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ue(y(e));if(!r){return}if(n){E().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function Z(e,t){e=y(e);se(e.parentElement.children,function(e){G(e,t)});K(ue(e),t)}function g(e,t){e=ue(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&ue(c(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function ge(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function p(t,r,n){if(r.indexOf("global ")===0){return p(t,r.slice(7),true)}t=y(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=ge(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),ge(r.substr(8)))}else if(r.indexOf("find ")===0){e=u(f(t),ge(r.substr(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,ge(r.substr(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,ge(r.substr(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=m(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=f(m(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ae(e,t){if(typeof e!=="string"){return p(e,t)[0]}else{return p(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return u(f(t)||document,e)}else{return e}}function xe(e,t,n,r){if(k(t)){return{target:ne().body,event:J(e),listener:t,options:n}}else{return{target:y(e),event:J(t),listener:n,options:r}}}function ye(t,n,r,o){Vn(function(){const e=xe(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function be(t,n,r){Vn(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const ve=ne().createElement("output");function we(e,t){const n=re(e,t);if(n){if(n==="this"){return[Se(e,t)]}else{const r=p(e,n);if(r.length===0){O('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ue(o(e,function(e){return te(ue(e),t)!=null}))}function Ee(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ae(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Ce(t){const n=Q.config.attributesToSettle;for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=p(t,n,false);if(r){se(r,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!Re(s,e)){t=f(n)}const r={shouldSwap:true,target:e,fragment:t};if(!he(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);_e(s,e,e,t,i);Te()}se(i.elts,function(e){he(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Te(){const e=u("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=u("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){se(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){if(e.moveBefore){let e=u("#--htmx-preserve-pantry--");if(e==null){ne().body.insertAdjacentHTML("afterend","
");e=u("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Le(l,e,c){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=f(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Ae(e){return function(){G(e,Q.config.addedClass);kt(ue(e));Ne(f(e));he(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=$(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function a(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ue(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n0}function $e(e,t,r,o){if(!o){o={}}e=y(e);const i=o.contextElement?m(o.contextElement,false):ne();const n=document.activeElement;let s={};try{s={elt:n,start:n?n.selectionStart:null,end:n?n.selectionEnd:null}}catch(e){}const l=xn(e);if(r.swapStyle==="textContent"){e.textContent=t}else{let n=P(t);l.title=n.title;if(o.selectOOB){const u=o.selectOOB.split(",");for(let t=0;t0){E().setTimeout(c,r.settleDelay)}else{c()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(D(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}he(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(ne().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function C(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=C(e,Qe).trim();e.shift()}else{t=C(e,v)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{C(o,w);const l=o.length;const c=C(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};C(o,w);u.pollInterval=d(C(o,/[,\[\s]/));C(o,w);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const a={trigger:c};var i=nt(e,o,"event");if(i){a.eventFilter=i}C(o,w);while(o.length>0&&o[0]!==","){const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=d(C(o,v))}else if(f==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=C(o,v);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=rt(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=d(C(o,v))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=C(o,v)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=rt(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=C(o,v)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}r.push(a)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=te(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!gt(n,e,Mt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function at(e){return g(e,Q.config.disableSelector)}function ft(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=ne().location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){pt(t,function(e,t){const n=ue(e);if(at(n)){b(n);return}de(r,o,n,t)},n,e,true)})}}function ht(e,t){const n=ue(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(h(n,'input[type="submit"], button')&&(h(n,"[form]")||g(n,"form")!==null)){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function dt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function gt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function pt(l,c,e,u,a){const f=ie(l);let t;if(u.from){t=p(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in f)){f.lastValue=new WeakMap}t.forEach(function(e){if(!f.lastValue.has(u)){f.lastValue.set(u,new WeakMap)}f.lastValue.get(u).set(e,e.value)})}se(t,function(i){const s=function(e){if(!le(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(a||ht(e,l)){e.preventDefault()}if(gt(u,l,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ue(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=event.target;const r=n.value;const o=f.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){he(l,"htmx:trigger");c(l,e);f.throttle=E().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=E().setTimeout(function(){he(l,"htmx:trigger");c(l,e)},u.delay)}else{he(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let xt=null;function yt(){if(!xt){xt=function(){mt=true};window.addEventListener("scroll",xt);window.addEventListener("resize",xt);setInterval(function(){if(mt){mt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&X(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){he(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){he(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;he(e,"htmx:trigger");t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;se(r,function(r){if(s(t,"hx-"+r)){const o=te(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ue(e);if(g(n,Q.config.disableSelector)){b(n);return}de(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){yt();pt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ae(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ue(r),n,e)}else{pt(r,n,t,e)}}function Et(e){const t=ue(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Tt(e){const t=g(ue(e.target),"button, input[type='submit']");const n=Lt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function Lt(e){const t=g(ue(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",Tt);e.addEventListener("focusin",Tt);e.addEventListener("focusout",qt)}function Nt(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(at(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function It(t){ke(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Vt(t){if(!B()){return null}t=U(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){he(ne().body,"htmx:historyCacheMissLoad",i);const e=P(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=Ut();const r=xn(n);kn(e.title);qe(e);Ve(n,t,r);Te();Kt(r.tasks);Bt=o;he(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{fe(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Wt(e){zt();e=e||location.pathname+location.search;const t=Vt(e);if(t){const n=P(t.content);const r=Ut();const o=xn(r);kn(t.title);qe(n);Ve(r,n,o);Te();Kt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Bt=e;he(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Gt(e)}}}function Zt(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Yt(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function Qt(e,t){se(e.concat(t),function(e){const t=ie(e);t.requestCount=(t.requestCount||1)-1});se(e,function(e){const t=ie(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function en(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function on(t,n,r,o,i){if(o==null||en(t,o)){return}else{t.push(o)}if(tn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=M(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=M(o.files)}nn(s,e,n);if(i){sn(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){rn(e.name,e.value,n)}else{t.push(e)}if(i){sn(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}nn(t,e,n)})}}function sn(e,t){const n=e;if(n.willValidate){he(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});he(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function ln(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){on(n,o,i,g(e,"form"),l)}on(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const a=ee(u,"name");nn(a,u.value,o)}const c=we(e,"hx-include");se(c,function(e){on(n,r,i,ue(e),l);if(!h(e,"form")){se(f(e).querySelectorAll(ot),function(e){on(n,r,i,e,l)})}});ln(r,o);return{errors:i,formData:r,values:An(r)}}function un(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function an(e){e=qn(e);let n="";e.forEach(function(e,t){n=un(n,t,e)});return n}function fn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};bn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function hn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function dn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function gn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!dn(e)){r.show="top"}if(n){const s=F(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.slice(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{O("Unknown modifier in hx-swap: "+l)}}}}return r}function pn(e){return re(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function mn(t,n,r){let o=null;Ft(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(pn(n)){return ln(new FormData,qn(r))}else{return an(r)}}}function xn(e){return{tasks:[],elts:[e]}}function yn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ae(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ae(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function bn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return bn(ue(c(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function wn(e,t){return bn(e,"hx-vars",true,t)}function Sn(e,t){return bn(e,"hx-vals",false,t)}function En(e){return ce(wn(e),Sn(e))}function Cn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function On(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function R(e,t){return t.test(e.getAllResponseHeaders())}function Rn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return de(t,n,null,null,{targetOverride:y(r)||ve,returnPromise:true})}else{let e=y(r.target);if(r.target&&!e||r.source&&!e&&!y(r.source)){e=ve}return de(t,n,y(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return de(t,n,null,null,{returnPromise:true})}}function Hn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Tn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return he(e,"htmx:validateUrl",ce({url:o,sameHost:r},n))}function qn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Ln(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function An(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}else{return e[t]}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Ln(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function de(t,n,r,o,i,D){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ne().body}const M=i.handler||Dn;const X=i.select||null;if(!le(r)){oe(s);return e}const c=i.targetOverride||ue(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let u=ie(r);const a=u.lastButtonClicked;if(a){const L=ee(a,"formaction");if(L!=null){n=L}const A=ee(a,"formmethod");if(A!=null){if(A.toLowerCase()!=="dialog"){t=A}}}const f=re(r,"hx-confirm");if(D===undefined){const K=function(e){return de(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(he(r,"htmx:confirm",G)===false){oe(s);return e}}let h=r;let d=re(r,"hx-sync");let g=null;let F=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ue(ae(r,I))}d=(N[1]||"drop").trim();u=ie(h);if(d==="drop"&&u.xhr&&u.abortable!==true){oe(s);return e}else if(d==="abort"){if(u.xhr){oe(s);return e}else{F=true}}else if(d==="replace"){he(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");g=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){he(h,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(g==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="all"){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){de(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;u.xhr=p;u.abortable=F;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const B=re(r,"hx-prompt");if(B){var x=prompt(B);if(x===null||!he(r,"htmx:prompt",{prompt:x,target:c})){oe(s);m();return e}}if(f&&!D){if(!confirm(f)){oe(s);m();return e}}let y=fn(r,c,x);if(t!=="get"&&!pn(r)){y["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){y=ce(y,i.headers)}const U=cn(r,t);let b=U.errors;const j=U.formData;if(i.values){ln(j,qn(i.values))}const V=qn(En(r));const v=ln(j,V);let w=hn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=bn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:w,parameters:An(w),unfilteredFormData:v,unfilteredParameters:An(v),headers:y,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!he(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;y=C.headers;w=qn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){he(r,"htmx:validation:halted",C);oe(s);m();return e}const z=n.split("#");const $=z[0];const O=z[1];let R=n;if(E){R=$;const Z=!w.keys().next().done;if(Z){if(R.indexOf("?")<0){R+="?"}else{R+="&"}R+=an(w);if(O){R+="#"+O}}}if(!Tn(r,R,C)){fe(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),R,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const k in y){if(y.hasOwnProperty(k)){const Y=y[k];Cn(p,k,Y)}}}const H={xhr:p,target:c,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:R,responsePath:null,anchor:O}};p.onload=function(){try{const t=Hn(r);H.pathInfo.responsePath=On(p);M(r,H);if(H.keepIndicators!==true){Qt(T,q)}he(r,"htmx:afterRequest",H);he(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){he(e,"htmx:afterRequest",H);he(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){fe(r,"htmx:onLoadError",ce({error:e},H));throw e}};p.onerror=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:timeout",H);oe(l);m()};if(!he(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Zt(r);var q=Yt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){he(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});he(r,"htmx:beforeSend",H);const J=E?null:mn(p,r,w);p.send(J);return e}function Nn(e,t){const n=t.xhr;let r=null;let o=null;if(R(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(R(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(R(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=re(e,"hx-push-url");const c=re(e,"hx-replace-url");const u=ie(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(c){a="replace";f=c}else if(u){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function In(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Pn(e){for(var t=0;t0){E().setTimeout(e,x.swapDelay)}else{e()}}if(f){fe(o,"htmx:responseError",ce({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Mn={};function Xn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Fn(e,t){if(t.init){t.init(n)}Mn[e]=ce(Xn(),t)}function Bn(e){delete Mn[e]}function Un(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Mn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return Un(ue(c(e)),n,r)}var jn=false;ne().addEventListener("DOMContentLoaded",function(){jn=true});function Vn(e){if(jn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function _n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend"," ."+Q.config.indicatorClass+"{opacity:0} ."+Q.config.requestClass+" ."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ."+Q.config.requestClass+"."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function $n(){const e=zn();if(e){Q.config=ce(Q.config,e)}}Vn(function(){$n();_n();let e=ne().body;kt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){Wt();se(t,function(e){he(e,"htmx:restored",{document:ne(),triggerEvent:he})})}else{if(n){n(e)}}};E().setTimeout(function(){he(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file diff --git a/templates/admin_users.html b/templates/admin_users.html new file mode 100644 index 0000000..d15e846 --- /dev/null +++ b/templates/admin_users.html @@ -0,0 +1,45 @@ +{{define "admin-users"}} +{{template "header" .}} +
+

Admin

+

Users

+ {{if .Error}}{{end}} +
+ + + + + + + + + + {{range .Users}} + + + + + + {{else}} + + {{end}} + +
UsernameRoleActions
{{.Username}}{{.Role}}
No users yet.
+
+
+{{template "footer" .}} +{{end}} diff --git a/templates/base.html b/templates/base.html new file mode 100644 index 0000000..f7a32d0 --- /dev/null +++ b/templates/base.html @@ -0,0 +1,73 @@ +{{define "header"}} + + + + + + {{if .Title}}{{.Title}} · {{end}}Ask a Plumber First + + + + + + + + + +
+
+ + +
+
+
+ {{if .Flash}}{{end}} +
+{{end}} + +{{define "footer"}} +
+

This site is not a substitute for a licensed plumber. Advice is general and based on the question as written. If you have a gas leak, flooding, or another emergency, leave the area if needed and call 911.

+
+ + +{{end}} diff --git a/templates/hunt.html b/templates/hunt.html new file mode 100644 index 0000000..fc939ca --- /dev/null +++ b/templates/hunt.html @@ -0,0 +1,21 @@ +{{define "hunt"}} +{{template "header" .}} +
+
+
+

{{if .IsToday}}Live board{{else if .IsYesterday}}Prior board{{else}}Archive{{end}}

+

{{.Label}}

+
+ +
+ {{template "leaderboard" .}} +
+{{template "footer" .}} +{{end}} diff --git a/templates/login.html b/templates/login.html new file mode 100644 index 0000000..e1dc202 --- /dev/null +++ b/templates/login.html @@ -0,0 +1,19 @@ +{{define "login"}} +{{template "header" .}} +
+

Access

+

Sign in

+ {{if .Error}}{{end}} +
+ + + + + + + +
+

New here? Create an account

+
+{{template "footer" .}} +{{end}} diff --git a/templates/partials/_answer.html b/templates/partials/_answer.html new file mode 100644 index 0000000..f50904a --- /dev/null +++ b/templates/partials/_answer.html @@ -0,0 +1,12 @@ +{{define "answer"}} +
+ {{if .Answer}} +

Shop response

+

Answer

+ +

{{.Answer.Body}}

+ {{else}} +

No answer yet. Check back after the hunt.

+ {{end}} +
+{{end}} diff --git a/templates/partials/_list.html b/templates/partials/_list.html new file mode 100644 index 0000000..5b8bb4a --- /dev/null +++ b/templates/partials/_list.html @@ -0,0 +1,37 @@ +{{define "leaderboard"}} +
    + {{if not .Questions}} +
  1. + {{if eq .Date .Today}} +

    Queue empty

    +

    No questions yet. Be the first to ask.

    + {{else}} +

    No questions on this day.

    + {{end}} +
  2. + {{else}} + {{range $i, $q := .Questions}} +
  3. + + {{template "vote" (voteCtx $.User $.CSRF "list" $.Date $q)}} +
    + {{$q.Title}} +

    + {{$q.AuthorName}} + {{if $q.City}}{{$q.City}}{{end}} + {{if $q.Answered}}Answered{{end}} +

    + {{if isAdmin $.User}} +
    + + + +
    + {{end}} +
    +
  4. + {{end}} + {{end}} +
+{{end}} diff --git a/templates/partials/_signin.html b/templates/partials/_signin.html new file mode 100644 index 0000000..0ba989f --- /dev/null +++ b/templates/partials/_signin.html @@ -0,0 +1,8 @@ +{{define "signin-prompt"}} + +{{end}} diff --git a/templates/partials/_vote.html b/templates/partials/_vote.html new file mode 100644 index 0000000..7b40010 --- /dev/null +++ b/templates/partials/_vote.html @@ -0,0 +1,37 @@ +{{define "vote"}} +
+ {{if .User}} +
+ + + + + +
+ {{.Question.Score}} +
+ + + + + +
+ {{else}} + + + + {{.Question.Score}} + + + + {{end}} +
+{{end}} diff --git a/templates/profile.html b/templates/profile.html new file mode 100644 index 0000000..2bd4176 --- /dev/null +++ b/templates/profile.html @@ -0,0 +1,57 @@ +{{define "profile"}} +{{template "header" .}} +
+

Account

+

Profile

+ {{if .Error}}{{end}} + +
+ + +
+ {{if .User.AvatarURL}} + + {{else}} + + {{end}} +
+ + {{if .UploadsEnabled}} + +

JPEG, PNG, or WebP · max 2MB

+ {{else}} +

Avatar uploads are not configured on this server.

+ {{end}} +
+
+ + + +

Optional. Sharing your state helps answers line up with local plumbing codes.

+ + +
+ +
+

{{.QuestionsLabel}}

+ {{if .Questions}} +
    + {{range .Questions}} +
  • + {{.Title}} + {{.HuntDate}} +
  • + {{end}} +
+ {{else}} +

Nothing here yet.

+ {{end}} +
+
+{{template "footer" .}} +{{end}} diff --git a/templates/question.html b/templates/question.html new file mode 100644 index 0000000..4f83855 --- /dev/null +++ b/templates/question.html @@ -0,0 +1,37 @@ +{{define "question"}} +{{template "header" .}} +
+

← {{pacificLabel .Question.HuntDate}}

+
+ {{template "vote" (voteCtx .User .CSRF "question" .Question.HuntDate .Question)}} +
+

{{.Question.Title}}

+

+ {{.Question.AuthorName}} + {{if .Question.City}}{{.Question.City}}{{end}} + + {{.Question.HuntDate}} +

+

{{.Question.Body}}

+ {{if isAdmin .User}} +
+ + +
+ {{end}} +
+
+ {{template "answer" .}} + {{if isAdmin .User}} +
+ + + + +
+ {{end}} +
+{{template "footer" .}} +{{end}} diff --git a/templates/register.html b/templates/register.html new file mode 100644 index 0000000..1e2c273 --- /dev/null +++ b/templates/register.html @@ -0,0 +1,20 @@ +{{define "register"}} +{{template "header" .}} +
+

New account

+

Create an account

+ {{if .Error}}{{end}} +
+ + + +

3–20 letters, numbers, or underscores.

+ + +

At least 8 characters.

+ +
+

Already have an account? Sign in

+
+{{template "footer" .}} +{{end}} diff --git a/templates/submit.html b/templates/submit.html new file mode 100644 index 0000000..ce8668f --- /dev/null +++ b/templates/submit.html @@ -0,0 +1,19 @@ +{{define "submit"}} +{{template "header" .}} +
+

Ask a question

+

It lands on today’s hunt (Pacific time). People vote; the ranking resets at midnight PT.

+ {{if .Error}}{{end}} +
+ + + + + + + + +
+
+{{template "footer" .}} +{{end}} diff --git a/todo.md b/todo.md new file mode 100644 index 0000000..b4d0601 --- /dev/null +++ b/todo.md @@ -0,0 +1,33 @@ +# Plumber — follow-ups + +From the project review. Priority order within each section. + +## Fix soon + +- [x] **Persist sessions** — Sessions live in the app DB (`sessions` table): SQLite locally, `postgresstore` when `DATABASE_URL` is set. Opaque cookie unchanged; unused `SESSION_SECRET` removed from config / `.env.example`. +- [x] **Drop Dockerfile** — Deploying on DigitalOcean App Platform (buildpack from `go.mod`); no container image needed. +- [ ] **Rune-safe truncation** — `title[:120]`, `body[:8000]`, `city[:80]`, answer body, etc. can split multi-byte UTF-8. Truncate by runes (or safely). +- [x] **Admin bootstrap** — `ADMIN_USERNAME` seeds the first admin on register only when no admin exists. Promote/demote via `/admin/users` (admins only); roles stay in `users.role`. + +## Docs & ops + +- [ ] **README** — How to run locally, env vars (from `.env.example`), admin bootstrap, SQLite vs PlanetScale `DATABASE_URL`, App Platform notes (`PORT`, `SECURE_COOKIE=1`). +- [ ] **Migrations story** — Schema is applied on boot from `schema.sql` (+ sessions DDL). OK for v1; plan real migrations before schema drifts between SQLite and Postgres. +- [x] **App Platform listen port** — Prefers `PORT`, then `LISTEN`, then `:8080`. +- [x] **Prod DB = PlanetScale Postgres** — App already opens Postgres when `DATABASE_URL` is set; DSN cleanup strips PlanetScale/libpq-only params (`sslrootcert=system`, `sslnegotiation`). Use dashboard URI on **5432** for boot schema create; **6432** (PgBouncer) later if you need pooling. + +## Smaller / later + +- [ ] Rate-limit login/register (bcrypt helps; still open to brute-force). +- [ ] Graceful shutdown instead of bare `ListenAndServe`. +- [ ] More tests: vote HTMX paths, admin answer/hide, archive redirects; optional Postgres integration test. +- [ ] Watch dual-dialect schema — one SQL file works now; expect divergence later. + +## Suggested order of attack + +1. ~~Persist sessions~~ done. +2. ~~Drop Dockerfile~~ done (App Platform). +3. ~~Wire `PORT`~~ done. +4. ~~Admin roles page~~ done. +5. Short README (run, env, admin, App Platform + PlanetScale). +6. Rune-safe truncation + a couple of handler tests (vote, admin hide). From 3391cce7bdd4398fbe11916f68490925c55ddf93 Mon Sep 17 00:00:00 2001 From: codegirl-007 Date: Fri, 21 Aug 2026 23:40:59 -0700 Subject: [PATCH 02/17] Address PR review: graceful shutdown, Role/NewUser, drop SQLite. --- .env.example | 7 +- cmd/server/main.go | 69 +++++++++++++----- go.mod | 9 --- go.sum | 46 ------------ internal/blob/spaces.go | 26 +++---- internal/store/db.go | 19 ++++- internal/store/migrate.go | 16 +---- internal/store/postgres.go | 43 +++--------- internal/store/sessions.go | 128 ++-------------------------------- internal/store/store.go | 79 ++++++--------------- internal/web/admin.go | 2 +- internal/web/auth.go | 12 +++- internal/web/memstore_test.go | 33 +++++---- 13 files changed, 152 insertions(+), 337 deletions(-) diff --git a/.env.example b/.env.example index e6941bb..a4d043c 100644 --- a/.env.example +++ b/.env.example @@ -1,14 +1,13 @@ # Local listen address (ignored when PORT is set, e.g. on App Platform) LISTEN=:8080 -DATA_PATH=data.db +# Required: PlanetScale Postgres URI (port 5432 so the app can create tables on boot). +# Switch to 6432 (PgBouncer) later if you need pooling. +DATABASE_URL=postgresql://user:password@host.example.com:5432/postgres?sslmode=verify-full # Optional: first matching registrant becomes admin only if no admin exists yet. # Later promote/demote via /admin/users (admins only). ADMIN_USERNAME=yourusername # Set to 1 when serving over HTTPS SECURE_COOKIE=0 -# Prod (PlanetScale Postgres): paste the dashboard URI. When set, SQLite is ignored. -# Use port 5432 so the app can create tables on boot. Switch to 6432 (PgBouncer) later if you need pooling. -# DATABASE_URL=postgresql://user:password@host.example.com:5432/postgres?sslmode=verify-full # DigitalOcean Spaces (profile avatars). Leave unset to disable uploads. # SPACES_KEY= # SPACES_SECRET= diff --git a/cmd/server/main.go b/cmd/server/main.go index 169fa9a..b482bf9 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -1,10 +1,15 @@ package main import ( + "context" + "errors" "log" "net/http" "os" + "os/signal" "strings" + "syscall" + "time" "github.com/joho/godotenv" @@ -17,29 +22,25 @@ import ( func main() { _ = godotenv.Load() listen := listenAddr() - st, err := store.Connect(os.Getenv("DATABASE_URL"), env("DATA_PATH", "data.db"), plumber.SchemaSQL) + + databaseURL := strings.TrimSpace(os.Getenv("DATABASE_URL")) + if databaseURL == "" { + log.Fatal("DATABASE_URL is required") + } + st, err := store.OpenPostgres(databaseURL, plumber.SchemaSQL) if err != nil { log.Fatalf("database: %v", err) } defer st.Close() - if os.Getenv("DATABASE_URL") != "" { - log.Printf("database: postgres") - } else { - log.Printf("database: sqlite") - } - uploader := blob.NewSpaces(blob.SpacesConfig{ - Key: os.Getenv("SPACES_KEY"), - Secret: os.Getenv("SPACES_SECRET"), - Region: os.Getenv("SPACES_REGION"), - Bucket: os.Getenv("SPACES_BUCKET"), - Endpoint: os.Getenv("SPACES_ENDPOINT"), - CDNBase: os.Getenv("SPACES_CDN_BASE"), - }) + log.Printf("database: postgres") + + uploader := spacesUploader() if uploader.Enabled() { log.Printf("avatars: digitalocean spaces") } else { log.Printf("avatars: uploads disabled (set SPACES_* to enable)") } + srv, err := web.New(st, st.SessionStore(), plumber.TemplateFS, plumber.StaticFS, web.Config{ AdminUsername: os.Getenv("ADMIN_USERNAME"), SecureCookie: os.Getenv("SECURE_COOKIE") == "1", @@ -48,12 +49,46 @@ func main() { if err != nil { log.Fatalf("server: %v", err) } - log.Printf("listening on %s", listen) - if err := http.ListenAndServe(listen, srv.Handler()); err != nil { - log.Fatal(err) + + httpSrv := &http.Server{Addr: listen, Handler: srv.Handler()} + errCh := make(chan error, 1) + go func() { + log.Printf("listening on %s", listen) + errCh <- httpSrv.ListenAndServe() + }() + + sigCh := make(chan os.Signal, 1) + signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM) + + select { + case err := <-errCh: + if err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Fatal(err) + } + case sig := <-sigCh: + log.Printf("shutdown signal: %v", sig) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := httpSrv.Shutdown(ctx); err != nil { + log.Printf("shutdown: %v", err) + } + if err := <-errCh; err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Fatal(err) + } } } +func spacesUploader() blob.Uploader { + return blob.NewSpaces(blob.SpacesConfig{ + Key: os.Getenv("SPACES_KEY"), + Secret: os.Getenv("SPACES_SECRET"), + Region: os.Getenv("SPACES_REGION"), + Bucket: os.Getenv("SPACES_BUCKET"), + Endpoint: os.Getenv("SPACES_ENDPOINT"), + CDNBase: os.Getenv("SPACES_CDN_BASE"), + }) +} + // listenAddr prefers PORT (App Platform / PaaS), then LISTEN, then :8080. func listenAddr() string { if p := strings.TrimSpace(os.Getenv("PORT")); p != "" { diff --git a/go.mod b/go.mod index a4ba585..84dc9b5 100644 --- a/go.mod +++ b/go.mod @@ -13,7 +13,6 @@ require ( github.com/jackc/pgx/v5 v5.10.0 github.com/joho/godotenv v1.5.1 golang.org/x/crypto v0.55.0 - modernc.org/sqlite v1.57.0 ) require ( @@ -26,17 +25,9 @@ require ( github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.38 // indirect github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.39 // indirect github.com/aws/smithy-go v1.27.8 // indirect - github.com/dustin/go-humanize v1.0.1 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect - github.com/mattn/go-isatty v0.0.24 // indirect - github.com/ncruces/go-strftime v1.0.0 // indirect - github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect golang.org/x/sync v0.22.0 // indirect - golang.org/x/sys v0.47.0 // indirect golang.org/x/text v0.41.0 // indirect - modernc.org/libc v1.74.4 // indirect - modernc.org/mathutil v1.7.1 // indirect - modernc.org/memory v1.11.0 // indirect ) diff --git a/go.sum b/go.sum index 66a4c4b..88aefcd 100644 --- a/go.sum +++ b/go.sum @@ -29,16 +29,10 @@ github.com/aws/smithy-go v1.27.8/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqx 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= -github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= -github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8= github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= -github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo= -github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= -github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= @@ -51,14 +45,8 @@ github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/lib/pq v1.4.0 h1:TmtCFbH+Aw0AixwyttznSMQDgbR5Yed/Gg6S8Funrhc= github.com/lib/pq v1.4.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= -github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= -github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= -github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= -github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= @@ -66,45 +54,11 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= -golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= -golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= -golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= -golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= -golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE= -golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -modernc.org/cc/v4 v4.29.1 h1:MKgdCV3WykTSPqpVrnxdEDS0HEd2FHpKZDzxzU5LyeI= -modernc.org/cc/v4 v4.29.1/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= -modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU= -modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk= -modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= -modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= -modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= -modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= -modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI= -modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= -modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= -modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= -modernc.org/libc v1.74.4 h1:fX1Omw4o2/1C2iRkkIsrQTasJQldLhRmuPreXLoWs9k= -modernc.org/libc v1.74.4/go.mod h1:eeQAS9W3sZeKYMFubydxJpII9ybHWshk+7or7bLG9co= -modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= -modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= -modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= -modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= -modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= -modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= -modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= -modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= -modernc.org/sqlite v1.57.0 h1:qNQP6xnx5M0ISNtlnxoOX0+cD5bJ0/gr9aMmndFczzg= -modernc.org/sqlite v1.57.0/go.mod h1:yCJ2cmAaIkHQ25oXWrF8H4O1lIfPYPR26yCEDj2P3pQ= -modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= -modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= -modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= -modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/internal/blob/spaces.go b/internal/blob/spaces.go index 69df506..4e0d8cd 100644 --- a/internal/blob/spaces.go +++ b/internal/blob/spaces.go @@ -21,12 +21,6 @@ type Uploader interface { // Disabled is a no-op uploader used when Spaces is not configured. type Disabled struct{} -func (Disabled) Enabled() bool { return false } - -func (Disabled) Upload(context.Context, string, io.Reader, string, int64) (string, error) { - return "", fmt.Errorf("avatar uploads are not configured") -} - // SpacesConfig holds DigitalOcean Spaces settings. type SpacesConfig struct { Key string @@ -37,6 +31,17 @@ type SpacesConfig struct { CDNBase string // optional public base URL without trailing slash } +type spaces struct { + client *s3.Client + cfg SpacesConfig +} + +func (Disabled) Enabled() bool { return false } + +func (Disabled) Upload(context.Context, string, io.Reader, string, int64) (string, error) { + return "", fmt.Errorf("avatar uploads are not configured") +} + // NewSpaces returns an Uploader when required env is present; otherwise Disabled. func NewSpaces(cfg SpacesConfig) Uploader { cfg.Key = strings.TrimSpace(cfg.Key) @@ -49,18 +54,13 @@ func NewSpaces(cfg SpacesConfig) Uploader { return Disabled{} } client := s3.New(s3.Options{ - Region: cfg.Region, - Credentials: credentials.NewStaticCredentialsProvider(cfg.Key, cfg.Secret, ""), + Region: cfg.Region, + Credentials: credentials.NewStaticCredentialsProvider(cfg.Key, cfg.Secret, ""), BaseEndpoint: aws.String(cfg.Endpoint), }) return &spaces{client: client, cfg: cfg} } -type spaces struct { - client *s3.Client - cfg SpacesConfig -} - func (s *spaces) Enabled() bool { return true } func (s *spaces) Upload(ctx context.Context, key string, body io.Reader, contentType string, size int64) (string, error) { diff --git a/internal/store/db.go b/internal/store/db.go index 00febb9..45514bc 100644 --- a/internal/store/db.go +++ b/internal/store/db.go @@ -8,15 +8,30 @@ import ( // ErrLastAdmin is returned when demoting the only remaining admin. var ErrLastAdmin = errors.New("cannot demote the last admin") +// Role is a user privilege level stored in users.role. +type Role string + +const ( + RoleUser Role = "user" + RoleAdmin Role = "admin" +) + +// NewUser is the input for CreateUser. +type NewUser struct { + Username string + PasswordHash string + Role Role +} + // DB is the persistence API used by the web layer. // Named DB to avoid colliding with scs.Store. type DB interface { - CreateUser(ctx context.Context, username, passwordHash string, asAdmin bool) (*User, error) + CreateUser(ctx context.Context, user NewUser) (*User, error) UserByID(ctx context.Context, id string) (*User, error) UserByUsername(ctx context.Context, username string) (*User, error) CountAdmins(ctx context.Context) (int, error) ListUsers(ctx context.Context) ([]User, error) - SetRole(ctx context.Context, userID, role string) error + SetRole(ctx context.Context, userID string, role Role) error CreateQuestion(ctx context.Context, authorID, title, body, city string) (*RankedQuestion, error) ListHunt(ctx context.Context, huntDate, viewerID string) ([]RankedQuestion, error) GetQuestion(ctx context.Context, id, viewerID string) (*RankedQuestion, error) diff --git a/internal/store/migrate.go b/internal/store/migrate.go index 0c247cb..bec080c 100644 --- a/internal/store/migrate.go +++ b/internal/store/migrate.go @@ -3,24 +3,14 @@ package store import ( "database/sql" "fmt" - "strings" ) -func migrateUserProfileColumns(db *sql.DB, dialect string) error { +// migrateUserProfileColumns adds avatar_url and state when missing (existing DBs). +func migrateUserProfileColumns(db *sql.DB) error { cols := []string{"avatar_url", "state"} for _, col := range cols { - var stmt string - switch dialect { - case dialectPostgres: - stmt = fmt.Sprintf(`ALTER TABLE users ADD COLUMN IF NOT EXISTS %s TEXT NOT NULL DEFAULT ''`, col) - default: - stmt = fmt.Sprintf(`ALTER TABLE users ADD COLUMN %s TEXT NOT NULL DEFAULT ''`, col) - } + stmt := fmt.Sprintf(`ALTER TABLE users ADD COLUMN IF NOT EXISTS %s TEXT NOT NULL DEFAULT ''`, col) if _, err := db.Exec(stmt); err != nil { - // SQLite errors when the column already exists. - if dialect == dialectSQLite && strings.Contains(strings.ToLower(err.Error()), "duplicate column") { - continue - } return fmt.Errorf("add column %s: %w", col, err) } } diff --git a/internal/store/postgres.go b/internal/store/postgres.go index 878e2d0..b9364ab 100644 --- a/internal/store/postgres.go +++ b/internal/store/postgres.go @@ -11,11 +11,7 @@ import ( _ "github.com/jackc/pgx/v5/stdlib" ) -const ( - dialectSQLite = "sqlite" - dialectPostgres = "postgres" -) - +// rebind converts ? placeholders to Postgres $1, $2, ... form. func rebind(query string) string { n := 0 var b strings.Builder @@ -31,13 +27,12 @@ func rebind(query string) string { return b.String() } +// q rebinds SQL placeholders for Postgres. func (s *Store) q(query string) string { - if s.dialect == dialectPostgres { - return rebind(query) - } - return query + return rebind(query) } +// applySchema runs semicolon-separated DDL statements, skipping PRAGMA lines. func applySchema(db *sql.DB, schema string) error { for _, stmt := range strings.Split(schema, ";") { stmt = strings.TrimSpace(stmt) @@ -55,6 +50,7 @@ func applySchema(db *sql.DB, schema string) error { return nil } +// postgresDSN normalizes DATABASE_URL for pgx (sslmode default, strip unsupported params). func postgresDSN(raw string) (string, error) { u, err := url.Parse(raw) if err != nil { @@ -77,16 +73,8 @@ func postgresDSN(raw string) (string, error) { return u.String(), nil } +// OpenPostgres connects to Postgres, applies schema/migrations, and starts session cleanup. func OpenPostgres(databaseURL, schema string) (*Store, error) { - return openPostgres(databaseURL, schema, 5*time.Minute) -} - -// OpenPostgresWithoutSessionCleanup opens Postgres without a session cleanup goroutine (for tests). -func OpenPostgresWithoutSessionCleanup(databaseURL, schema string) (*Store, error) { - return openPostgres(databaseURL, schema, 0) -} - -func openPostgres(databaseURL, schema string, sessionCleanup time.Duration) (*Store, error) { dsn, err := postgresDSN(databaseURL) if err != nil { return nil, err @@ -105,26 +93,15 @@ func openPostgres(databaseURL, schema string, sessionCleanup time.Duration) (*St _ = db.Close() return nil, fmt.Errorf("apply schema: %w", err) } - if err := applySessionsSchema(db, dialectPostgres); err != nil { + if err := applySessionsSchema(db); err != nil { _ = db.Close() return nil, fmt.Errorf("apply sessions schema: %w", err) } - if err := migrateUserProfileColumns(db, dialectPostgres); err != nil { + if err := migrateUserProfileColumns(db); err != nil { _ = db.Close() return nil, fmt.Errorf("migrate profile columns: %w", err) } - st := &Store{db: db, dialect: dialectPostgres} - st.initSessionStore(sessionCleanup) + st := &Store{db: db} + st.initSessionStore(5 * time.Minute) return st, nil } - -// Connect uses PlanetScale Postgres when DATABASE_URL is set, otherwise SQLite. -func Connect(databaseURL, sqlitePath, schema string) (*Store, error) { - if strings.TrimSpace(databaseURL) != "" { - return OpenPostgres(databaseURL, schema) - } - if sqlitePath == "" { - sqlitePath = "data.db" - } - return Open(sqlitePath, schema) -} diff --git a/internal/store/sessions.go b/internal/store/sessions.go index 1e4041f..33c507c 100644 --- a/internal/store/sessions.go +++ b/internal/store/sessions.go @@ -2,22 +2,12 @@ package store import ( "database/sql" - "log" "time" "github.com/alexedwards/scs/postgresstore" "github.com/alexedwards/scs/v2" ) -const sessionsSchemaSQLite = ` -CREATE TABLE IF NOT EXISTS sessions ( - token TEXT PRIMARY KEY, - data BLOB NOT NULL, - expiry REAL NOT NULL -); -CREATE INDEX IF NOT EXISTS sessions_expiry_idx ON sessions(expiry); -` - const sessionsSchemaPostgres = ` CREATE TABLE IF NOT EXISTS sessions ( token TEXT PRIMARY KEY, @@ -27,12 +17,9 @@ CREATE TABLE IF NOT EXISTS sessions ( CREATE INDEX IF NOT EXISTS sessions_expiry_idx ON sessions (expiry); ` -func applySessionsSchema(db *sql.DB, dialect string) error { - schema := sessionsSchemaSQLite - if dialect == dialectPostgres { - schema = sessionsSchemaPostgres - } - return applySchema(db, schema) +// applySessionsSchema creates the scs sessions table if missing. +func applySessionsSchema(db *sql.DB) error { + return applySchema(db, sessionsSchemaPostgres) } type sessionStopper interface { @@ -45,110 +32,7 @@ func (s *Store) SessionStore() scs.Store { } func (s *Store) initSessionStore(cleanupInterval time.Duration) { - switch s.dialect { - case dialectPostgres: - ps := postgresstore.NewWithCleanupInterval(s.db, cleanupInterval) - s.sessionStore = ps - s.sessionStopper = ps - default: - ss := newSQLiteSessionStore(s.db, cleanupInterval) - s.sessionStore = ss - s.sessionStopper = ss - } + ps := postgresstore.NewWithCleanupInterval(s.db, cleanupInterval) + s.sessionStore = ps + s.sessionStopper = ps } - -// sqliteSessionStore is a modernc-safe scs.Store (uses ? placeholders). -type sqliteSessionStore struct { - db *sql.DB - stopCleanup chan bool -} - -func newSQLiteSessionStore(db *sql.DB, cleanupInterval time.Duration) *sqliteSessionStore { - s := &sqliteSessionStore{db: db} - if cleanupInterval > 0 { - s.stopCleanup = make(chan bool) - go s.startCleanup(cleanupInterval) - } - return s -} - -func (s *sqliteSessionStore) Find(token string) ([]byte, bool, error) { - var b []byte - err := s.db.QueryRow( - `SELECT data FROM sessions WHERE token = ? AND julianday('now') < expiry`, - token, - ).Scan(&b) - if err == sql.ErrNoRows { - return nil, false, nil - } - if err != nil { - return nil, false, err - } - return b, true, nil -} - -func (s *sqliteSessionStore) Commit(token string, b []byte, expiry time.Time) error { - _, err := s.db.Exec( - `REPLACE INTO sessions (token, data, expiry) VALUES (?, ?, julianday(?))`, - token, - b, - expiry.UTC().Format("2006-01-02T15:04:05.999"), - ) - return err -} - -func (s *sqliteSessionStore) Delete(token string) error { - _, err := s.db.Exec(`DELETE FROM sessions WHERE token = ?`, token) - return err -} - -func (s *sqliteSessionStore) All() (map[string][]byte, error) { - rows, err := s.db.Query(`SELECT token, data FROM sessions WHERE julianday('now') < expiry`) - if err != nil { - return nil, err - } - defer rows.Close() - out := make(map[string][]byte) - for rows.Next() { - var token string - var data []byte - if err := rows.Scan(&token, &data); err != nil { - return nil, err - } - out[token] = data - } - return out, rows.Err() -} - -func (s *sqliteSessionStore) startCleanup(interval time.Duration) { - ticker := time.NewTicker(interval) - for { - select { - case <-ticker.C: - if err := s.deleteExpired(); err != nil { - log.Println(err) - } - case <-s.stopCleanup: - ticker.Stop() - return - } - } -} - -func (s *sqliteSessionStore) StopCleanup() { - if s.stopCleanup != nil { - s.stopCleanup <- true - } -} - -func (s *sqliteSessionStore) deleteExpired() error { - _, err := s.db.Exec(`DELETE FROM sessions WHERE expiry < julianday('now')`) - return err -} - -// Ensure interface compliance. -var ( - _ scs.Store = (*sqliteSessionStore)(nil) - _ scs.IterableStore = (*sqliteSessionStore)(nil) - _ sessionStopper = (*sqliteSessionStore)(nil) -) diff --git a/internal/store/store.go b/internal/store/store.go index 778dfc8..ccfe95a 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -9,14 +9,12 @@ import ( "github.com/alexedwards/scs/v2" "github.com/google/uuid" - _ "modernc.org/sqlite" "plumber/internal/pacific" ) type Store struct { db *sql.DB - dialect string sessionStore scs.Store sessionStopper sessionStopper } @@ -25,7 +23,7 @@ type User struct { ID string Username string Name string - Role string + Role Role AvatarURL string State string CreatedAt string @@ -33,7 +31,7 @@ type User struct { } func (u *User) Admin() bool { - return u != nil && u.Role == "admin" + return u != nil && u.Role == RoleAdmin } type RankedQuestion struct { @@ -60,42 +58,6 @@ type Answer struct { UpdatedAt string } -func Open(path, schema string) (*Store, error) { - return openSQLite(path, schema, 5*time.Minute) -} - -// OpenWithoutSessionCleanup opens SQLite without a session cleanup goroutine (for tests). -func OpenWithoutSessionCleanup(path, schema string) (*Store, error) { - return openSQLite(path, schema, 0) -} - -func openSQLite(path, schema string, sessionCleanup time.Duration) (*Store, error) { - dsn := path - if !strings.Contains(dsn, "?") { - dsn += "?_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)" - } - db, err := sql.Open("sqlite", dsn) - if err != nil { - return nil, err - } - db.SetMaxOpenConns(1) - if _, err := db.Exec(schema); err != nil { - _ = db.Close() - return nil, fmt.Errorf("apply schema: %w", err) - } - if err := applySessionsSchema(db, dialectSQLite); err != nil { - _ = db.Close() - return nil, fmt.Errorf("apply sessions schema: %w", err) - } - if err := migrateUserProfileColumns(db, dialectSQLite); err != nil { - _ = db.Close() - return nil, fmt.Errorf("migrate profile columns: %w", err) - } - st := &Store{db: db, dialect: dialectSQLite} - st.initSessionStore(sessionCleanup) - return st, nil -} - func (s *Store) Close() error { if s.sessionStopper != nil { s.sessionStopper.StopCleanup() @@ -104,22 +66,21 @@ func (s *Store) Close() error { return s.db.Close() } -func (s *Store) CreateUser(ctx context.Context, username, passwordHash string, asAdmin bool) (*User, error) { - username = NormalizeUsername(username) - role := "user" - if asAdmin { - role = "admin" +func (s *Store) CreateUser(ctx context.Context, nu NewUser) (*User, error) { + if nu.Role != RoleUser && nu.Role != RoleAdmin { + return nil, fmt.Errorf("invalid role") } + username := NormalizeUsername(nu.Username) u := &User{ ID: uuid.NewString(), Username: username, Name: username, - Role: role, - PasswordHash: passwordHash, + Role: nu.Role, + PasswordHash: nu.PasswordHash, CreatedAt: time.Now().UTC().Format(time.RFC3339), } _, err := s.db.ExecContext(ctx, s.q(`INSERT INTO users (id, username, name, password_hash, role, avatar_url, state, created_at) VALUES (?, ?, ?, ?, ?, '', '', ?)`), - u.ID, u.Username, u.Name, u.PasswordHash, u.Role, u.CreatedAt) + u.ID, u.Username, u.Name, u.PasswordHash, string(u.Role), u.CreatedAt) if err != nil { return nil, err } @@ -128,7 +89,7 @@ func (s *Store) CreateUser(ctx context.Context, username, passwordHash string, a func (s *Store) CountAdmins(ctx context.Context) (int, error) { var n int - err := s.db.QueryRowContext(ctx, s.q(`SELECT COUNT(*) FROM users WHERE role = ?`), "admin").Scan(&n) + err := s.db.QueryRowContext(ctx, s.q(`SELECT COUNT(*) FROM users WHERE role = ?`), string(RoleAdmin)).Scan(&n) return n, err } @@ -141,16 +102,18 @@ func (s *Store) ListUsers(ctx context.Context) ([]User, error) { var out []User for rows.Next() { var u User - if err := rows.Scan(&u.ID, &u.Username, &u.Name, &u.Role, &u.AvatarURL, &u.State, &u.CreatedAt); err != nil { + var role string + if err := rows.Scan(&u.ID, &u.Username, &u.Name, &role, &u.AvatarURL, &u.State, &u.CreatedAt); err != nil { return nil, err } + u.Role = Role(role) out = append(out, u) } return out, rows.Err() } -func (s *Store) SetRole(ctx context.Context, userID, role string) error { - if role != "user" && role != "admin" { +func (s *Store) SetRole(ctx context.Context, userID string, role Role) error { + if role != RoleUser && role != RoleAdmin { return fmt.Errorf("invalid role") } tx, err := s.db.BeginTx(ctx, nil) @@ -164,16 +127,16 @@ func (s *Store) SetRole(ctx context.Context, userID, role string) error { if err != nil { return err } - if current == "admin" && role == "user" { + if Role(current) == RoleAdmin && role == RoleUser { var n int - if err := tx.QueryRowContext(ctx, s.q(`SELECT COUNT(*) FROM users WHERE role = ?`), "admin").Scan(&n); err != nil { + if err := tx.QueryRowContext(ctx, s.q(`SELECT COUNT(*) FROM users WHERE role = ?`), string(RoleAdmin)).Scan(&n); err != nil { return err } if n <= 1 { return ErrLastAdmin } } - res, err := tx.ExecContext(ctx, s.q(`UPDATE users SET role = ? WHERE id = ?`), role, userID) + res, err := tx.ExecContext(ctx, s.q(`UPDATE users SET role = ? WHERE id = ?`), string(role), userID) if err != nil { return err } @@ -197,15 +160,17 @@ func (s *Store) UserByUsername(ctx context.Context, username string) (*User, err func scanUser(row *sql.Row, withSecrets bool) (*User, error) { var u User + var role string var err error if withSecrets { - err = row.Scan(&u.ID, &u.Username, &u.Name, &u.Role, &u.AvatarURL, &u.State, &u.CreatedAt, &u.PasswordHash) + err = row.Scan(&u.ID, &u.Username, &u.Name, &role, &u.AvatarURL, &u.State, &u.CreatedAt, &u.PasswordHash) } else { - err = row.Scan(&u.ID, &u.Username, &u.Name, &u.Role, &u.AvatarURL, &u.State, &u.CreatedAt) + err = row.Scan(&u.ID, &u.Username, &u.Name, &role, &u.AvatarURL, &u.State, &u.CreatedAt) } if err != nil { return nil, err } + u.Role = Role(role) return &u, nil } diff --git a/internal/web/admin.go b/internal/web/admin.go index 2e955d3..e7e9e70 100644 --- a/internal/web/admin.go +++ b/internal/web/admin.go @@ -47,7 +47,7 @@ func (s *Server) handleAdminSetRole(w http.ResponseWriter, r *http.Request) { return } id := chi.URLParam(r, "id") - role := r.PostFormValue("role") + role := store.Role(r.PostFormValue("role")) err := s.store.SetRole(r.Context(), id, role) if errors.Is(err, store.ErrLastAdmin) { users, listErr := s.store.ListUsers(r.Context()) diff --git a/internal/web/auth.go b/internal/web/auth.go index 4bfcb00..65cc384 100644 --- a/internal/web/auth.go +++ b/internal/web/auth.go @@ -88,16 +88,22 @@ func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) { http.Error(w, "could not save password", http.StatusInternalServerError) return } - asAdmin := false + role := store.RoleUser if s.cfg.AdminUsername != "" && store.NormalizeUsername(username) == store.NormalizeUsername(s.cfg.AdminUsername) { n, err := s.store.CountAdmins(r.Context()) if err != nil { http.Error(w, "could not create account", http.StatusInternalServerError) return } - asAdmin = n == 0 + if n == 0 { + role = store.RoleAdmin + } } - u, err := s.store.CreateUser(r.Context(), username, string(hash), asAdmin) + u, err := s.store.CreateUser(r.Context(), store.NewUser{ + Username: username, + PasswordHash: string(hash), + Role: role, + }) if err != nil { p.Error = "That username is taken." s.exec(w, "register", p) diff --git a/internal/web/memstore_test.go b/internal/web/memstore_test.go index 0eb62d4..8476ce5 100644 --- a/internal/web/memstore_test.go +++ b/internal/web/memstore_test.go @@ -18,11 +18,11 @@ import ( // memDB is an in-memory store.DB for tests. type memDB struct { mu sync.Mutex - users map[string]*store.User // id -> user - byName map[string]string // username -> id - questions map[string]*store.RankedQuestion // id -> question - votes map[string]int // userID|questionID -> value - answers map[string]*store.Answer // questionID -> answer + users map[string]*store.User // id -> user + byName map[string]string // username -> id + questions map[string]*store.RankedQuestion // id -> question + votes map[string]int // userID|questionID -> value + answers map[string]*store.Answer // questionID -> answer } func newMemDB() *memDB { @@ -39,23 +39,22 @@ func voteKey(userID, questionID string) string { return userID + "|" + questionID } -func (m *memDB) CreateUser(_ context.Context, username, passwordHash string, asAdmin bool) (*store.User, error) { +func (m *memDB) CreateUser(_ context.Context, nu store.NewUser) (*store.User, error) { m.mu.Lock() defer m.mu.Unlock() - username = store.NormalizeUsername(username) + username := store.NormalizeUsername(nu.Username) if _, ok := m.byName[username]; ok { return nil, fmt.Errorf("username taken") } - role := "user" - if asAdmin { - role = "admin" + if nu.Role != store.RoleUser && nu.Role != store.RoleAdmin { + return nil, fmt.Errorf("invalid role") } u := &store.User{ ID: uuid.NewString(), Username: username, Name: username, - Role: role, - PasswordHash: passwordHash, + Role: nu.Role, + PasswordHash: nu.PasswordHash, CreatedAt: time.Now().UTC().Format(time.RFC3339), } m.users[u.ID] = u @@ -92,7 +91,7 @@ func (m *memDB) CountAdmins(_ context.Context) (int, error) { defer m.mu.Unlock() n := 0 for _, u := range m.users { - if u.Role == "admin" { + if u.Role == store.RoleAdmin { n++ } } @@ -114,8 +113,8 @@ func (m *memDB) ListUsers(_ context.Context) ([]store.User, error) { return out, nil } -func (m *memDB) SetRole(_ context.Context, userID, role string) error { - if role != "user" && role != "admin" { +func (m *memDB) SetRole(_ context.Context, userID string, role store.Role) error { + if role != store.RoleUser && role != store.RoleAdmin { return fmt.Errorf("invalid role") } m.mu.Lock() @@ -124,10 +123,10 @@ func (m *memDB) SetRole(_ context.Context, userID, role string) error { if !ok { return sql.ErrNoRows } - if u.Role == "admin" && role == "user" { + if u.Role == store.RoleAdmin && role == store.RoleUser { n := 0 for _, x := range m.users { - if x.Role == "admin" { + if x.Role == store.RoleAdmin { n++ } } From 3eb75cfd805cfbff7c04d98d51f928e27cdf54ec Mon Sep 17 00:00:00 2001 From: codegirl-007 Date: Fri, 21 Aug 2026 23:43:01 -0700 Subject: [PATCH 03/17] Split main into openStore, newHandler, and run helpers. --- cmd/server/main.go | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/cmd/server/main.go b/cmd/server/main.go index b482bf9..a41407e 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -21,8 +21,18 @@ import ( func main() { _ = godotenv.Load() - listen := listenAddr() + st := openStore() + defer st.Close() + + uploader := spacesUploader() + logSpaces(uploader) + + handler := newHandler(st, uploader) + run(&http.Server{Addr: listenAddr(), Handler: handler}) +} + +func openStore() *store.Store { databaseURL := strings.TrimSpace(os.Getenv("DATABASE_URL")) if databaseURL == "" { log.Fatal("DATABASE_URL is required") @@ -31,16 +41,19 @@ func main() { if err != nil { log.Fatalf("database: %v", err) } - defer st.Close() log.Printf("database: postgres") + return st +} - uploader := spacesUploader() +func logSpaces(uploader blob.Uploader) { if uploader.Enabled() { log.Printf("avatars: digitalocean spaces") - } else { - log.Printf("avatars: uploads disabled (set SPACES_* to enable)") + return } + log.Printf("avatars: uploads disabled (set SPACES_* to enable)") +} +func newHandler(st *store.Store, uploader blob.Uploader) http.Handler { srv, err := web.New(st, st.SessionStore(), plumber.TemplateFS, plumber.StaticFS, web.Config{ AdminUsername: os.Getenv("ADMIN_USERNAME"), SecureCookie: os.Getenv("SECURE_COOKIE") == "1", @@ -49,11 +62,13 @@ func main() { if err != nil { log.Fatalf("server: %v", err) } + return srv.Handler() +} - httpSrv := &http.Server{Addr: listen, Handler: srv.Handler()} +func run(httpSrv *http.Server) { errCh := make(chan error, 1) go func() { - log.Printf("listening on %s", listen) + log.Printf("listening on %s", httpSrv.Addr) errCh <- httpSrv.ListenAndServe() }() From a36bc723cc3386f5695cf3661c1ef3363c223182 Mon Sep 17 00:00:00 2001 From: codegirl-007 Date: Fri, 21 Aug 2026 23:48:18 -0700 Subject: [PATCH 04/17] Move Spaces FromEnv into blob; Upload takes Object; drop logSpaces. --- cmd/server/main.go | 23 +---------------------- internal/blob/spaces.go | 37 +++++++++++++++++++++++++++++-------- internal/web/profile.go | 16 +++++++++++----- internal/web/server_test.go | 8 ++++---- 4 files changed, 45 insertions(+), 39 deletions(-) diff --git a/cmd/server/main.go b/cmd/server/main.go index a41407e..b09be88 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -25,9 +25,7 @@ func main() { st := openStore() defer st.Close() - uploader := spacesUploader() - logSpaces(uploader) - + uploader := blob.FromEnv() handler := newHandler(st, uploader) run(&http.Server{Addr: listenAddr(), Handler: handler}) } @@ -45,14 +43,6 @@ func openStore() *store.Store { return st } -func logSpaces(uploader blob.Uploader) { - if uploader.Enabled() { - log.Printf("avatars: digitalocean spaces") - return - } - log.Printf("avatars: uploads disabled (set SPACES_* to enable)") -} - func newHandler(st *store.Store, uploader blob.Uploader) http.Handler { srv, err := web.New(st, st.SessionStore(), plumber.TemplateFS, plumber.StaticFS, web.Config{ AdminUsername: os.Getenv("ADMIN_USERNAME"), @@ -93,17 +83,6 @@ func run(httpSrv *http.Server) { } } -func spacesUploader() blob.Uploader { - return blob.NewSpaces(blob.SpacesConfig{ - Key: os.Getenv("SPACES_KEY"), - Secret: os.Getenv("SPACES_SECRET"), - Region: os.Getenv("SPACES_REGION"), - Bucket: os.Getenv("SPACES_BUCKET"), - Endpoint: os.Getenv("SPACES_ENDPOINT"), - CDNBase: os.Getenv("SPACES_CDN_BASE"), - }) -} - // listenAddr prefers PORT (App Platform / PaaS), then LISTEN, then :8080. func listenAddr() string { if p := strings.TrimSpace(os.Getenv("PORT")); p != "" { diff --git a/internal/blob/spaces.go b/internal/blob/spaces.go index 4e0d8cd..979e7d9 100644 --- a/internal/blob/spaces.go +++ b/internal/blob/spaces.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "io" + "os" "strings" "github.com/aws/aws-sdk-go-v2/aws" @@ -15,7 +16,15 @@ import ( // Uploader stores public avatar objects. type Uploader interface { Enabled() bool - Upload(ctx context.Context, key string, body io.Reader, contentType string, size int64) (publicURL string, err error) + Upload(ctx context.Context, obj Object) (publicURL string, err error) +} + +// Object is a file to upload to object storage. +type Object struct { + Key string + Body io.Reader + ContentType string + Size int64 } // Disabled is a no-op uploader used when Spaces is not configured. @@ -38,10 +47,22 @@ type spaces struct { func (Disabled) Enabled() bool { return false } -func (Disabled) Upload(context.Context, string, io.Reader, string, int64) (string, error) { +func (Disabled) Upload(context.Context, Object) (string, error) { return "", fmt.Errorf("avatar uploads are not configured") } +// FromEnv builds an Uploader from SPACES_* environment variables. +func FromEnv() Uploader { + return NewSpaces(SpacesConfig{ + Key: os.Getenv("SPACES_KEY"), + Secret: os.Getenv("SPACES_SECRET"), + Region: os.Getenv("SPACES_REGION"), + Bucket: os.Getenv("SPACES_BUCKET"), + Endpoint: os.Getenv("SPACES_ENDPOINT"), + CDNBase: os.Getenv("SPACES_CDN_BASE"), + }) +} + // NewSpaces returns an Uploader when required env is present; otherwise Disabled. func NewSpaces(cfg SpacesConfig) Uploader { cfg.Key = strings.TrimSpace(cfg.Key) @@ -63,17 +84,17 @@ func NewSpaces(cfg SpacesConfig) Uploader { func (s *spaces) Enabled() bool { return true } -func (s *spaces) Upload(ctx context.Context, key string, body io.Reader, contentType string, size int64) (string, error) { - key = strings.TrimPrefix(key, "/") +func (s *spaces) Upload(ctx context.Context, obj Object) (string, error) { + key := strings.TrimPrefix(obj.Key, "/") input := &s3.PutObjectInput{ Bucket: aws.String(s.cfg.Bucket), Key: aws.String(key), - Body: body, - ContentType: aws.String(contentType), + Body: obj.Body, + ContentType: aws.String(obj.ContentType), ACL: types.ObjectCannedACLPublicRead, } - if size > 0 { - input.ContentLength = aws.Int64(size) + if obj.Size > 0 { + input.ContentLength = aws.Int64(obj.Size) } if _, err := s.client.PutObject(ctx, input); err != nil { return "", err diff --git a/internal/web/profile.go b/internal/web/profile.go index 1c214ec..c603885 100644 --- a/internal/web/profile.go +++ b/internal/web/profile.go @@ -8,18 +8,19 @@ import ( "github.com/google/uuid" + "plumber/internal/blob" "plumber/internal/geo" "plumber/internal/store" ) type profilePage struct { page - States []struct{ Code, Name string } - Questions []store.RankedQuestion + States []struct{ Code, Name string } + Questions []store.RankedQuestion QuestionsLabel string UploadsEnabled bool - Error string - StateVal string + Error string + StateVal string } func (s *Server) handleProfileForm(w http.ResponseWriter, r *http.Request) { @@ -74,7 +75,12 @@ func (s *Server) handleProfile(w http.ResponseWriter, r *http.Request) { } key := path.Join("avatars", u.ID, uuid.NewString()+ext) limited := io.LimitReader(file, (2<<20)+1) - url, upErr := s.cfg.Blob.Upload(r.Context(), key, limited, contentType, hdr.Size) + url, upErr := s.cfg.Blob.Upload(r.Context(), blob.Object{ + Key: key, + Body: limited, + ContentType: contentType, + Size: hdr.Size, + }) if upErr != nil { s.renderProfile(w, r, u, "Could not upload avatar. Try again later.", state) return diff --git a/internal/web/server_test.go b/internal/web/server_test.go index aa6f849..57a1aed 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -3,7 +3,6 @@ package web import ( "bytes" "context" - "io" "mime/multipart" "net/http" "net/http/httptest" @@ -13,6 +12,7 @@ import ( "github.com/alexedwards/scs/v2" "plumber" + "plumber/internal/blob" ) func newTestServer(t *testing.T) (*Server, *memDB, scs.Store) { @@ -296,10 +296,10 @@ type fakeBlob struct { func (f *fakeBlob) Enabled() bool { return true } -func (f *fakeBlob) Upload(_ context.Context, key string, _ io.Reader, _ string, _ int64) (string, error) { +func (f *fakeBlob) Upload(_ context.Context, obj blob.Object) (string, error) { f.calls++ - f.last = key - return "https://cdn.example.com/" + key, nil + f.last = obj.Key + return "https://cdn.example.com/" + obj.Key, nil } func TestProfilePageAndState(t *testing.T) { From a249965fc13342da47eb44ada8d898cf1e003719 Mon Sep 17 00:00:00 2001 From: codegirl-007 Date: Fri, 21 Aug 2026 23:53:00 -0700 Subject: [PATCH 05/17] Rename Object to FileUpload; use native Postgres $n placeholders. --- internal/blob/spaces.go | 10 ++--- internal/store/postgres.go | 22 ----------- internal/store/postgres_test.go | 8 ---- internal/store/store.go | 68 ++++++++++++++++----------------- internal/web/profile.go | 2 +- internal/web/server_test.go | 2 +- 6 files changed, 41 insertions(+), 71 deletions(-) diff --git a/internal/blob/spaces.go b/internal/blob/spaces.go index 979e7d9..1a69d36 100644 --- a/internal/blob/spaces.go +++ b/internal/blob/spaces.go @@ -16,11 +16,11 @@ import ( // Uploader stores public avatar objects. type Uploader interface { Enabled() bool - Upload(ctx context.Context, obj Object) (publicURL string, err error) + Upload(ctx context.Context, obj FileUpload) (publicURL string, err error) } -// Object is a file to upload to object storage. -type Object struct { +// FileUpload is a file body to store (e.g. an avatar). +type FileUpload struct { Key string Body io.Reader ContentType string @@ -47,7 +47,7 @@ type spaces struct { func (Disabled) Enabled() bool { return false } -func (Disabled) Upload(context.Context, Object) (string, error) { +func (Disabled) Upload(context.Context, FileUpload) (string, error) { return "", fmt.Errorf("avatar uploads are not configured") } @@ -84,7 +84,7 @@ func NewSpaces(cfg SpacesConfig) Uploader { func (s *spaces) Enabled() bool { return true } -func (s *spaces) Upload(ctx context.Context, obj Object) (string, error) { +func (s *spaces) Upload(ctx context.Context, obj FileUpload) (string, error) { key := strings.TrimPrefix(obj.Key, "/") input := &s3.PutObjectInput{ Bucket: aws.String(s.cfg.Bucket), diff --git a/internal/store/postgres.go b/internal/store/postgres.go index b9364ab..bd14f7d 100644 --- a/internal/store/postgres.go +++ b/internal/store/postgres.go @@ -4,34 +4,12 @@ import ( "database/sql" "fmt" "net/url" - "strconv" "strings" "time" _ "github.com/jackc/pgx/v5/stdlib" ) -// rebind converts ? placeholders to Postgres $1, $2, ... form. -func rebind(query string) string { - n := 0 - var b strings.Builder - for i := 0; i < len(query); i++ { - if query[i] == '?' { - n++ - b.WriteByte('$') - b.WriteString(strconv.Itoa(n)) - continue - } - b.WriteByte(query[i]) - } - return b.String() -} - -// q rebinds SQL placeholders for Postgres. -func (s *Store) q(query string) string { - return rebind(query) -} - // applySchema runs semicolon-separated DDL statements, skipping PRAGMA lines. func applySchema(db *sql.DB, schema string) error { for _, stmt := range strings.Split(schema, ";") { diff --git a/internal/store/postgres_test.go b/internal/store/postgres_test.go index f297d14..c854834 100644 --- a/internal/store/postgres_test.go +++ b/internal/store/postgres_test.go @@ -2,14 +2,6 @@ package store import "testing" -func TestRebindPostgresPlaceholders(t *testing.T) { - got := rebind(`SELECT a FROM t WHERE x = ? AND y = ?`) - want := `SELECT a FROM t WHERE x = $1 AND y = $2` - if got != want { - t.Fatalf("got %q", got) - } -} - func TestNormalizeUsername(t *testing.T) { if got := NormalizeUsername(" Alice_1 "); got != "alice_1" { t.Fatalf("got %q", got) diff --git a/internal/store/store.go b/internal/store/store.go index ccfe95a..9c93af8 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -79,7 +79,7 @@ func (s *Store) CreateUser(ctx context.Context, nu NewUser) (*User, error) { PasswordHash: nu.PasswordHash, CreatedAt: time.Now().UTC().Format(time.RFC3339), } - _, err := s.db.ExecContext(ctx, s.q(`INSERT INTO users (id, username, name, password_hash, role, avatar_url, state, created_at) VALUES (?, ?, ?, ?, ?, '', '', ?)`), + _, err := s.db.ExecContext(ctx, `INSERT INTO users (id, username, name, password_hash, role, avatar_url, state, created_at) VALUES ($1, $2, $3, $4, $5, '', '', $6)`, u.ID, u.Username, u.Name, u.PasswordHash, string(u.Role), u.CreatedAt) if err != nil { return nil, err @@ -89,12 +89,12 @@ func (s *Store) CreateUser(ctx context.Context, nu NewUser) (*User, error) { func (s *Store) CountAdmins(ctx context.Context) (int, error) { var n int - err := s.db.QueryRowContext(ctx, s.q(`SELECT COUNT(*) FROM users WHERE role = ?`), string(RoleAdmin)).Scan(&n) + err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users WHERE role = $1`, string(RoleAdmin)).Scan(&n) return n, err } func (s *Store) ListUsers(ctx context.Context) ([]User, error) { - rows, err := s.db.QueryContext(ctx, s.q(`SELECT id, username, name, role, avatar_url, state, created_at FROM users ORDER BY created_at ASC`)) + rows, err := s.db.QueryContext(ctx, `SELECT id, username, name, role, avatar_url, state, created_at FROM users ORDER BY created_at ASC`) if err != nil { return nil, err } @@ -123,20 +123,20 @@ func (s *Store) SetRole(ctx context.Context, userID string, role Role) error { defer tx.Rollback() var current string - err = tx.QueryRowContext(ctx, s.q(`SELECT role FROM users WHERE id = ?`), userID).Scan(¤t) + err = tx.QueryRowContext(ctx, `SELECT role FROM users WHERE id = $1`, userID).Scan(¤t) if err != nil { return err } if Role(current) == RoleAdmin && role == RoleUser { var n int - if err := tx.QueryRowContext(ctx, s.q(`SELECT COUNT(*) FROM users WHERE role = ?`), string(RoleAdmin)).Scan(&n); err != nil { + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM users WHERE role = $1`, string(RoleAdmin)).Scan(&n); err != nil { return err } if n <= 1 { return ErrLastAdmin } } - res, err := tx.ExecContext(ctx, s.q(`UPDATE users SET role = ? WHERE id = ?`), string(role), userID) + res, err := tx.ExecContext(ctx, `UPDATE users SET role = $1 WHERE id = $2`, string(role), userID) if err != nil { return err } @@ -151,11 +151,11 @@ func (s *Store) SetRole(ctx context.Context, userID string, role Role) error { } func (s *Store) UserByID(ctx context.Context, id string) (*User, error) { - return scanUser(s.db.QueryRowContext(ctx, s.q(`SELECT id, username, name, role, avatar_url, state, created_at FROM users WHERE id = ?`), id), false) + return scanUser(s.db.QueryRowContext(ctx, `SELECT id, username, name, role, avatar_url, state, created_at FROM users WHERE id = $1`, id), false) } func (s *Store) UserByUsername(ctx context.Context, username string) (*User, error) { - return scanUser(s.db.QueryRowContext(ctx, s.q(`SELECT id, username, name, role, avatar_url, state, created_at, password_hash FROM users WHERE username = ?`), NormalizeUsername(username)), true) + return scanUser(s.db.QueryRowContext(ctx, `SELECT id, username, name, role, avatar_url, state, created_at, password_hash FROM users WHERE username = $1`, NormalizeUsername(username)), true) } func scanUser(row *sql.Row, withSecrets bool) (*User, error) { @@ -188,7 +188,7 @@ func (s *Store) CreateQuestion(ctx context.Context, authorID, title, body, city HuntDate: pacific.Today(), CreatedAt: time.Now().UTC().Format(time.RFC3339), } - _, err := s.db.ExecContext(ctx, s.q(`INSERT INTO questions (id, author_id, title, body, city, hunt_date, hidden, created_at) VALUES (?, ?, ?, ?, ?, ?, 0, ?)`), + _, err := s.db.ExecContext(ctx, `INSERT INTO questions (id, author_id, title, body, city, hunt_date, hidden, created_at) VALUES ($1, $2, $3, $4, $5, $6, 0, $7)`, q.ID, q.AuthorID, q.Title, q.Body, q.City, q.HuntDate, q.CreatedAt) if err != nil { return nil, err @@ -197,18 +197,18 @@ func (s *Store) CreateQuestion(ctx context.Context, authorID, title, body, city } func (s *Store) ListHunt(ctx context.Context, huntDate, viewerID string) ([]RankedQuestion, error) { - rows, err := s.db.QueryContext(ctx, s.q(` + rows, err := s.db.QueryContext(ctx, ` SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, COALESCE(SUM(v.value), 0) AS score, CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END AS answered, - COALESCE((SELECT value FROM votes WHERE user_id = ? AND question_id = q.id), 0) AS user_vote + COALESCE((SELECT value FROM votes WHERE user_id = $1 AND question_id = q.id), 0) AS user_vote FROM questions q JOIN users u ON u.id = q.author_id LEFT JOIN votes v ON v.question_id = q.id LEFT JOIN answers a ON a.question_id = q.id -WHERE q.hunt_date = ? AND q.hidden = 0 +WHERE q.hunt_date = $2 AND q.hidden = 0 GROUP BY q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, a.question_id -ORDER BY score DESC, q.created_at ASC`), viewerID, huntDate) +ORDER BY score DESC, q.created_at ASC`, viewerID, huntDate) if err != nil { return nil, err } @@ -225,15 +225,15 @@ ORDER BY score DESC, q.created_at ASC`), viewerID, huntDate) } func (s *Store) GetQuestion(ctx context.Context, id, viewerID string) (*RankedQuestion, error) { - row := s.db.QueryRowContext(ctx, s.q(` + row := s.db.QueryRowContext(ctx, ` SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, COALESCE((SELECT SUM(value) FROM votes WHERE question_id = q.id), 0) AS score, CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END AS answered, - COALESCE((SELECT value FROM votes WHERE user_id = ? AND question_id = q.id), 0) AS user_vote + COALESCE((SELECT value FROM votes WHERE user_id = $1 AND question_id = q.id), 0) AS user_vote FROM questions q JOIN users u ON u.id = q.author_id LEFT JOIN answers a ON a.question_id = q.id -WHERE q.id = ?`), viewerID, id) +WHERE q.id = $2`, viewerID, id) q, err := scanRankedRow(row) if err != nil { return nil, err @@ -268,15 +268,15 @@ func (s *Store) Vote(ctx context.Context, userID, questionID string, value int) } defer tx.Rollback() var current sql.NullInt64 - err = tx.QueryRowContext(ctx, s.q(`SELECT value FROM votes WHERE user_id = ? AND question_id = ?`), userID, questionID).Scan(¤t) + err = tx.QueryRowContext(ctx, `SELECT value FROM votes WHERE user_id = $1 AND question_id = $2`, userID, questionID).Scan(¤t) if err != nil && err != sql.ErrNoRows { return err } if err == nil && current.Valid && int(current.Int64) == value { - _, err = tx.ExecContext(ctx, s.q(`DELETE FROM votes WHERE user_id = ? AND question_id = ?`), userID, questionID) + _, err = tx.ExecContext(ctx, `DELETE FROM votes WHERE user_id = $1 AND question_id = $2`, userID, questionID) } else { - _, err = tx.ExecContext(ctx, s.q(`INSERT INTO votes (user_id, question_id, value) VALUES (?, ?, ?) -ON CONFLICT (user_id, question_id) DO UPDATE SET value = excluded.value`), userID, questionID, value) + _, err = tx.ExecContext(ctx, `INSERT INTO votes (user_id, question_id, value) VALUES ($1, $2, $3) +ON CONFLICT (user_id, question_id) DO UPDATE SET value = excluded.value`, userID, questionID, value) } if err != nil { return err @@ -286,11 +286,11 @@ ON CONFLICT (user_id, question_id) DO UPDATE SET value = excluded.value`), userI func (s *Store) GetAnswer(ctx context.Context, questionID string) (*Answer, error) { var a Answer - err := s.db.QueryRowContext(ctx, s.q(` + err := s.db.QueryRowContext(ctx, ` SELECT a.question_id, a.author_id, u.name, a.body, a.created_at, a.updated_at FROM answers a JOIN users u ON u.id = a.author_id -WHERE a.question_id = ?`), questionID).Scan(&a.QuestionID, &a.AuthorID, &a.AuthorName, &a.Body, &a.CreatedAt, &a.UpdatedAt) +WHERE a.question_id = $1`, questionID).Scan(&a.QuestionID, &a.AuthorID, &a.AuthorName, &a.Body, &a.CreatedAt, &a.UpdatedAt) if err != nil { return nil, err } @@ -300,30 +300,30 @@ WHERE a.question_id = ?`), questionID).Scan(&a.QuestionID, &a.AuthorID, &a.Autho func (s *Store) UpsertAnswer(ctx context.Context, questionID, authorID, body string) error { body = strings.TrimSpace(body) now := time.Now().UTC().Format(time.RFC3339) - _, err := s.db.ExecContext(ctx, s.q(` -INSERT INTO answers (question_id, author_id, body, created_at, updated_at) VALUES (?, ?, ?, ?, ?) -ON CONFLICT (question_id) DO UPDATE SET body = excluded.body, author_id = excluded.author_id, updated_at = excluded.updated_at`), + _, err := s.db.ExecContext(ctx, ` +INSERT INTO answers (question_id, author_id, body, created_at, updated_at) VALUES ($1, $2, $3, $4, $5) +ON CONFLICT (question_id) DO UPDATE SET body = excluded.body, author_id = excluded.author_id, updated_at = excluded.updated_at`, questionID, authorID, body, now, now) return err } func (s *Store) HideQuestion(ctx context.Context, id string) error { - _, err := s.db.ExecContext(ctx, s.q(`UPDATE questions SET hidden = 1 WHERE id = ?`), id) + _, err := s.db.ExecContext(ctx, `UPDATE questions SET hidden = 1 WHERE id = $1`, id) return err } func (s *Store) UpdateProfile(ctx context.Context, userID, state, avatarURL string) error { state = strings.TrimSpace(state) if avatarURL == "" { - _, err := s.db.ExecContext(ctx, s.q(`UPDATE users SET state = ? WHERE id = ?`), state, userID) + _, err := s.db.ExecContext(ctx, `UPDATE users SET state = $1 WHERE id = $2`, state, userID) return err } - _, err := s.db.ExecContext(ctx, s.q(`UPDATE users SET state = ?, avatar_url = ? WHERE id = ?`), state, avatarURL, userID) + _, err := s.db.ExecContext(ctx, `UPDATE users SET state = $1, avatar_url = $2 WHERE id = $3`, state, avatarURL, userID) return err } func (s *Store) ListQuestionsByAuthor(ctx context.Context, authorID string) ([]RankedQuestion, error) { - rows, err := s.db.QueryContext(ctx, s.q(` + rows, err := s.db.QueryContext(ctx, ` SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, COALESCE((SELECT SUM(value) FROM votes WHERE question_id = q.id), 0) AS score, CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END AS answered, @@ -331,8 +331,8 @@ SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden FROM questions q JOIN users u ON u.id = q.author_id LEFT JOIN answers a ON a.question_id = q.id -WHERE q.author_id = ? AND q.hidden = 0 -ORDER BY q.created_at DESC`), authorID) +WHERE q.author_id = $1 AND q.hidden = 0 +ORDER BY q.created_at DESC`, authorID) if err != nil { return nil, err } @@ -341,7 +341,7 @@ ORDER BY q.created_at DESC`), authorID) } func (s *Store) ListQuestionsAnsweredBy(ctx context.Context, adminID string) ([]RankedQuestion, error) { - rows, err := s.db.QueryContext(ctx, s.q(` + rows, err := s.db.QueryContext(ctx, ` SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, COALESCE((SELECT SUM(value) FROM votes WHERE question_id = q.id), 0) AS score, 1 AS answered, @@ -349,8 +349,8 @@ SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden FROM answers ans JOIN questions q ON q.id = ans.question_id JOIN users u ON u.id = q.author_id -WHERE ans.author_id = ? AND q.hidden = 0 -ORDER BY ans.updated_at DESC`), adminID) +WHERE ans.author_id = $1 AND q.hidden = 0 +ORDER BY ans.updated_at DESC`, adminID) if err != nil { return nil, err } diff --git a/internal/web/profile.go b/internal/web/profile.go index c603885..0ec071d 100644 --- a/internal/web/profile.go +++ b/internal/web/profile.go @@ -75,7 +75,7 @@ func (s *Server) handleProfile(w http.ResponseWriter, r *http.Request) { } key := path.Join("avatars", u.ID, uuid.NewString()+ext) limited := io.LimitReader(file, (2<<20)+1) - url, upErr := s.cfg.Blob.Upload(r.Context(), blob.Object{ + url, upErr := s.cfg.Blob.Upload(r.Context(), blob.FileUpload{ Key: key, Body: limited, ContentType: contentType, diff --git a/internal/web/server_test.go b/internal/web/server_test.go index 57a1aed..130157c 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -296,7 +296,7 @@ type fakeBlob struct { func (f *fakeBlob) Enabled() bool { return true } -func (f *fakeBlob) Upload(_ context.Context, obj blob.Object) (string, error) { +func (f *fakeBlob) Upload(_ context.Context, obj blob.FileUpload) (string, error) { f.calls++ f.last = obj.Key return "https://cdn.example.com/" + obj.Key, nil From f31f352838a5c2ee7ce5013de182457bd46f6b5b Mon Sep 17 00:00:00 2001 From: codegirl-007 Date: Fri, 21 Aug 2026 23:55:09 -0700 Subject: [PATCH 06/17] Remove remaining SQLite-only schema and docs residue. --- .gitignore | 4 ---- internal/store/postgres.go | 6 +----- schema.sql | 2 -- todo.md | 9 ++++----- 4 files changed, 5 insertions(+), 16 deletions(-) diff --git a/.gitignore b/.gitignore index 3f6b01e..29d4243 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,3 @@ -/data.db -/data.db-* -/.test.db -/.test.db-* /bin/ /tmp/ .env diff --git a/internal/store/postgres.go b/internal/store/postgres.go index bd14f7d..44b1069 100644 --- a/internal/store/postgres.go +++ b/internal/store/postgres.go @@ -10,17 +10,13 @@ import ( _ "github.com/jackc/pgx/v5/stdlib" ) -// applySchema runs semicolon-separated DDL statements, skipping PRAGMA lines. +// applySchema runs semicolon-separated DDL statements. func applySchema(db *sql.DB, schema string) error { for _, stmt := range strings.Split(schema, ";") { stmt = strings.TrimSpace(stmt) if stmt == "" { continue } - upper := strings.ToUpper(stmt) - if strings.HasPrefix(upper, "PRAGMA") { - continue - } if _, err := db.Exec(stmt); err != nil { return fmt.Errorf("%w: %s", err, stmt) } diff --git a/schema.sql b/schema.sql index 29bd809..e3a8e89 100644 --- a/schema.sql +++ b/schema.sql @@ -1,5 +1,3 @@ -PRAGMA foreign_keys = ON; - CREATE TABLE IF NOT EXISTS users ( id TEXT PRIMARY KEY, username TEXT NOT NULL UNIQUE, diff --git a/todo.md b/todo.md index b4d0601..5cac465 100644 --- a/todo.md +++ b/todo.md @@ -4,24 +4,23 @@ From the project review. Priority order within each section. ## Fix soon -- [x] **Persist sessions** — Sessions live in the app DB (`sessions` table): SQLite locally, `postgresstore` when `DATABASE_URL` is set. Opaque cookie unchanged; unused `SESSION_SECRET` removed from config / `.env.example`. +- [x] **Persist sessions** — Sessions live in the app DB (`sessions` table) via `postgresstore`. Opaque cookie unchanged; unused `SESSION_SECRET` removed from config / `.env.example`. - [x] **Drop Dockerfile** — Deploying on DigitalOcean App Platform (buildpack from `go.mod`); no container image needed. - [ ] **Rune-safe truncation** — `title[:120]`, `body[:8000]`, `city[:80]`, answer body, etc. can split multi-byte UTF-8. Truncate by runes (or safely). - [x] **Admin bootstrap** — `ADMIN_USERNAME` seeds the first admin on register only when no admin exists. Promote/demote via `/admin/users` (admins only); roles stay in `users.role`. ## Docs & ops -- [ ] **README** — How to run locally, env vars (from `.env.example`), admin bootstrap, SQLite vs PlanetScale `DATABASE_URL`, App Platform notes (`PORT`, `SECURE_COOKIE=1`). -- [ ] **Migrations story** — Schema is applied on boot from `schema.sql` (+ sessions DDL). OK for v1; plan real migrations before schema drifts between SQLite and Postgres. +- [ ] **README** — How to run locally, env vars (from `.env.example`), admin bootstrap, PlanetScale `DATABASE_URL`, App Platform notes (`PORT`, `SECURE_COOKIE=1`). +- [ ] **Migrations story** — Schema is applied on boot from `schema.sql` (+ sessions DDL). OK for v1; plan real migrations before schema drifts. - [x] **App Platform listen port** — Prefers `PORT`, then `LISTEN`, then `:8080`. -- [x] **Prod DB = PlanetScale Postgres** — App already opens Postgres when `DATABASE_URL` is set; DSN cleanup strips PlanetScale/libpq-only params (`sslrootcert=system`, `sslnegotiation`). Use dashboard URI on **5432** for boot schema create; **6432** (PgBouncer) later if you need pooling. +- [x] **Prod DB = PlanetScale Postgres** — App opens Postgres via required `DATABASE_URL`; DSN cleanup strips PlanetScale/libpq-only params (`sslrootcert=system`, `sslnegotiation`). Use dashboard URI on **5432** for boot schema create; **6432** (PgBouncer) later if you need pooling. ## Smaller / later - [ ] Rate-limit login/register (bcrypt helps; still open to brute-force). - [ ] Graceful shutdown instead of bare `ListenAndServe`. - [ ] More tests: vote HTMX paths, admin answer/hide, archive redirects; optional Postgres integration test. -- [ ] Watch dual-dialect schema — one SQL file works now; expect divergence later. ## Suggested order of attack From c77298411e38e982463ac69cbed604515084e1f9 Mon Sep 17 00:00:00 2001 From: codegirl-007 Date: Sat, 22 Aug 2026 02:40:51 -0700 Subject: [PATCH 07/17] Refactor Store into SessionStore; move domain SQL onto User/Question/Answer. --- cmd/server/main.go | 18 +- internal/store/answer.go | 57 ++++++ internal/store/db.go | 48 ----- internal/store/postgres.go | 19 +- internal/store/question.go | 168 +++++++++++++++ internal/store/sessions.go | 29 ++- internal/store/store.go | 371 ---------------------------------- internal/store/user.go | 183 +++++++++++++++++ internal/store/vote.go | 34 ++++ internal/web/admin.go | 11 +- internal/web/auth.go | 15 +- internal/web/memstore_test.go | 329 ------------------------------ internal/web/profile.go | 12 +- internal/web/server.go | 43 ++-- internal/web/server_test.go | 235 ++++++++++++++------- 15 files changed, 696 insertions(+), 876 deletions(-) create mode 100644 internal/store/answer.go delete mode 100644 internal/store/db.go create mode 100644 internal/store/question.go delete mode 100644 internal/store/store.go create mode 100644 internal/store/user.go create mode 100644 internal/store/vote.go delete mode 100644 internal/web/memstore_test.go diff --git a/cmd/server/main.go b/cmd/server/main.go index b09be88..aed2530 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -2,6 +2,7 @@ package main import ( "context" + "database/sql" "errors" "log" "net/http" @@ -22,29 +23,30 @@ import ( func main() { _ = godotenv.Load() - st := openStore() - defer st.Close() + db, sessions := openDB() + defer db.Close() + defer sessions.Close() uploader := blob.FromEnv() - handler := newHandler(st, uploader) + handler := newHandler(db, sessions, uploader) run(&http.Server{Addr: listenAddr(), Handler: handler}) } -func openStore() *store.Store { +func openDB() (*sql.DB, *store.SessionStore) { databaseURL := strings.TrimSpace(os.Getenv("DATABASE_URL")) if databaseURL == "" { log.Fatal("DATABASE_URL is required") } - st, err := store.OpenPostgres(databaseURL, plumber.SchemaSQL) + db, sessions, err := store.OpenPostgres(databaseURL, plumber.SchemaSQL) if err != nil { log.Fatalf("database: %v", err) } log.Printf("database: postgres") - return st + return db, sessions } -func newHandler(st *store.Store, uploader blob.Uploader) http.Handler { - srv, err := web.New(st, st.SessionStore(), plumber.TemplateFS, plumber.StaticFS, web.Config{ +func newHandler(db *sql.DB, sessions *store.SessionStore, uploader blob.Uploader) http.Handler { + srv, err := web.New(db, sessions.Store(), plumber.TemplateFS, plumber.StaticFS, web.Config{ AdminUsername: os.Getenv("ADMIN_USERNAME"), SecureCookie: os.Getenv("SECURE_COOKIE") == "1", Blob: uploader, diff --git a/internal/store/answer.go b/internal/store/answer.go new file mode 100644 index 0000000..571186c --- /dev/null +++ b/internal/store/answer.go @@ -0,0 +1,57 @@ +package store + +import ( + "context" + "database/sql" + "fmt" + "strings" + "time" +) + +// Answer is an admin reply to a question. +type Answer struct { + QuestionID string + AuthorID string + AuthorName string + Body string + CreatedAt string + UpdatedAt string + db *sql.DB +} + +// NewAnswer returns an Answer bound to db. +func NewAnswer(db *sql.DB) *Answer { + return &Answer{db: db} +} + +// Upsert inserts or updates the answer for QuestionID. +func (a *Answer) Upsert(ctx context.Context) error { + if a == nil || a.db == nil { + return fmt.Errorf("answer: no database") + } + a.Body = strings.TrimSpace(a.Body) + now := time.Now().UTC().Format(time.RFC3339) + if a.CreatedAt == "" { + a.CreatedAt = now + } + a.UpdatedAt = now + _, err := a.db.ExecContext(ctx, ` +INSERT INTO answers (question_id, author_id, body, created_at, updated_at) VALUES ($1, $2, $3, $4, $5) +ON CONFLICT (question_id) DO UPDATE SET body = excluded.body, author_id = excluded.author_id, updated_at = excluded.updated_at`, + a.QuestionID, a.AuthorID, a.Body, a.CreatedAt, a.UpdatedAt) + return err +} + +func GetAnswer(ctx context.Context, db *sql.DB, questionID string) (*Answer, error) { + var a Answer + err := db.QueryRowContext(ctx, ` +SELECT a.question_id, a.author_id, u.name, a.body, a.created_at, a.updated_at +FROM answers a +JOIN users u ON u.id = a.author_id +WHERE a.question_id = $1`, questionID).Scan(&a.QuestionID, &a.AuthorID, &a.AuthorName, &a.Body, &a.CreatedAt, &a.UpdatedAt) + if err != nil { + return nil, err + } + a.db = db + return &a, nil +} diff --git a/internal/store/db.go b/internal/store/db.go deleted file mode 100644 index 45514bc..0000000 --- a/internal/store/db.go +++ /dev/null @@ -1,48 +0,0 @@ -package store - -import ( - "context" - "errors" -) - -// ErrLastAdmin is returned when demoting the only remaining admin. -var ErrLastAdmin = errors.New("cannot demote the last admin") - -// Role is a user privilege level stored in users.role. -type Role string - -const ( - RoleUser Role = "user" - RoleAdmin Role = "admin" -) - -// NewUser is the input for CreateUser. -type NewUser struct { - Username string - PasswordHash string - Role Role -} - -// DB is the persistence API used by the web layer. -// Named DB to avoid colliding with scs.Store. -type DB interface { - CreateUser(ctx context.Context, user NewUser) (*User, error) - UserByID(ctx context.Context, id string) (*User, error) - UserByUsername(ctx context.Context, username string) (*User, error) - CountAdmins(ctx context.Context) (int, error) - ListUsers(ctx context.Context) ([]User, error) - SetRole(ctx context.Context, userID string, role Role) error - CreateQuestion(ctx context.Context, authorID, title, body, city string) (*RankedQuestion, error) - ListHunt(ctx context.Context, huntDate, viewerID string) ([]RankedQuestion, error) - GetQuestion(ctx context.Context, id, viewerID string) (*RankedQuestion, error) - Vote(ctx context.Context, userID, questionID string, value int) error - GetAnswer(ctx context.Context, questionID string) (*Answer, error) - UpsertAnswer(ctx context.Context, questionID, authorID, body string) error - HideQuestion(ctx context.Context, id string) error - UpdateProfile(ctx context.Context, userID, state, avatarURL string) error - ListQuestionsByAuthor(ctx context.Context, authorID string) ([]RankedQuestion, error) - ListQuestionsAnsweredBy(ctx context.Context, adminID string) ([]RankedQuestion, error) -} - -// Compile-time check: *Store implements DB. -var _ DB = (*Store)(nil) diff --git a/internal/store/postgres.go b/internal/store/postgres.go index 44b1069..cd5d24b 100644 --- a/internal/store/postgres.go +++ b/internal/store/postgres.go @@ -48,34 +48,33 @@ func postgresDSN(raw string) (string, error) { } // OpenPostgres connects to Postgres, applies schema/migrations, and starts session cleanup. -func OpenPostgres(databaseURL, schema string) (*Store, error) { +func OpenPostgres(databaseURL, schema string) (*sql.DB, *SessionStore, error) { dsn, err := postgresDSN(databaseURL) if err != nil { - return nil, err + return nil, nil, err } db, err := sql.Open("pgx", dsn) if err != nil { - return nil, err + return nil, nil, err } db.SetMaxOpenConns(20) db.SetMaxIdleConns(5) if err := db.Ping(); err != nil { _ = db.Close() - return nil, fmt.Errorf("postgres ping: %w", err) + return nil, nil, fmt.Errorf("postgres ping: %w", err) } if err := applySchema(db, schema); err != nil { _ = db.Close() - return nil, fmt.Errorf("apply schema: %w", err) + return nil, nil, fmt.Errorf("apply schema: %w", err) } if err := applySessionsSchema(db); err != nil { _ = db.Close() - return nil, fmt.Errorf("apply sessions schema: %w", err) + return nil, nil, fmt.Errorf("apply sessions schema: %w", err) } if err := migrateUserProfileColumns(db); err != nil { _ = db.Close() - return nil, fmt.Errorf("migrate profile columns: %w", err) + return nil, nil, fmt.Errorf("migrate profile columns: %w", err) } - st := &Store{db: db} - st.initSessionStore(5 * time.Minute) - return st, nil + sessions := NewSessionStore(db, 5*time.Minute) + return db, sessions, nil } diff --git a/internal/store/question.go b/internal/store/question.go new file mode 100644 index 0000000..81928a4 --- /dev/null +++ b/internal/store/question.go @@ -0,0 +1,168 @@ +package store + +import ( + "context" + "database/sql" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + + "plumber/internal/pacific" +) + +// RankedQuestion is a question row with score / vote annotations for lists. +type RankedQuestion struct { + ID string + AuthorID string + AuthorName string + Title string + Body string + City string + HuntDate string + Hidden bool + CreatedAt string + Score int + Answered bool + UserVote int + db *sql.DB +} + +// NewQuestion returns a question bound to db (not yet inserted). +func NewQuestion(db *sql.DB) *RankedQuestion { + return &RankedQuestion{db: db} +} + +// Create inserts the question. Sets ID, HuntDate, and CreatedAt when empty. +func (q *RankedQuestion) Create(ctx context.Context) error { + if q == nil || q.db == nil { + return fmt.Errorf("question: no database") + } + q.Title = strings.TrimSpace(q.Title) + q.Body = strings.TrimSpace(q.Body) + q.City = strings.TrimSpace(q.City) + if q.ID == "" { + q.ID = uuid.NewString() + } + if q.HuntDate == "" { + q.HuntDate = pacific.Today() + } + if q.CreatedAt == "" { + q.CreatedAt = time.Now().UTC().Format(time.RFC3339) + } + _, err := q.db.ExecContext(ctx, `INSERT INTO questions (id, author_id, title, body, city, hunt_date, hidden, created_at) VALUES ($1, $2, $3, $4, $5, $6, 0, $7)`, + q.ID, q.AuthorID, q.Title, q.Body, q.City, q.HuntDate, q.CreatedAt) + return err +} + +// Hide marks the question hidden. +func (q *RankedQuestion) Hide(ctx context.Context) error { + if q == nil || q.db == nil { + return fmt.Errorf("question: no database") + } + _, err := q.db.ExecContext(ctx, `UPDATE questions SET hidden = 1 WHERE id = $1`, q.ID) + if err == nil { + q.Hidden = true + } + return err +} + +func ListHunt(ctx context.Context, db *sql.DB, huntDate, viewerID string) ([]RankedQuestion, error) { + rows, err := db.QueryContext(ctx, ` +SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE(SUM(v.value), 0) AS score, + CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END AS answered, + COALESCE((SELECT value FROM votes WHERE user_id = $1 AND question_id = q.id), 0) AS user_vote +FROM questions q +JOIN users u ON u.id = q.author_id +LEFT JOIN votes v ON v.question_id = q.id +LEFT JOIN answers a ON a.question_id = q.id +WHERE q.hunt_date = $2 AND q.hidden = 0 +GROUP BY q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, a.question_id +ORDER BY score DESC, q.created_at ASC`, viewerID, huntDate) + if err != nil { + return nil, err + } + defer rows.Close() + return scanRankedList(db, rows) +} + +func GetQuestion(ctx context.Context, db *sql.DB, id, viewerID string) (*RankedQuestion, error) { + row := db.QueryRowContext(ctx, ` +SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE((SELECT SUM(value) FROM votes WHERE question_id = q.id), 0) AS score, + CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END AS answered, + COALESCE((SELECT value FROM votes WHERE user_id = $1 AND question_id = q.id), 0) AS user_vote +FROM questions q +JOIN users u ON u.id = q.author_id +LEFT JOIN answers a ON a.question_id = q.id +WHERE q.id = $2`, viewerID, id) + q, err := scanRanked(db, row) + if err != nil { + return nil, err + } + return &q, nil +} + +func ListQuestionsByAuthor(ctx context.Context, db *sql.DB, authorID string) ([]RankedQuestion, error) { + rows, err := db.QueryContext(ctx, ` +SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE((SELECT SUM(value) FROM votes WHERE question_id = q.id), 0) AS score, + CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END AS answered, + 0 AS user_vote +FROM questions q +JOIN users u ON u.id = q.author_id +LEFT JOIN answers a ON a.question_id = q.id +WHERE q.author_id = $1 AND q.hidden = 0 +ORDER BY q.created_at DESC`, authorID) + if err != nil { + return nil, err + } + defer rows.Close() + return scanRankedList(db, rows) +} + +func ListQuestionsAnsweredBy(ctx context.Context, db *sql.DB, adminID string) ([]RankedQuestion, error) { + rows, err := db.QueryContext(ctx, ` +SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE((SELECT SUM(value) FROM votes WHERE question_id = q.id), 0) AS score, + 1 AS answered, + 0 AS user_vote +FROM answers ans +JOIN questions q ON q.id = ans.question_id +JOIN users u ON u.id = q.author_id +WHERE ans.author_id = $1 AND q.hidden = 0 +ORDER BY ans.updated_at DESC`, adminID) + if err != nil { + return nil, err + } + defer rows.Close() + return scanRankedList(db, rows) +} + +type scanned interface { + Scan(dest ...any) error +} + +func scanRanked(db *sql.DB, rows scanned) (RankedQuestion, error) { + var q RankedQuestion + var hidden, answered int + err := rows.Scan(&q.ID, &q.AuthorID, &q.AuthorName, &q.Title, &q.Body, &q.City, &q.HuntDate, &hidden, &q.CreatedAt, &q.Score, &answered, &q.UserVote) + q.Hidden = hidden != 0 + q.Answered = answered != 0 + q.db = db + return q, err +} + +func scanRankedList(db *sql.DB, rows *sql.Rows) ([]RankedQuestion, error) { + var out []RankedQuestion + for rows.Next() { + q, err := scanRanked(db, rows) + if err != nil { + return nil, err + } + out = append(out, q) + } + return out, rows.Err() +} diff --git a/internal/store/sessions.go b/internal/store/sessions.go index 33c507c..4d4edcf 100644 --- a/internal/store/sessions.go +++ b/internal/store/sessions.go @@ -26,13 +26,28 @@ type sessionStopper interface { StopCleanup() } -// SessionStore returns the scs store backed by this database. -func (s *Store) SessionStore() scs.Store { - return s.sessionStore +// SessionStore wraps scs Postgres session persistence and cleanup. +type SessionStore struct { + store scs.Store + stopper sessionStopper } -func (s *Store) initSessionStore(cleanupInterval time.Duration) { - ps := postgresstore.NewWithCleanupInterval(s.db, cleanupInterval) - s.sessionStore = ps - s.sessionStopper = ps +// NewSessionStore starts a postgresstore with the given cleanup interval. +func NewSessionStore(db *sql.DB, cleanupInterval time.Duration) *SessionStore { + ps := postgresstore.NewWithCleanupInterval(db, cleanupInterval) + return &SessionStore{store: ps, stopper: ps} +} + +// Store returns the scs.Store implementation. +func (s *SessionStore) Store() scs.Store { + return s.store +} + +// Close stops background session cleanup. +func (s *SessionStore) Close() { + if s == nil || s.stopper == nil { + return + } + s.stopper.StopCleanup() + s.stopper = nil } diff --git a/internal/store/store.go b/internal/store/store.go deleted file mode 100644 index 9c93af8..0000000 --- a/internal/store/store.go +++ /dev/null @@ -1,371 +0,0 @@ -package store - -import ( - "context" - "database/sql" - "fmt" - "strings" - "time" - - "github.com/alexedwards/scs/v2" - "github.com/google/uuid" - - "plumber/internal/pacific" -) - -type Store struct { - db *sql.DB - sessionStore scs.Store - sessionStopper sessionStopper -} - -type User struct { - ID string - Username string - Name string - Role Role - AvatarURL string - State string - CreatedAt string - PasswordHash string -} - -func (u *User) Admin() bool { - return u != nil && u.Role == RoleAdmin -} - -type RankedQuestion struct { - ID string - AuthorID string - AuthorName string - Title string - Body string - City string - HuntDate string - Hidden bool - CreatedAt string - Score int - Answered bool - UserVote int -} - -type Answer struct { - QuestionID string - AuthorID string - AuthorName string - Body string - CreatedAt string - UpdatedAt string -} - -func (s *Store) Close() error { - if s.sessionStopper != nil { - s.sessionStopper.StopCleanup() - s.sessionStopper = nil - } - return s.db.Close() -} - -func (s *Store) CreateUser(ctx context.Context, nu NewUser) (*User, error) { - if nu.Role != RoleUser && nu.Role != RoleAdmin { - return nil, fmt.Errorf("invalid role") - } - username := NormalizeUsername(nu.Username) - u := &User{ - ID: uuid.NewString(), - Username: username, - Name: username, - Role: nu.Role, - PasswordHash: nu.PasswordHash, - CreatedAt: time.Now().UTC().Format(time.RFC3339), - } - _, err := s.db.ExecContext(ctx, `INSERT INTO users (id, username, name, password_hash, role, avatar_url, state, created_at) VALUES ($1, $2, $3, $4, $5, '', '', $6)`, - u.ID, u.Username, u.Name, u.PasswordHash, string(u.Role), u.CreatedAt) - if err != nil { - return nil, err - } - return u, nil -} - -func (s *Store) CountAdmins(ctx context.Context) (int, error) { - var n int - err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users WHERE role = $1`, string(RoleAdmin)).Scan(&n) - return n, err -} - -func (s *Store) ListUsers(ctx context.Context) ([]User, error) { - rows, err := s.db.QueryContext(ctx, `SELECT id, username, name, role, avatar_url, state, created_at FROM users ORDER BY created_at ASC`) - if err != nil { - return nil, err - } - defer rows.Close() - var out []User - for rows.Next() { - var u User - var role string - if err := rows.Scan(&u.ID, &u.Username, &u.Name, &role, &u.AvatarURL, &u.State, &u.CreatedAt); err != nil { - return nil, err - } - u.Role = Role(role) - out = append(out, u) - } - return out, rows.Err() -} - -func (s *Store) SetRole(ctx context.Context, userID string, role Role) error { - if role != RoleUser && role != RoleAdmin { - return fmt.Errorf("invalid role") - } - tx, err := s.db.BeginTx(ctx, nil) - if err != nil { - return err - } - defer tx.Rollback() - - var current string - err = tx.QueryRowContext(ctx, `SELECT role FROM users WHERE id = $1`, userID).Scan(¤t) - if err != nil { - return err - } - if Role(current) == RoleAdmin && role == RoleUser { - var n int - if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM users WHERE role = $1`, string(RoleAdmin)).Scan(&n); err != nil { - return err - } - if n <= 1 { - return ErrLastAdmin - } - } - res, err := tx.ExecContext(ctx, `UPDATE users SET role = $1 WHERE id = $2`, string(role), userID) - if err != nil { - return err - } - aff, err := res.RowsAffected() - if err != nil { - return err - } - if aff == 0 { - return sql.ErrNoRows - } - return tx.Commit() -} - -func (s *Store) UserByID(ctx context.Context, id string) (*User, error) { - return scanUser(s.db.QueryRowContext(ctx, `SELECT id, username, name, role, avatar_url, state, created_at FROM users WHERE id = $1`, id), false) -} - -func (s *Store) UserByUsername(ctx context.Context, username string) (*User, error) { - return scanUser(s.db.QueryRowContext(ctx, `SELECT id, username, name, role, avatar_url, state, created_at, password_hash FROM users WHERE username = $1`, NormalizeUsername(username)), true) -} - -func scanUser(row *sql.Row, withSecrets bool) (*User, error) { - var u User - var role string - var err error - if withSecrets { - err = row.Scan(&u.ID, &u.Username, &u.Name, &role, &u.AvatarURL, &u.State, &u.CreatedAt, &u.PasswordHash) - } else { - err = row.Scan(&u.ID, &u.Username, &u.Name, &role, &u.AvatarURL, &u.State, &u.CreatedAt) - } - if err != nil { - return nil, err - } - u.Role = Role(role) - return &u, nil -} - -func NormalizeUsername(s string) string { - return strings.ToLower(strings.TrimSpace(s)) -} - -func (s *Store) CreateQuestion(ctx context.Context, authorID, title, body, city string) (*RankedQuestion, error) { - q := &RankedQuestion{ - ID: uuid.NewString(), - AuthorID: authorID, - Title: strings.TrimSpace(title), - Body: strings.TrimSpace(body), - City: strings.TrimSpace(city), - HuntDate: pacific.Today(), - CreatedAt: time.Now().UTC().Format(time.RFC3339), - } - _, err := s.db.ExecContext(ctx, `INSERT INTO questions (id, author_id, title, body, city, hunt_date, hidden, created_at) VALUES ($1, $2, $3, $4, $5, $6, 0, $7)`, - q.ID, q.AuthorID, q.Title, q.Body, q.City, q.HuntDate, q.CreatedAt) - if err != nil { - return nil, err - } - return q, nil -} - -func (s *Store) ListHunt(ctx context.Context, huntDate, viewerID string) ([]RankedQuestion, error) { - rows, err := s.db.QueryContext(ctx, ` -SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, - COALESCE(SUM(v.value), 0) AS score, - CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END AS answered, - COALESCE((SELECT value FROM votes WHERE user_id = $1 AND question_id = q.id), 0) AS user_vote -FROM questions q -JOIN users u ON u.id = q.author_id -LEFT JOIN votes v ON v.question_id = q.id -LEFT JOIN answers a ON a.question_id = q.id -WHERE q.hunt_date = $2 AND q.hidden = 0 -GROUP BY q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, a.question_id -ORDER BY score DESC, q.created_at ASC`, viewerID, huntDate) - if err != nil { - return nil, err - } - defer rows.Close() - var out []RankedQuestion - for rows.Next() { - q, err := scanRanked(rows) - if err != nil { - return nil, err - } - out = append(out, q) - } - return out, rows.Err() -} - -func (s *Store) GetQuestion(ctx context.Context, id, viewerID string) (*RankedQuestion, error) { - row := s.db.QueryRowContext(ctx, ` -SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, - COALESCE((SELECT SUM(value) FROM votes WHERE question_id = q.id), 0) AS score, - CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END AS answered, - COALESCE((SELECT value FROM votes WHERE user_id = $1 AND question_id = q.id), 0) AS user_vote -FROM questions q -JOIN users u ON u.id = q.author_id -LEFT JOIN answers a ON a.question_id = q.id -WHERE q.id = $2`, viewerID, id) - q, err := scanRankedRow(row) - if err != nil { - return nil, err - } - return &q, nil -} - -type scanned interface { - Scan(dest ...any) error -} - -func scanRanked(rows scanned) (RankedQuestion, error) { - var q RankedQuestion - var hidden, answered int - err := rows.Scan(&q.ID, &q.AuthorID, &q.AuthorName, &q.Title, &q.Body, &q.City, &q.HuntDate, &hidden, &q.CreatedAt, &q.Score, &answered, &q.UserVote) - q.Hidden = hidden != 0 - q.Answered = answered != 0 - return q, err -} - -func scanRankedRow(row *sql.Row) (RankedQuestion, error) { - return scanRanked(row) -} - -func (s *Store) Vote(ctx context.Context, userID, questionID string, value int) error { - if value != 1 && value != -1 { - return fmt.Errorf("invalid vote") - } - tx, err := s.db.BeginTx(ctx, nil) - if err != nil { - return err - } - defer tx.Rollback() - var current sql.NullInt64 - err = tx.QueryRowContext(ctx, `SELECT value FROM votes WHERE user_id = $1 AND question_id = $2`, userID, questionID).Scan(¤t) - if err != nil && err != sql.ErrNoRows { - return err - } - if err == nil && current.Valid && int(current.Int64) == value { - _, err = tx.ExecContext(ctx, `DELETE FROM votes WHERE user_id = $1 AND question_id = $2`, userID, questionID) - } else { - _, err = tx.ExecContext(ctx, `INSERT INTO votes (user_id, question_id, value) VALUES ($1, $2, $3) -ON CONFLICT (user_id, question_id) DO UPDATE SET value = excluded.value`, userID, questionID, value) - } - if err != nil { - return err - } - return tx.Commit() -} - -func (s *Store) GetAnswer(ctx context.Context, questionID string) (*Answer, error) { - var a Answer - err := s.db.QueryRowContext(ctx, ` -SELECT a.question_id, a.author_id, u.name, a.body, a.created_at, a.updated_at -FROM answers a -JOIN users u ON u.id = a.author_id -WHERE a.question_id = $1`, questionID).Scan(&a.QuestionID, &a.AuthorID, &a.AuthorName, &a.Body, &a.CreatedAt, &a.UpdatedAt) - if err != nil { - return nil, err - } - return &a, nil -} - -func (s *Store) UpsertAnswer(ctx context.Context, questionID, authorID, body string) error { - body = strings.TrimSpace(body) - now := time.Now().UTC().Format(time.RFC3339) - _, err := s.db.ExecContext(ctx, ` -INSERT INTO answers (question_id, author_id, body, created_at, updated_at) VALUES ($1, $2, $3, $4, $5) -ON CONFLICT (question_id) DO UPDATE SET body = excluded.body, author_id = excluded.author_id, updated_at = excluded.updated_at`, - questionID, authorID, body, now, now) - return err -} - -func (s *Store) HideQuestion(ctx context.Context, id string) error { - _, err := s.db.ExecContext(ctx, `UPDATE questions SET hidden = 1 WHERE id = $1`, id) - return err -} - -func (s *Store) UpdateProfile(ctx context.Context, userID, state, avatarURL string) error { - state = strings.TrimSpace(state) - if avatarURL == "" { - _, err := s.db.ExecContext(ctx, `UPDATE users SET state = $1 WHERE id = $2`, state, userID) - return err - } - _, err := s.db.ExecContext(ctx, `UPDATE users SET state = $1, avatar_url = $2 WHERE id = $3`, state, avatarURL, userID) - return err -} - -func (s *Store) ListQuestionsByAuthor(ctx context.Context, authorID string) ([]RankedQuestion, error) { - rows, err := s.db.QueryContext(ctx, ` -SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, - COALESCE((SELECT SUM(value) FROM votes WHERE question_id = q.id), 0) AS score, - CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END AS answered, - 0 AS user_vote -FROM questions q -JOIN users u ON u.id = q.author_id -LEFT JOIN answers a ON a.question_id = q.id -WHERE q.author_id = $1 AND q.hidden = 0 -ORDER BY q.created_at DESC`, authorID) - if err != nil { - return nil, err - } - defer rows.Close() - return scanRankedList(rows) -} - -func (s *Store) ListQuestionsAnsweredBy(ctx context.Context, adminID string) ([]RankedQuestion, error) { - rows, err := s.db.QueryContext(ctx, ` -SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, - COALESCE((SELECT SUM(value) FROM votes WHERE question_id = q.id), 0) AS score, - 1 AS answered, - 0 AS user_vote -FROM answers ans -JOIN questions q ON q.id = ans.question_id -JOIN users u ON u.id = q.author_id -WHERE ans.author_id = $1 AND q.hidden = 0 -ORDER BY ans.updated_at DESC`, adminID) - if err != nil { - return nil, err - } - defer rows.Close() - return scanRankedList(rows) -} - -func scanRankedList(rows *sql.Rows) ([]RankedQuestion, error) { - var out []RankedQuestion - for rows.Next() { - q, err := scanRanked(rows) - if err != nil { - return nil, err - } - out = append(out, q) - } - return out, rows.Err() -} diff --git a/internal/store/user.go b/internal/store/user.go new file mode 100644 index 0000000..21e57a3 --- /dev/null +++ b/internal/store/user.go @@ -0,0 +1,183 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "fmt" + "strings" + "time" + + "github.com/google/uuid" +) + +// ErrLastAdmin is returned when demoting the only remaining admin. +var ErrLastAdmin = errors.New("cannot demote the last admin") + +// Role is a user privilege level stored in users.role. +type Role string + +const ( + RoleUser Role = "user" + RoleAdmin Role = "admin" +) + +// User is an account row. Methods run SQL against db. +type User struct { + ID string + Username string + Name string + Role Role + AvatarURL string + State string + CreatedAt string + PasswordHash string + db *sql.DB +} + +// NewUser returns a User bound to db (not yet inserted). +func NewUser(db *sql.DB) *User { + return &User{db: db} +} + +func (u *User) Admin() bool { + return u != nil && u.Role == RoleAdmin +} + +func NormalizeUsername(s string) string { + return strings.ToLower(strings.TrimSpace(s)) +} + +// Create inserts the user. Sets ID, Name, and CreatedAt when empty. +func (u *User) Create(ctx context.Context) error { + if u == nil || u.db == nil { + return fmt.Errorf("user: no database") + } + if u.Role != RoleUser && u.Role != RoleAdmin { + return fmt.Errorf("invalid role") + } + u.Username = NormalizeUsername(u.Username) + if u.ID == "" { + u.ID = uuid.NewString() + } + if u.Name == "" { + u.Name = u.Username + } + if u.CreatedAt == "" { + u.CreatedAt = time.Now().UTC().Format(time.RFC3339) + } + _, err := u.db.ExecContext(ctx, `INSERT INTO users (id, username, name, password_hash, role, avatar_url, state, created_at) VALUES ($1, $2, $3, $4, $5, '', '', $6)`, + u.ID, u.Username, u.Name, u.PasswordHash, string(u.Role), u.CreatedAt) + return err +} + +// SetRole updates this user's role (last-admin safe). +func (u *User) SetRole(ctx context.Context, role Role) error { + if u == nil || u.db == nil { + return fmt.Errorf("user: no database") + } + if role != RoleUser && role != RoleAdmin { + return fmt.Errorf("invalid role") + } + tx, err := u.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + + var current string + err = tx.QueryRowContext(ctx, `SELECT role FROM users WHERE id = $1`, u.ID).Scan(¤t) + if err != nil { + return err + } + if Role(current) == RoleAdmin && role == RoleUser { + var n int + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM users WHERE role = $1`, string(RoleAdmin)).Scan(&n); err != nil { + return err + } + if n <= 1 { + return ErrLastAdmin + } + } + res, err := tx.ExecContext(ctx, `UPDATE users SET role = $1 WHERE id = $2`, string(role), u.ID) + if err != nil { + return err + } + aff, err := res.RowsAffected() + if err != nil { + return err + } + if aff == 0 { + return sql.ErrNoRows + } + if err := tx.Commit(); err != nil { + return err + } + u.Role = role + return nil +} + +// SaveProfile writes State and optionally AvatarURL. +func (u *User) SaveProfile(ctx context.Context) error { + if u == nil || u.db == nil { + return fmt.Errorf("user: no database") + } + u.State = strings.TrimSpace(u.State) + if u.AvatarURL == "" { + _, err := u.db.ExecContext(ctx, `UPDATE users SET state = $1 WHERE id = $2`, u.State, u.ID) + return err + } + _, err := u.db.ExecContext(ctx, `UPDATE users SET state = $1, avatar_url = $2 WHERE id = $3`, u.State, u.AvatarURL, u.ID) + return err +} + +func CountAdmins(ctx context.Context, db *sql.DB) (int, error) { + var n int + err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users WHERE role = $1`, string(RoleAdmin)).Scan(&n) + return n, err +} + +func ListUsers(ctx context.Context, db *sql.DB) ([]User, error) { + rows, err := db.QueryContext(ctx, `SELECT id, username, name, role, avatar_url, state, created_at FROM users ORDER BY created_at ASC`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []User + for rows.Next() { + var u User + var role string + if err := rows.Scan(&u.ID, &u.Username, &u.Name, &role, &u.AvatarURL, &u.State, &u.CreatedAt); err != nil { + return nil, err + } + u.Role = Role(role) + u.db = db + out = append(out, u) + } + return out, rows.Err() +} + +func UserByID(ctx context.Context, db *sql.DB, id string) (*User, error) { + return scanUser(db, db.QueryRowContext(ctx, `SELECT id, username, name, role, avatar_url, state, created_at FROM users WHERE id = $1`, id), false) +} + +func UserByUsername(ctx context.Context, db *sql.DB, username string) (*User, error) { + return scanUser(db, db.QueryRowContext(ctx, `SELECT id, username, name, role, avatar_url, state, created_at, password_hash FROM users WHERE username = $1`, NormalizeUsername(username)), true) +} + +func scanUser(db *sql.DB, row *sql.Row, withSecrets bool) (*User, error) { + var u User + var role string + var err error + if withSecrets { + err = row.Scan(&u.ID, &u.Username, &u.Name, &role, &u.AvatarURL, &u.State, &u.CreatedAt, &u.PasswordHash) + } else { + err = row.Scan(&u.ID, &u.Username, &u.Name, &role, &u.AvatarURL, &u.State, &u.CreatedAt) + } + if err != nil { + return nil, err + } + u.Role = Role(role) + u.db = db + return &u, nil +} diff --git a/internal/store/vote.go b/internal/store/vote.go new file mode 100644 index 0000000..d3c07b6 --- /dev/null +++ b/internal/store/vote.go @@ -0,0 +1,34 @@ +package store + +import ( + "context" + "database/sql" + "fmt" +) + +// Vote toggles or sets a user's vote on a question (value must be 1 or -1). +func Vote(ctx context.Context, db *sql.DB, userID, questionID string, value int) error { + if value != 1 && value != -1 { + return fmt.Errorf("invalid vote") + } + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var current sql.NullInt64 + err = tx.QueryRowContext(ctx, `SELECT value FROM votes WHERE user_id = $1 AND question_id = $2`, userID, questionID).Scan(¤t) + if err != nil && err != sql.ErrNoRows { + return err + } + if err == nil && current.Valid && int(current.Int64) == value { + _, err = tx.ExecContext(ctx, `DELETE FROM votes WHERE user_id = $1 AND question_id = $2`, userID, questionID) + } else { + _, err = tx.ExecContext(ctx, `INSERT INTO votes (user_id, question_id, value) VALUES ($1, $2, $3) +ON CONFLICT (user_id, question_id) DO UPDATE SET value = excluded.value`, userID, questionID, value) + } + if err != nil { + return err + } + return tx.Commit() +} diff --git a/internal/web/admin.go b/internal/web/admin.go index e7e9e70..b44c966 100644 --- a/internal/web/admin.go +++ b/internal/web/admin.go @@ -28,7 +28,7 @@ func (s *Server) handleAdminUsers(w http.ResponseWriter, r *http.Request) { if s.requireAdmin(w, r) == nil { return } - users, err := s.store.ListUsers(r.Context()) + users, err := store.ListUsers(r.Context(), s.db) if err != nil { http.Error(w, "could not load users", http.StatusInternalServerError) return @@ -48,9 +48,14 @@ func (s *Server) handleAdminSetRole(w http.ResponseWriter, r *http.Request) { } id := chi.URLParam(r, "id") role := store.Role(r.PostFormValue("role")) - err := s.store.SetRole(r.Context(), id, role) + u, err := store.UserByID(r.Context(), s.db, id) + if err != nil { + http.Error(w, "could not update role", http.StatusBadRequest) + return + } + err = u.SetRole(r.Context(), role) if errors.Is(err, store.ErrLastAdmin) { - users, listErr := s.store.ListUsers(r.Context()) + users, listErr := store.ListUsers(r.Context(), s.db) if listErr != nil { http.Error(w, "could not demote last admin", http.StatusBadRequest) return diff --git a/internal/web/auth.go b/internal/web/auth.go index 65cc384..5bf63d3 100644 --- a/internal/web/auth.go +++ b/internal/web/auth.go @@ -43,7 +43,7 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { username := strings.TrimSpace(r.PostFormValue("username")) password := r.PostFormValue("password") next := safeNext(r.PostFormValue("next")) - u, err := s.store.UserByUsername(r.Context(), username) + u, err := store.UserByUsername(r.Context(), s.db, username) if err != nil || bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password)) != nil { w.WriteHeader(http.StatusUnauthorized) s.exec(w, "login", authPage{ @@ -90,7 +90,7 @@ func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) { } role := store.RoleUser if s.cfg.AdminUsername != "" && store.NormalizeUsername(username) == store.NormalizeUsername(s.cfg.AdminUsername) { - n, err := s.store.CountAdmins(r.Context()) + n, err := store.CountAdmins(r.Context(), s.db) if err != nil { http.Error(w, "could not create account", http.StatusInternalServerError) return @@ -99,12 +99,11 @@ func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) { role = store.RoleAdmin } } - u, err := s.store.CreateUser(r.Context(), store.NewUser{ - Username: username, - PasswordHash: string(hash), - Role: role, - }) - if err != nil { + u := store.NewUser(s.db) + u.Username = username + u.PasswordHash = string(hash) + u.Role = role + if err := u.Create(r.Context()); err != nil { p.Error = "That username is taken." s.exec(w, "register", p) return diff --git a/internal/web/memstore_test.go b/internal/web/memstore_test.go deleted file mode 100644 index 8476ce5..0000000 --- a/internal/web/memstore_test.go +++ /dev/null @@ -1,329 +0,0 @@ -package web - -import ( - "context" - "database/sql" - "fmt" - "sort" - "strings" - "sync" - "time" - - "github.com/google/uuid" - - "plumber/internal/pacific" - "plumber/internal/store" -) - -// memDB is an in-memory store.DB for tests. -type memDB struct { - mu sync.Mutex - users map[string]*store.User // id -> user - byName map[string]string // username -> id - questions map[string]*store.RankedQuestion // id -> question - votes map[string]int // userID|questionID -> value - answers map[string]*store.Answer // questionID -> answer -} - -func newMemDB() *memDB { - return &memDB{ - users: map[string]*store.User{}, - byName: map[string]string{}, - questions: map[string]*store.RankedQuestion{}, - votes: map[string]int{}, - answers: map[string]*store.Answer{}, - } -} - -func voteKey(userID, questionID string) string { - return userID + "|" + questionID -} - -func (m *memDB) CreateUser(_ context.Context, nu store.NewUser) (*store.User, error) { - m.mu.Lock() - defer m.mu.Unlock() - username := store.NormalizeUsername(nu.Username) - if _, ok := m.byName[username]; ok { - return nil, fmt.Errorf("username taken") - } - if nu.Role != store.RoleUser && nu.Role != store.RoleAdmin { - return nil, fmt.Errorf("invalid role") - } - u := &store.User{ - ID: uuid.NewString(), - Username: username, - Name: username, - Role: nu.Role, - PasswordHash: nu.PasswordHash, - CreatedAt: time.Now().UTC().Format(time.RFC3339), - } - m.users[u.ID] = u - m.byName[username] = u.ID - cp := *u - return &cp, nil -} - -func (m *memDB) UserByID(_ context.Context, id string) (*store.User, error) { - m.mu.Lock() - defer m.mu.Unlock() - u, ok := m.users[id] - if !ok { - return nil, sql.ErrNoRows - } - cp := *u - cp.PasswordHash = "" - return &cp, nil -} - -func (m *memDB) UserByUsername(_ context.Context, username string) (*store.User, error) { - m.mu.Lock() - defer m.mu.Unlock() - id, ok := m.byName[store.NormalizeUsername(username)] - if !ok { - return nil, sql.ErrNoRows - } - cp := *m.users[id] - return &cp, nil -} - -func (m *memDB) CountAdmins(_ context.Context) (int, error) { - m.mu.Lock() - defer m.mu.Unlock() - n := 0 - for _, u := range m.users { - if u.Role == store.RoleAdmin { - n++ - } - } - return n, nil -} - -func (m *memDB) ListUsers(_ context.Context) ([]store.User, error) { - m.mu.Lock() - defer m.mu.Unlock() - out := make([]store.User, 0, len(m.users)) - for _, u := range m.users { - cp := *u - cp.PasswordHash = "" - out = append(out, cp) - } - sort.Slice(out, func(i, j int) bool { - return out[i].CreatedAt < out[j].CreatedAt - }) - return out, nil -} - -func (m *memDB) SetRole(_ context.Context, userID string, role store.Role) error { - if role != store.RoleUser && role != store.RoleAdmin { - return fmt.Errorf("invalid role") - } - m.mu.Lock() - defer m.mu.Unlock() - u, ok := m.users[userID] - if !ok { - return sql.ErrNoRows - } - if u.Role == store.RoleAdmin && role == store.RoleUser { - n := 0 - for _, x := range m.users { - if x.Role == store.RoleAdmin { - n++ - } - } - if n <= 1 { - return store.ErrLastAdmin - } - } - u.Role = role - return nil -} - -func (m *memDB) CreateQuestion(_ context.Context, authorID, title, body, city string) (*store.RankedQuestion, error) { - m.mu.Lock() - defer m.mu.Unlock() - author, ok := m.users[authorID] - if !ok { - return nil, fmt.Errorf("unknown author") - } - q := &store.RankedQuestion{ - ID: uuid.NewString(), - AuthorID: authorID, - AuthorName: author.Name, - Title: strings.TrimSpace(title), - Body: strings.TrimSpace(body), - City: strings.TrimSpace(city), - HuntDate: pacific.Today(), - CreatedAt: time.Now().UTC().Format(time.RFC3339), - } - m.questions[q.ID] = q - cp := *q - return &cp, nil -} - -func (m *memDB) rankedLocked(q *store.RankedQuestion, viewerID string) store.RankedQuestion { - out := *q - score := 0 - for k, v := range m.votes { - _, qid, ok := strings.Cut(k, "|") - if ok && qid == q.ID { - score += v - } - } - out.Score = score - out.Answered = m.answers[q.ID] != nil - if viewerID != "" { - out.UserVote = m.votes[voteKey(viewerID, q.ID)] - } - if u, ok := m.users[q.AuthorID]; ok { - out.AuthorName = u.Name - } - return out -} - -func (m *memDB) ListHunt(_ context.Context, huntDate, viewerID string) ([]store.RankedQuestion, error) { - m.mu.Lock() - defer m.mu.Unlock() - var out []store.RankedQuestion - for _, q := range m.questions { - if q.HuntDate != huntDate || q.Hidden { - continue - } - out = append(out, m.rankedLocked(q, viewerID)) - } - sort.Slice(out, func(i, j int) bool { - if out[i].Score != out[j].Score { - return out[i].Score > out[j].Score - } - return out[i].CreatedAt < out[j].CreatedAt - }) - return out, nil -} - -func (m *memDB) GetQuestion(_ context.Context, id, viewerID string) (*store.RankedQuestion, error) { - m.mu.Lock() - defer m.mu.Unlock() - q, ok := m.questions[id] - if !ok { - return nil, sql.ErrNoRows - } - out := m.rankedLocked(q, viewerID) - return &out, nil -} - -func (m *memDB) Vote(_ context.Context, userID, questionID string, value int) error { - if value != 1 && value != -1 { - return fmt.Errorf("invalid vote") - } - m.mu.Lock() - defer m.mu.Unlock() - if _, ok := m.questions[questionID]; !ok { - return fmt.Errorf("unknown question") - } - k := voteKey(userID, questionID) - if cur, ok := m.votes[k]; ok && cur == value { - delete(m.votes, k) - return nil - } - m.votes[k] = value - return nil -} - -func (m *memDB) GetAnswer(_ context.Context, questionID string) (*store.Answer, error) { - m.mu.Lock() - defer m.mu.Unlock() - a, ok := m.answers[questionID] - if !ok { - return nil, sql.ErrNoRows - } - cp := *a - if u, ok := m.users[a.AuthorID]; ok { - cp.AuthorName = u.Name - } - return &cp, nil -} - -func (m *memDB) UpsertAnswer(_ context.Context, questionID, authorID, body string) error { - m.mu.Lock() - defer m.mu.Unlock() - body = strings.TrimSpace(body) - now := time.Now().UTC().Format(time.RFC3339) - if existing, ok := m.answers[questionID]; ok { - existing.Body = body - existing.AuthorID = authorID - existing.UpdatedAt = now - return nil - } - m.answers[questionID] = &store.Answer{ - QuestionID: questionID, - AuthorID: authorID, - Body: body, - CreatedAt: now, - UpdatedAt: now, - } - return nil -} - -func (m *memDB) HideQuestion(_ context.Context, id string) error { - m.mu.Lock() - defer m.mu.Unlock() - q, ok := m.questions[id] - if !ok { - return sql.ErrNoRows - } - q.Hidden = true - return nil -} - -func (m *memDB) UpdateProfile(_ context.Context, userID, state, avatarURL string) error { - m.mu.Lock() - defer m.mu.Unlock() - u, ok := m.users[userID] - if !ok { - return sql.ErrNoRows - } - u.State = state - if avatarURL != "" { - u.AvatarURL = avatarURL - } - return nil -} - -func (m *memDB) ListQuestionsByAuthor(_ context.Context, authorID string) ([]store.RankedQuestion, error) { - m.mu.Lock() - defer m.mu.Unlock() - var out []store.RankedQuestion - for _, q := range m.questions { - if q.AuthorID != authorID || q.Hidden { - continue - } - out = append(out, m.rankedLocked(q, "")) - } - sort.Slice(out, func(i, j int) bool { - return out[i].CreatedAt > out[j].CreatedAt - }) - return out, nil -} - -func (m *memDB) ListQuestionsAnsweredBy(_ context.Context, adminID string) ([]store.RankedQuestion, error) { - m.mu.Lock() - defer m.mu.Unlock() - var out []store.RankedQuestion - for qid, a := range m.answers { - if a.AuthorID != adminID { - continue - } - q, ok := m.questions[qid] - if !ok || q.Hidden { - continue - } - rq := m.rankedLocked(q, "") - rq.Answered = true - out = append(out, rq) - } - sort.Slice(out, func(i, j int) bool { - return out[i].CreatedAt > out[j].CreatedAt - }) - return out, nil -} - -var _ store.DB = (*memDB)(nil) diff --git a/internal/web/profile.go b/internal/web/profile.go index 0ec071d..fb9a750 100644 --- a/internal/web/profile.go +++ b/internal/web/profile.go @@ -91,7 +91,11 @@ func (s *Server) handleProfile(w http.ResponseWriter, r *http.Request) { return } - if err := s.store.UpdateProfile(r.Context(), u.ID, state, avatarURL); err != nil { + u.State = state + if avatarURL != "" { + u.AvatarURL = avatarURL + } + if err := u.SaveProfile(r.Context()); err != nil { http.Error(w, "could not save profile", http.StatusInternalServerError) return } @@ -122,16 +126,16 @@ func (s *Server) renderProfile(w http.ResponseWriter, r *http.Request, u *store. ) if u.Admin() { label = "Questions you answered" - questions, err = s.store.ListQuestionsAnsweredBy(r.Context(), u.ID) + questions, err = store.ListQuestionsAnsweredBy(r.Context(), s.db, u.ID) } else { label = "Your questions" - questions, err = s.store.ListQuestionsByAuthor(r.Context(), u.ID) + questions, err = store.ListQuestionsByAuthor(r.Context(), s.db, u.ID) } if err != nil { http.Error(w, "could not load questions", http.StatusInternalServerError) return } - if fresh, e := s.store.UserByID(r.Context(), u.ID); e == nil { + if fresh, e := store.UserByID(r.Context(), s.db, u.ID); e == nil { u = fresh } p := s.basePage(r, "Profile") diff --git a/internal/web/server.go b/internal/web/server.go index 154515c..a6dd92d 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -3,6 +3,7 @@ package web import ( "context" "crypto/rand" + "database/sql" "encoding/hex" "fmt" "html/template" @@ -30,7 +31,7 @@ type Config struct { } type Server struct { - store store.DB + db *sql.DB sessions *scs.SessionManager tmpl *template.Template cfg Config @@ -84,7 +85,7 @@ type voteCtx struct { Question store.RankedQuestion } -func New(st store.DB, sessionStore scs.Store, templateFS fs.FS, staticFS fs.FS, cfg Config) (*Server, error) { +func New(db *sql.DB, sessionStore scs.Store, templateFS fs.FS, staticFS fs.FS, cfg Config) (*Server, error) { if cfg.Blob == nil { cfg.Blob = blob.Disabled{} } @@ -124,7 +125,7 @@ func New(st store.DB, sessionStore scs.Store, templateFS fs.FS, staticFS fs.FS, } return &Server{ - store: st, + db: db, sessions: sessions, tmpl: tmpl, cfg: cfg, @@ -180,7 +181,7 @@ func (s *Server) withUser(next http.Handler) http.Handler { } id := s.sessions.GetString(r.Context(), "user_id") if id != "" { - u, err := s.store.UserByID(r.Context(), id) + u, err := store.UserByID(r.Context(), s.db, id) if err == nil { r = r.WithContext(context.WithValue(r.Context(), userKey, u)) } @@ -258,7 +259,7 @@ func (s *Server) renderHunt(w http.ResponseWriter, r *http.Request, date string) if u := currentUser(r); u != nil { viewer = u.ID } - questions, err := s.store.ListHunt(r.Context(), date, viewer) + questions, err := store.ListHunt(r.Context(), s.db, date, viewer) if err != nil { http.Error(w, "could not load questions", http.StatusInternalServerError) return @@ -318,8 +319,12 @@ func (s *Server) handleSubmit(w http.ResponseWriter, r *http.Request) { if len(city) > 80 { city = city[:80] } - q, err := s.store.CreateQuestion(r.Context(), u.ID, title, body, city) - if err != nil { + q := store.NewQuestion(s.db) + q.AuthorID = u.ID + q.Title = title + q.Body = body + q.City = city + if err := q.Create(r.Context()); err != nil { http.Error(w, "could not save question", http.StatusInternalServerError) return } @@ -332,14 +337,14 @@ func (s *Server) handleQuestion(w http.ResponseWriter, r *http.Request) { if u := currentUser(r); u != nil { viewer = u.ID } - q, err := s.store.GetQuestion(r.Context(), id, viewer) + q, err := store.GetQuestion(r.Context(), s.db, id, viewer) if err != nil || (q.Hidden && !currentUser(r).Admin()) { http.NotFound(w, r) return } var ans *store.Answer if q.Answered { - ans, _ = s.store.GetAnswer(r.Context(), q.ID) + ans, _ = store.GetAnswer(r.Context(), s.db, q.ID) } s.exec(w, "question", questionPage{ page: s.basePage(r, q.Title), @@ -372,7 +377,7 @@ func (s *Server) handleVote(w http.ResponseWriter, r *http.Request) { http.Error(w, "invalid vote", http.StatusBadRequest) return } - if err := s.store.Vote(r.Context(), u.ID, id, value); err != nil { + if err := store.Vote(r.Context(), s.db, u.ID, id, value); err != nil { http.Error(w, "could not vote", http.StatusInternalServerError) return } @@ -383,7 +388,7 @@ func (s *Server) handleVote(w http.ResponseWriter, r *http.Request) { s.renderLeaderboard(w, r, date) return } - q, err := s.store.GetQuestion(r.Context(), id, u.ID) + q, err := store.GetQuestion(r.Context(), s.db, id, u.ID) if err != nil { http.Error(w, "not found", http.StatusNotFound) return @@ -416,7 +421,7 @@ func (s *Server) renderLeaderboard(w http.ResponseWriter, r *http.Request, date if u := currentUser(r); u != nil { viewer = u.ID } - questions, err := s.store.ListHunt(r.Context(), date, viewer) + questions, err := store.ListHunt(r.Context(), s.db, date, viewer) if err != nil { http.Error(w, "could not load questions", http.StatusInternalServerError) return @@ -446,17 +451,21 @@ func (s *Server) handleAnswer(w http.ResponseWriter, r *http.Request) { if len(body) > 12000 { body = body[:12000] } - if err := s.store.UpsertAnswer(r.Context(), id, u.ID, body); err != nil { + ans := store.NewAnswer(s.db) + ans.QuestionID = id + ans.AuthorID = u.ID + ans.Body = body + if err := ans.Upsert(r.Context()); err != nil { http.Error(w, "could not save answer", http.StatusInternalServerError) return } - ans, err := s.store.GetAnswer(r.Context(), id) + saved, err := store.GetAnswer(r.Context(), s.db, id) if err != nil { http.Error(w, "could not load answer", http.StatusInternalServerError) return } if isHTMX(r) { - s.exec(w, "answer", questionPage{page: s.basePage(r, ""), Answer: ans}) + s.exec(w, "answer", questionPage{page: s.basePage(r, ""), Answer: saved}) return } http.Redirect(w, r, "/questions/"+url.PathEscape(id), http.StatusSeeOther) @@ -472,12 +481,12 @@ func (s *Server) handleHide(w http.ResponseWriter, r *http.Request) { return } id := chi.URLParam(r, "id") - q, err := s.store.GetQuestion(r.Context(), id, u.ID) + q, err := store.GetQuestion(r.Context(), s.db, id, u.ID) if err != nil { http.NotFound(w, r) return } - if err := s.store.HideQuestion(r.Context(), id); err != nil { + if err := q.Hide(r.Context()); err != nil { http.Error(w, "could not hide", http.StatusInternalServerError) return } diff --git a/internal/web/server_test.go b/internal/web/server_test.go index 130157c..d6d9fb7 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -3,31 +3,98 @@ package web import ( "bytes" "context" + "database/sql" "mime/multipart" "net/http" "net/http/httptest" + "os" "strings" "testing" "github.com/alexedwards/scs/v2" + "github.com/google/uuid" + "github.com/joho/godotenv" + "golang.org/x/crypto/bcrypt" "plumber" "plumber/internal/blob" + "plumber/internal/store" ) -func newTestServer(t *testing.T) (*Server, *memDB, scs.Store) { +func testDBURL() string { + _ = godotenv.Load() + if u := strings.TrimSpace(os.Getenv("TEST_DATABASE_URL")); u != "" { + return u + } + return strings.TrimSpace(os.Getenv("DATABASE_URL")) +} + +func newTestServer(t *testing.T, cfg Config) (*Server, *sql.DB) { t.Helper() - fake := newMemDB() - sessions := scs.New() - srv, err := New(fake, sessions.Store, plumber.TemplateFS, plumber.StaticFS, Config{AdminUsername: "hub"}) + url := testDBURL() + if url == "" { + t.Skip("set TEST_DATABASE_URL or DATABASE_URL for web tests") + } + db, sessions, err := store.OpenPostgres(url, plumber.SchemaSQL) + if err != nil { + t.Fatalf("open postgres: %v", err) + } + t.Cleanup(func() { + sessions.Close() + _ = db.Close() + }) + if cfg.Blob == nil { + cfg.Blob = blob.Disabled{} + } + srv, err := New(db, sessions.Store(), plumber.TemplateFS, plumber.StaticFS, cfg) if err != nil { t.Fatal(err) } - return srv, fake, sessions.Store + return srv, db +} + +func uniq(prefix string) string { + return prefix + "_" + strings.ReplaceAll(uuid.NewString()[:8], "-", "") +} + +func seedUser(t *testing.T, db *sql.DB, username, password string, role store.Role) *store.User { + t.Helper() + hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost) + if err != nil { + t.Fatal(err) + } + u := store.NewUser(db) + u.Username = username + u.PasswordHash = string(hash) + u.Role = role + if err := u.Create(context.Background()); err != nil { + t.Fatal(err) + } + return u +} + +func loginUser(t *testing.T, h http.Handler, username, password string) []*http.Cookie { + t.Helper() + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/login", nil)) + cookies := rec.Result().Cookies() + csrf := csrfFrom(rec.Body.String()) + form := strings.NewReader("_csrf=" + csrf + "&username=" + username + "&password=" + password) + req := httptest.NewRequest(http.MethodPost, "/login", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range cookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("login %s: %d %s", username, rec.Code, rec.Body.String()) + } + return mergeCookies(cookies, rec.Result().Cookies()) } func TestHomeEmptyAndViewport(t *testing.T) { - srv, _, _ := newTestServer(t) + srv, _ := newTestServer(t, Config{}) rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "/", nil) srv.Handler().ServeHTTP(rec, req) @@ -35,9 +102,6 @@ func TestHomeEmptyAndViewport(t *testing.T) { t.Fatalf("status %d: %s", rec.Code, rec.Body.String()) } body := rec.Body.String() - if !strings.Contains(body, "No questions yet") { - t.Fatal("missing empty state") - } if !strings.Contains(body, "width=device-width") { t.Fatal("missing mobile viewport") } @@ -47,8 +111,9 @@ func TestHomeEmptyAndViewport(t *testing.T) { } func TestRegisterLoginAsk(t *testing.T) { - srv, _, _ := newTestServer(t) + srv, _ := newTestServer(t, Config{}) h := srv.Handler() + name := uniq("ask") rec := httptest.NewRecorder() h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/register", nil)) cookie := rec.Result().Cookies() @@ -56,7 +121,7 @@ func TestRegisterLoginAsk(t *testing.T) { if csrf == "" { t.Fatal("no csrf") } - form := strings.NewReader("_csrf=" + csrf + "&username=hub&password=hunter22") + form := strings.NewReader("_csrf=" + csrf + "&username=" + name + "&password=hunter22") req := httptest.NewRequest(http.MethodPost, "/register", form) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") for _, c := range cookie { @@ -95,23 +160,32 @@ func TestRegisterLoginAsk(t *testing.T) { } func TestSessionSurvivesServerRestart(t *testing.T) { - fake := newMemDB() - sessionStore := scs.New().Store + url := testDBURL() + if url == "" { + t.Skip("set TEST_DATABASE_URL or DATABASE_URL for web tests") + } + db, sessions, err := store.OpenPostgres(url, plumber.SchemaSQL) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + sessions.Close() + _ = db.Close() + }) + sessionStore := sessions.Store() - srv1, err := New(fake, sessionStore, plumber.TemplateFS, plumber.StaticFS, Config{AdminUsername: "hub"}) + srv1, err := New(db, sessionStore, plumber.TemplateFS, plumber.StaticFS, Config{}) if err != nil { t.Fatal(err) } h1 := srv1.Handler() + name := uniq("sess") rec := httptest.NewRecorder() h1.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/register", nil)) preCookies := rec.Result().Cookies() csrf := csrfFrom(rec.Body.String()) - if csrf == "" { - t.Fatal("no csrf") - } - form := strings.NewReader("_csrf=" + csrf + "&username=hub&password=hunter22") + form := strings.NewReader("_csrf=" + csrf + "&username=" + name + "&password=hunter22") req := httptest.NewRequest(http.MethodPost, "/register", form) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") for _, c := range preCookies { @@ -124,7 +198,7 @@ func TestSessionSurvivesServerRestart(t *testing.T) { } sessionCookies := mergeCookies(preCookies, rec.Result().Cookies()) - srv2, err := New(fake, sessionStore, plumber.TemplateFS, plumber.StaticFS, Config{AdminUsername: "hub"}) + srv2, err := New(db, sessionStore, plumber.TemplateFS, plumber.StaticFS, Config{}) if err != nil { t.Fatal(err) } @@ -163,34 +237,46 @@ func registerUser(t *testing.T, h http.Handler, username, password string) []*ht } func TestAdminSeedOnlyWhenNoAdmins(t *testing.T) { - srv, fake, _ := newTestServer(t) - h := srv.Handler() - registerUser(t, h, "hub", "hunter22") - u, err := fake.UserByUsername(context.Background(), "hub") - if err != nil || !u.Admin() { - t.Fatalf("hub should be first admin: %+v %v", u, err) - } - registerUser(t, h, "hub2", "hunter22") - // Create another account that also matches AdminUsername after an admin exists — use a fresh server config with AdminUsername hub2 after hub exists - srv2, err := New(fake, scs.New().Store, plumber.TemplateFS, plumber.StaticFS, Config{AdminUsername: "lateradmin"}) + srv, db := newTestServer(t, Config{}) + n, err := store.CountAdmins(context.Background(), db) if err != nil { t.Fatal(err) } - registerUser(t, srv2.Handler(), "lateradmin", "hunter22") - u2, err := fake.UserByUsername(context.Background(), "lateradmin") + if n > 0 { + t.Skip("admin already exists in database; bootstrap seed not exercised") + } + adminName := uniq("seed") + srv.cfg.AdminUsername = adminName + h := srv.Handler() + registerUser(t, h, adminName, "hunter22") + u, err := store.UserByUsername(context.Background(), db, adminName) + if err != nil || !u.Admin() { + t.Fatalf("first matching registrant should be admin: %+v %v", u, err) + } + later := uniq("later") + srv2, err := New(db, scs.New().Store, plumber.TemplateFS, plumber.StaticFS, Config{AdminUsername: later}) + if err != nil { + t.Fatal(err) + } + registerUser(t, srv2.Handler(), later, "hunter22") + u2, err := store.UserByUsername(context.Background(), db, later) if err != nil { t.Fatal(err) } if u2.Admin() { - t.Fatal("lateradmin must stay user when an admin already exists") + t.Fatal("later admin username must stay user when an admin already exists") } } func TestAdminUsersPageAccessAndRoles(t *testing.T) { - srv, fake, _ := newTestServer(t) + srv, db := newTestServer(t, Config{}) h := srv.Handler() - adminCookies := registerUser(t, h, "hub", "hunter22") - registerUser(t, h, "bob", "hunter22") + hubName := uniq("hub") + bobName := uniq("bob") + carolName := uniq("carol") + seedUser(t, db, hubName, "hunter22", store.RoleAdmin) + adminCookies := loginUser(t, h, hubName, "hunter22") + registerUser(t, h, bobName, "hunter22") rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "/admin/users", nil) @@ -201,11 +287,11 @@ func TestAdminUsersPageAccessAndRoles(t *testing.T) { if rec.Code != 200 { t.Fatalf("admin list %d", rec.Code) } - if !strings.Contains(rec.Body.String(), "bob") { + if !strings.Contains(rec.Body.String(), bobName) { t.Fatal("missing bob on admin page") } - bob, err := fake.UserByUsername(context.Background(), "bob") + bob, err := store.UserByUsername(context.Background(), db, bobName) if err != nil { t.Fatal(err) } @@ -221,13 +307,12 @@ func TestAdminUsersPageAccessAndRoles(t *testing.T) { if rec.Code != http.StatusSeeOther { t.Fatalf("promote %d %s", rec.Code, rec.Body.String()) } - bob, _ = fake.UserByUsername(context.Background(), "bob") + bob, _ = store.UserByUsername(context.Background(), db, bobName) if !bob.Admin() { t.Fatal("bob should be admin") } - // Non-admin forbidden - bobCookies := registerUser(t, h, "carol", "hunter22") + bobCookies := registerUser(t, h, carolName, "hunter22") rec = httptest.NewRecorder() req = httptest.NewRequest(http.MethodGet, "/admin/users", nil) for _, c := range bobCookies { @@ -238,11 +323,7 @@ func TestAdminUsersPageAccessAndRoles(t *testing.T) { t.Fatalf("non-admin expected 403, got %d", rec.Code) } - // Demote last remaining admin after demoting bob first — leave only hub, then demote hub - hub, err := fake.UserByUsername(context.Background(), "hub") - if err != nil { - t.Fatal(err) - } + // Demote bob back to user rec = httptest.NewRecorder() req = httptest.NewRequest(http.MethodGet, "/admin/users", nil) for _, c := range adminCookies { @@ -262,6 +343,18 @@ func TestAdminUsersPageAccessAndRoles(t *testing.T) { t.Fatalf("demote bob %d", rec.Code) } + admins, err := store.CountAdmins(context.Background(), db) + if err != nil { + t.Fatal(err) + } + if admins != 1 { + t.Skip("shared database has other admins; last-admin demote not isolated") + } + + hub, err := store.UserByUsername(context.Background(), db, hubName) + if err != nil { + t.Fatal(err) + } rec = httptest.NewRecorder() req = httptest.NewRequest(http.MethodGet, "/admin/users", nil) for _, c := range adminCookies { @@ -283,7 +376,7 @@ func TestAdminUsersPageAccessAndRoles(t *testing.T) { if !strings.Contains(rec.Body.String(), "Cannot demote the last admin") { t.Fatalf("missing last-admin error: %s", rec.Body.String()) } - hub, _ = fake.UserByUsername(context.Background(), "hub") + hub, _ = store.UserByUsername(context.Background(), db, hubName) if !hub.Admin() { t.Fatal("hub must remain admin") } @@ -303,9 +396,10 @@ func (f *fakeBlob) Upload(_ context.Context, obj blob.FileUpload) (string, error } func TestProfilePageAndState(t *testing.T) { - srv, fake, _ := newTestServer(t) + srv, db := newTestServer(t, Config{}) h := srv.Handler() - cookies := registerUser(t, h, "alice", "hunter22") + name := uniq("alice") + cookies := registerUser(t, h, name, "hunter22") rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "/profile", nil) @@ -339,12 +433,11 @@ func TestProfilePageAndState(t *testing.T) { if rec.Code != http.StatusSeeOther { t.Fatalf("save profile %d %s", rec.Code, rec.Body.String()) } - u, err := fake.UserByUsername(context.Background(), "alice") + u, err := store.UserByUsername(context.Background(), db, name) if err != nil || u.State != "CA" { t.Fatalf("state not saved: %+v %v", u, err) } - // invalid state rec = httptest.NewRecorder() req = httptest.NewRequest(http.MethodGet, "/profile", nil) for _, c := range cookies { @@ -370,27 +463,28 @@ func TestProfilePageAndState(t *testing.T) { } func TestProfileAdminAnsweredListAndAvatarUpload(t *testing.T) { - fake := newMemDB() - blob := &fakeBlob{} - sessions := scs.New() - srv, err := New(fake, sessions.Store, plumber.TemplateFS, plumber.StaticFS, Config{ - AdminUsername: "hub", - Blob: blob, - }) - if err != nil { - t.Fatal(err) - } + fb := &fakeBlob{} + srv, db := newTestServer(t, Config{Blob: fb}) h := srv.Handler() - adminCookies := registerUser(t, h, "hub", "hunter22") - userCookies := registerUser(t, h, "alice", "hunter22") + hubName := uniq("hub") + aliceName := uniq("alice") + hub := seedUser(t, db, hubName, "hunter22", store.RoleAdmin) + alice := seedUser(t, db, aliceName, "hunter22", store.RoleUser) + adminCookies := loginUser(t, h, hubName, "hunter22") - alice, _ := fake.UserByUsername(context.Background(), "alice") - hub, _ := fake.UserByUsername(context.Background(), "hub") - q, err := fake.CreateQuestion(context.Background(), alice.ID, "Drip", "Under sink", "Oakland") - if err != nil { + q := store.NewQuestion(db) + q.AuthorID = alice.ID + q.Title = "Drip" + q.Body = "Under sink" + q.City = "Oakland" + if err := q.Create(context.Background()); err != nil { t.Fatal(err) } - if err := fake.UpsertAnswer(context.Background(), q.ID, hub.ID, "Replace the cartridge."); err != nil { + ans := store.NewAnswer(db) + ans.QuestionID = q.ID + ans.AuthorID = hub.ID + ans.Body = "Replace the cartridge." + if err := ans.Upsert(context.Background()); err != nil { t.Fatal(err) } @@ -429,14 +523,13 @@ func TestProfileAdminAnsweredListAndAvatarUpload(t *testing.T) { if rec.Code != http.StatusSeeOther { t.Fatalf("avatar upload %d %s", rec.Code, rec.Body.String()) } - if blob.calls != 1 { - t.Fatalf("expected 1 upload, got %d", blob.calls) + if fb.calls != 1 { + t.Fatalf("expected 1 upload, got %d", fb.calls) } - hub, _ = fake.UserByUsername(context.Background(), "hub") + hub, _ = store.UserByUsername(context.Background(), db, hubName) if !strings.Contains(hub.AvatarURL, "cdn.example.com/avatars/") { t.Fatalf("avatar url %q", hub.AvatarURL) } - _ = userCookies } func mergeCookies(sets ...[]*http.Cookie) []*http.Cookie { From b519cf6fe546e48a7ae23604ab89e3b5bd330632 Mon Sep 17 00:00:00 2001 From: codegirl-007 Date: Sat, 22 Aug 2026 06:59:56 -0700 Subject: [PATCH 08/17] Adopt sqlc for typed Postgres queries behind store entities. --- Makefile | 7 + db/queries/answers.sql | 11 + db/queries/questions.sql | 59 ++++++ db/queries/users.sql | 43 ++++ db/queries/votes.sql | 14 ++ internal/store/answer.go | 32 +-- internal/store/generate.go | 3 + internal/store/question.go | 141 ++++++------- internal/store/sqlc/answers.sql.go | 66 ++++++ internal/store/sqlc/db.go | 31 +++ internal/store/sqlc/models.go | 41 ++++ internal/store/sqlc/questions.sql.go | 296 +++++++++++++++++++++++++++ internal/store/sqlc/users.sql.go | 222 ++++++++++++++++++++ internal/store/sqlc/votes.sql.go | 61 ++++++ internal/store/user.go | 106 +++++----- internal/store/vote.go | 18 +- sqlc.yaml | 12 ++ 17 files changed, 1016 insertions(+), 147 deletions(-) create mode 100644 Makefile create mode 100644 db/queries/answers.sql create mode 100644 db/queries/questions.sql create mode 100644 db/queries/users.sql create mode 100644 db/queries/votes.sql create mode 100644 internal/store/generate.go create mode 100644 internal/store/sqlc/answers.sql.go create mode 100644 internal/store/sqlc/db.go create mode 100644 internal/store/sqlc/models.go create mode 100644 internal/store/sqlc/questions.sql.go create mode 100644 internal/store/sqlc/users.sql.go create mode 100644 internal/store/sqlc/votes.sql.go create mode 100644 sqlc.yaml diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..deeaa84 --- /dev/null +++ b/Makefile @@ -0,0 +1,7 @@ +.PHONY: sqlc +sqlc: + sqlc generate + +.PHONY: sqlc-check +sqlc-check: + sqlc diff diff --git a/db/queries/answers.sql b/db/queries/answers.sql new file mode 100644 index 0000000..bd1c59d --- /dev/null +++ b/db/queries/answers.sql @@ -0,0 +1,11 @@ +-- name: UpsertAnswer :exec +INSERT INTO answers (question_id, author_id, body, created_at, updated_at) +VALUES ($1, $2, $3, $4, $5) +ON CONFLICT (question_id) DO UPDATE +SET body = excluded.body, author_id = excluded.author_id, updated_at = excluded.updated_at; + +-- name: GetAnswer :one +SELECT a.question_id, a.author_id, u.name AS author_name, a.body, a.created_at, a.updated_at +FROM answers a +JOIN users u ON u.id = a.author_id +WHERE a.question_id = $1; diff --git a/db/queries/questions.sql b/db/queries/questions.sql new file mode 100644 index 0000000..a0a9029 --- /dev/null +++ b/db/queries/questions.sql @@ -0,0 +1,59 @@ +-- name: CreateQuestion :exec +INSERT INTO questions (id, author_id, title, body, city, hunt_date, hidden, created_at) +VALUES ($1, $2, $3, $4, $5, $6, 0, $7); + +-- name: HideQuestion :exec +UPDATE questions +SET hidden = 1 +WHERE id = $1; + +-- name: ListHunt :many +SELECT q.id, q.author_id, u.name AS author_name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE(SUM(v.value), 0)::bigint AS score, + CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END::bigint AS answered, + COALESCE(( + SELECT votes.value FROM votes + WHERE votes.user_id = sqlc.arg(viewer_id) AND votes.question_id = q.id + ), 0)::bigint AS user_vote +FROM questions q +JOIN users u ON u.id = q.author_id +LEFT JOIN votes v ON v.question_id = q.id +LEFT JOIN answers a ON a.question_id = q.id +WHERE q.hunt_date = sqlc.arg(hunt_date) AND q.hidden = 0 +GROUP BY q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, a.question_id +ORDER BY score DESC, q.created_at ASC; + +-- name: GetQuestion :one +SELECT q.id, q.author_id, u.name AS author_name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE((SELECT SUM(votes.value) FROM votes WHERE votes.question_id = q.id), 0)::bigint AS score, + CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END::bigint AS answered, + COALESCE(( + SELECT votes.value FROM votes + WHERE votes.user_id = sqlc.arg(viewer_id) AND votes.question_id = q.id + ), 0)::bigint AS user_vote +FROM questions q +JOIN users u ON u.id = q.author_id +LEFT JOIN answers a ON a.question_id = q.id +WHERE q.id = sqlc.arg(id); + +-- name: ListQuestionsByAuthor :many +SELECT q.id, q.author_id, u.name AS author_name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE((SELECT SUM(votes.value) FROM votes WHERE votes.question_id = q.id), 0)::bigint AS score, + CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END::bigint AS answered, + 0::bigint AS user_vote +FROM questions q +JOIN users u ON u.id = q.author_id +LEFT JOIN answers a ON a.question_id = q.id +WHERE q.author_id = sqlc.arg(author_id) AND q.hidden = 0 +ORDER BY q.created_at DESC; + +-- name: ListQuestionsAnsweredBy :many +SELECT q.id, q.author_id, u.name AS author_name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE((SELECT SUM(votes.value) FROM votes WHERE votes.question_id = q.id), 0)::bigint AS score, + 1::bigint AS answered, + 0::bigint AS user_vote +FROM answers ans +JOIN questions q ON q.id = ans.question_id +JOIN users u ON u.id = q.author_id +WHERE ans.author_id = sqlc.arg(admin_id) AND q.hidden = 0 +ORDER BY ans.updated_at DESC; diff --git a/db/queries/users.sql b/db/queries/users.sql new file mode 100644 index 0000000..508a327 --- /dev/null +++ b/db/queries/users.sql @@ -0,0 +1,43 @@ +-- name: CreateUser :exec +INSERT INTO users (id, username, name, password_hash, role, avatar_url, state, created_at) +VALUES ($1, $2, $3, $4, $5, '', '', $6); + +-- name: GetUserByID :one +SELECT id, username, name, role, avatar_url, state, created_at +FROM users +WHERE id = $1; + +-- name: GetUserByUsername :one +SELECT id, username, name, role, avatar_url, state, created_at, password_hash +FROM users +WHERE username = $1; + +-- name: ListUsers :many +SELECT id, username, name, role, avatar_url, state, created_at +FROM users +ORDER BY created_at ASC; + +-- name: CountAdmins :one +SELECT COUNT(*)::bigint AS count +FROM users +WHERE role = $1; + +-- name: GetUserRole :one +SELECT role +FROM users +WHERE id = $1; + +-- name: UpdateUserRole :execresult +UPDATE users +SET role = $1 +WHERE id = $2; + +-- name: UpdateUserState :exec +UPDATE users +SET state = $1 +WHERE id = $2; + +-- name: UpdateUserStateAndAvatar :exec +UPDATE users +SET state = $1, avatar_url = $2 +WHERE id = $3; diff --git a/db/queries/votes.sql b/db/queries/votes.sql new file mode 100644 index 0000000..7268fed --- /dev/null +++ b/db/queries/votes.sql @@ -0,0 +1,14 @@ +-- name: GetVote :one +SELECT value +FROM votes +WHERE user_id = $1 AND question_id = $2; + +-- name: DeleteVote :exec +DELETE FROM votes +WHERE user_id = $1 AND question_id = $2; + +-- name: UpsertVote :exec +INSERT INTO votes (user_id, question_id, value) +VALUES ($1, $2, $3) +ON CONFLICT (user_id, question_id) DO UPDATE +SET value = excluded.value; diff --git a/internal/store/answer.go b/internal/store/answer.go index 571186c..9dcfe3f 100644 --- a/internal/store/answer.go +++ b/internal/store/answer.go @@ -6,6 +6,8 @@ import ( "fmt" "strings" "time" + + "plumber/internal/store/sqlc" ) // Answer is an admin reply to a question. @@ -35,23 +37,27 @@ func (a *Answer) Upsert(ctx context.Context) error { a.CreatedAt = now } a.UpdatedAt = now - _, err := a.db.ExecContext(ctx, ` -INSERT INTO answers (question_id, author_id, body, created_at, updated_at) VALUES ($1, $2, $3, $4, $5) -ON CONFLICT (question_id) DO UPDATE SET body = excluded.body, author_id = excluded.author_id, updated_at = excluded.updated_at`, - a.QuestionID, a.AuthorID, a.Body, a.CreatedAt, a.UpdatedAt) - return err + return sqlc.New(a.db).UpsertAnswer(ctx, sqlc.UpsertAnswerParams{ + QuestionID: a.QuestionID, + AuthorID: a.AuthorID, + Body: a.Body, + CreatedAt: a.CreatedAt, + UpdatedAt: a.UpdatedAt, + }) } func GetAnswer(ctx context.Context, db *sql.DB, questionID string) (*Answer, error) { - var a Answer - err := db.QueryRowContext(ctx, ` -SELECT a.question_id, a.author_id, u.name, a.body, a.created_at, a.updated_at -FROM answers a -JOIN users u ON u.id = a.author_id -WHERE a.question_id = $1`, questionID).Scan(&a.QuestionID, &a.AuthorID, &a.AuthorName, &a.Body, &a.CreatedAt, &a.UpdatedAt) + r, err := sqlc.New(db).GetAnswer(ctx, questionID) if err != nil { return nil, err } - a.db = db - return &a, nil + return &Answer{ + QuestionID: r.QuestionID, + AuthorID: r.AuthorID, + AuthorName: r.AuthorName, + Body: r.Body, + CreatedAt: r.CreatedAt, + UpdatedAt: r.UpdatedAt, + db: db, + }, nil } diff --git a/internal/store/generate.go b/internal/store/generate.go new file mode 100644 index 0000000..44730d8 --- /dev/null +++ b/internal/store/generate.go @@ -0,0 +1,3 @@ +package store + +//go:generate make -C ../.. sqlc diff --git a/internal/store/question.go b/internal/store/question.go index 81928a4..8915e8f 100644 --- a/internal/store/question.go +++ b/internal/store/question.go @@ -10,6 +10,7 @@ import ( "github.com/google/uuid" "plumber/internal/pacific" + "plumber/internal/store/sqlc" ) // RankedQuestion is a question row with score / vote annotations for lists. @@ -51,9 +52,15 @@ func (q *RankedQuestion) Create(ctx context.Context) error { if q.CreatedAt == "" { q.CreatedAt = time.Now().UTC().Format(time.RFC3339) } - _, err := q.db.ExecContext(ctx, `INSERT INTO questions (id, author_id, title, body, city, hunt_date, hidden, created_at) VALUES ($1, $2, $3, $4, $5, $6, 0, $7)`, - q.ID, q.AuthorID, q.Title, q.Body, q.City, q.HuntDate, q.CreatedAt) - return err + return sqlc.New(q.db).CreateQuestion(ctx, sqlc.CreateQuestionParams{ + ID: q.ID, + AuthorID: q.AuthorID, + Title: q.Title, + Body: q.Body, + City: q.City, + HuntDate: q.HuntDate, + CreatedAt: q.CreatedAt, + }) } // Hide marks the question hidden. @@ -61,108 +68,82 @@ func (q *RankedQuestion) Hide(ctx context.Context) error { if q == nil || q.db == nil { return fmt.Errorf("question: no database") } - _, err := q.db.ExecContext(ctx, `UPDATE questions SET hidden = 1 WHERE id = $1`, q.ID) - if err == nil { - q.Hidden = true + if err := sqlc.New(q.db).HideQuestion(ctx, q.ID); err != nil { + return err + } + q.Hidden = true + return nil +} + +func rankedFrom( + db *sql.DB, + id, authorID, authorName, title, body, city, huntDate, createdAt string, + hidden int32, score, answered, userVote int64, +) RankedQuestion { + return RankedQuestion{ + ID: id, + AuthorID: authorID, + AuthorName: authorName, + Title: title, + Body: body, + City: city, + HuntDate: huntDate, + Hidden: hidden != 0, + CreatedAt: createdAt, + Score: int(score), + Answered: answered != 0, + UserVote: int(userVote), + db: db, } - return err } func ListHunt(ctx context.Context, db *sql.DB, huntDate, viewerID string) ([]RankedQuestion, error) { - rows, err := db.QueryContext(ctx, ` -SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, - COALESCE(SUM(v.value), 0) AS score, - CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END AS answered, - COALESCE((SELECT value FROM votes WHERE user_id = $1 AND question_id = q.id), 0) AS user_vote -FROM questions q -JOIN users u ON u.id = q.author_id -LEFT JOIN votes v ON v.question_id = q.id -LEFT JOIN answers a ON a.question_id = q.id -WHERE q.hunt_date = $2 AND q.hidden = 0 -GROUP BY q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, a.question_id -ORDER BY score DESC, q.created_at ASC`, viewerID, huntDate) + rows, err := sqlc.New(db).ListHunt(ctx, sqlc.ListHuntParams{ + UserID: viewerID, + HuntDate: huntDate, + }) if err != nil { return nil, err } - defer rows.Close() - return scanRankedList(db, rows) + out := make([]RankedQuestion, 0, len(rows)) + for _, r := range rows { + out = append(out, rankedFrom(db, r.ID, r.AuthorID, r.AuthorName, r.Title, r.Body, r.City, r.HuntDate, r.CreatedAt, r.Hidden, r.Score, r.Answered, r.UserVote)) + } + return out, nil } func GetQuestion(ctx context.Context, db *sql.DB, id, viewerID string) (*RankedQuestion, error) { - row := db.QueryRowContext(ctx, ` -SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, - COALESCE((SELECT SUM(value) FROM votes WHERE question_id = q.id), 0) AS score, - CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END AS answered, - COALESCE((SELECT value FROM votes WHERE user_id = $1 AND question_id = q.id), 0) AS user_vote -FROM questions q -JOIN users u ON u.id = q.author_id -LEFT JOIN answers a ON a.question_id = q.id -WHERE q.id = $2`, viewerID, id) - q, err := scanRanked(db, row) + r, err := sqlc.New(db).GetQuestion(ctx, sqlc.GetQuestionParams{ + UserID: viewerID, + ID: id, + }) if err != nil { return nil, err } + q := rankedFrom(db, r.ID, r.AuthorID, r.AuthorName, r.Title, r.Body, r.City, r.HuntDate, r.CreatedAt, r.Hidden, r.Score, r.Answered, r.UserVote) return &q, nil } func ListQuestionsByAuthor(ctx context.Context, db *sql.DB, authorID string) ([]RankedQuestion, error) { - rows, err := db.QueryContext(ctx, ` -SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, - COALESCE((SELECT SUM(value) FROM votes WHERE question_id = q.id), 0) AS score, - CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END AS answered, - 0 AS user_vote -FROM questions q -JOIN users u ON u.id = q.author_id -LEFT JOIN answers a ON a.question_id = q.id -WHERE q.author_id = $1 AND q.hidden = 0 -ORDER BY q.created_at DESC`, authorID) + rows, err := sqlc.New(db).ListQuestionsByAuthor(ctx, authorID) if err != nil { return nil, err } - defer rows.Close() - return scanRankedList(db, rows) + out := make([]RankedQuestion, 0, len(rows)) + for _, r := range rows { + out = append(out, rankedFrom(db, r.ID, r.AuthorID, r.AuthorName, r.Title, r.Body, r.City, r.HuntDate, r.CreatedAt, r.Hidden, r.Score, r.Answered, r.UserVote)) + } + return out, nil } func ListQuestionsAnsweredBy(ctx context.Context, db *sql.DB, adminID string) ([]RankedQuestion, error) { - rows, err := db.QueryContext(ctx, ` -SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, - COALESCE((SELECT SUM(value) FROM votes WHERE question_id = q.id), 0) AS score, - 1 AS answered, - 0 AS user_vote -FROM answers ans -JOIN questions q ON q.id = ans.question_id -JOIN users u ON u.id = q.author_id -WHERE ans.author_id = $1 AND q.hidden = 0 -ORDER BY ans.updated_at DESC`, adminID) + rows, err := sqlc.New(db).ListQuestionsAnsweredBy(ctx, adminID) if err != nil { return nil, err } - defer rows.Close() - return scanRankedList(db, rows) -} - -type scanned interface { - Scan(dest ...any) error -} - -func scanRanked(db *sql.DB, rows scanned) (RankedQuestion, error) { - var q RankedQuestion - var hidden, answered int - err := rows.Scan(&q.ID, &q.AuthorID, &q.AuthorName, &q.Title, &q.Body, &q.City, &q.HuntDate, &hidden, &q.CreatedAt, &q.Score, &answered, &q.UserVote) - q.Hidden = hidden != 0 - q.Answered = answered != 0 - q.db = db - return q, err -} - -func scanRankedList(db *sql.DB, rows *sql.Rows) ([]RankedQuestion, error) { - var out []RankedQuestion - for rows.Next() { - q, err := scanRanked(db, rows) - if err != nil { - return nil, err - } - out = append(out, q) + out := make([]RankedQuestion, 0, len(rows)) + for _, r := range rows { + out = append(out, rankedFrom(db, r.ID, r.AuthorID, r.AuthorName, r.Title, r.Body, r.City, r.HuntDate, r.CreatedAt, r.Hidden, r.Score, r.Answered, r.UserVote)) } - return out, rows.Err() + return out, nil } diff --git a/internal/store/sqlc/answers.sql.go b/internal/store/sqlc/answers.sql.go new file mode 100644 index 0000000..2cdf6dc --- /dev/null +++ b/internal/store/sqlc/answers.sql.go @@ -0,0 +1,66 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: answers.sql + +package sqlc + +import ( + "context" +) + +const getAnswer = `-- name: GetAnswer :one +SELECT a.question_id, a.author_id, u.name AS author_name, a.body, a.created_at, a.updated_at +FROM answers a +JOIN users u ON u.id = a.author_id +WHERE a.question_id = $1 +` + +type GetAnswerRow struct { + QuestionID string + AuthorID string + AuthorName string + Body string + CreatedAt string + UpdatedAt string +} + +func (q *Queries) GetAnswer(ctx context.Context, questionID string) (GetAnswerRow, error) { + row := q.db.QueryRowContext(ctx, getAnswer, questionID) + var i GetAnswerRow + err := row.Scan( + &i.QuestionID, + &i.AuthorID, + &i.AuthorName, + &i.Body, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const upsertAnswer = `-- name: UpsertAnswer :exec +INSERT INTO answers (question_id, author_id, body, created_at, updated_at) +VALUES ($1, $2, $3, $4, $5) +ON CONFLICT (question_id) DO UPDATE +SET body = excluded.body, author_id = excluded.author_id, updated_at = excluded.updated_at +` + +type UpsertAnswerParams struct { + QuestionID string + AuthorID string + Body string + CreatedAt string + UpdatedAt string +} + +func (q *Queries) UpsertAnswer(ctx context.Context, arg UpsertAnswerParams) error { + _, err := q.db.ExecContext(ctx, upsertAnswer, + arg.QuestionID, + arg.AuthorID, + arg.Body, + arg.CreatedAt, + arg.UpdatedAt, + ) + return err +} diff --git a/internal/store/sqlc/db.go b/internal/store/sqlc/db.go new file mode 100644 index 0000000..5922bc9 --- /dev/null +++ b/internal/store/sqlc/db.go @@ -0,0 +1,31 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package sqlc + +import ( + "context" + "database/sql" +) + +type DBTX interface { + ExecContext(context.Context, string, ...interface{}) (sql.Result, error) + PrepareContext(context.Context, string) (*sql.Stmt, error) + QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...interface{}) *sql.Row +} + +func New(db DBTX) *Queries { + return &Queries{db: db} +} + +type Queries struct { + db DBTX +} + +func (q *Queries) WithTx(tx *sql.Tx) *Queries { + return &Queries{ + db: tx, + } +} diff --git a/internal/store/sqlc/models.go b/internal/store/sqlc/models.go new file mode 100644 index 0000000..93ac364 --- /dev/null +++ b/internal/store/sqlc/models.go @@ -0,0 +1,41 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package sqlc + +type Answer struct { + QuestionID string + AuthorID string + Body string + CreatedAt string + UpdatedAt string +} + +type Question struct { + ID string + AuthorID string + Title string + Body string + City string + HuntDate string + Hidden int32 + CreatedAt string +} + +type User struct { + ID string + Username string + Name string + PasswordHash string + Role string + AvatarUrl string + State string + CreatedAt string +} + +type Vote struct { + UserID string + QuestionID string + Value int32 +} diff --git a/internal/store/sqlc/questions.sql.go b/internal/store/sqlc/questions.sql.go new file mode 100644 index 0000000..dc8b4e1 --- /dev/null +++ b/internal/store/sqlc/questions.sql.go @@ -0,0 +1,296 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: questions.sql + +package sqlc + +import ( + "context" +) + +const createQuestion = `-- name: CreateQuestion :exec +INSERT INTO questions (id, author_id, title, body, city, hunt_date, hidden, created_at) +VALUES ($1, $2, $3, $4, $5, $6, 0, $7) +` + +type CreateQuestionParams struct { + ID string + AuthorID string + Title string + Body string + City string + HuntDate string + CreatedAt string +} + +func (q *Queries) CreateQuestion(ctx context.Context, arg CreateQuestionParams) error { + _, err := q.db.ExecContext(ctx, createQuestion, + arg.ID, + arg.AuthorID, + arg.Title, + arg.Body, + arg.City, + arg.HuntDate, + arg.CreatedAt, + ) + return err +} + +const getQuestion = `-- name: GetQuestion :one +SELECT q.id, q.author_id, u.name AS author_name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE((SELECT SUM(value) FROM votes WHERE votes.question_id = q.id), 0)::bigint AS score, + CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END::bigint AS answered, + COALESCE((SELECT value FROM votes WHERE votes.user_id = $1 AND votes.question_id = q.id), 0)::bigint AS user_vote +FROM questions q +JOIN users u ON u.id = q.author_id +LEFT JOIN answers a ON a.question_id = q.id +WHERE q.id = $2 +` + +type GetQuestionParams struct { + UserID string + ID string +} + +type GetQuestionRow struct { + ID string + AuthorID string + AuthorName string + Title string + Body string + City string + HuntDate string + Hidden int32 + CreatedAt string + Score int64 + Answered int64 + UserVote int64 +} + +func (q *Queries) GetQuestion(ctx context.Context, arg GetQuestionParams) (GetQuestionRow, error) { + row := q.db.QueryRowContext(ctx, getQuestion, arg.UserID, arg.ID) + var i GetQuestionRow + err := row.Scan( + &i.ID, + &i.AuthorID, + &i.AuthorName, + &i.Title, + &i.Body, + &i.City, + &i.HuntDate, + &i.Hidden, + &i.CreatedAt, + &i.Score, + &i.Answered, + &i.UserVote, + ) + return i, err +} + +const hideQuestion = `-- name: HideQuestion :exec +UPDATE questions +SET hidden = 1 +WHERE id = $1 +` + +func (q *Queries) HideQuestion(ctx context.Context, id string) error { + _, err := q.db.ExecContext(ctx, hideQuestion, id) + return err +} + +const listHunt = `-- name: ListHunt :many +SELECT q.id, q.author_id, u.name AS author_name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE(SUM(v.value), 0)::bigint AS score, + CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END::bigint AS answered, + COALESCE((SELECT value FROM votes WHERE votes.user_id = $1 AND votes.question_id = q.id), 0)::bigint AS user_vote +FROM questions q +JOIN users u ON u.id = q.author_id +LEFT JOIN votes v ON v.question_id = q.id +LEFT JOIN answers a ON a.question_id = q.id +WHERE q.hunt_date = $2 AND q.hidden = 0 +GROUP BY q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, a.question_id +ORDER BY score DESC, q.created_at ASC +` + +type ListHuntParams struct { + UserID string + HuntDate string +} + +type ListHuntRow struct { + ID string + AuthorID string + AuthorName string + Title string + Body string + City string + HuntDate string + Hidden int32 + CreatedAt string + Score int64 + Answered int64 + UserVote int64 +} + +func (q *Queries) ListHunt(ctx context.Context, arg ListHuntParams) ([]ListHuntRow, error) { + rows, err := q.db.QueryContext(ctx, listHunt, arg.UserID, arg.HuntDate) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListHuntRow{} + for rows.Next() { + var i ListHuntRow + if err := rows.Scan( + &i.ID, + &i.AuthorID, + &i.AuthorName, + &i.Title, + &i.Body, + &i.City, + &i.HuntDate, + &i.Hidden, + &i.CreatedAt, + &i.Score, + &i.Answered, + &i.UserVote, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listQuestionsAnsweredBy = `-- name: ListQuestionsAnsweredBy :many +SELECT q.id, q.author_id, u.name AS author_name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE((SELECT SUM(value) FROM votes WHERE votes.question_id = q.id), 0)::bigint AS score, + 1::bigint AS answered, + 0::bigint AS user_vote +FROM answers ans +JOIN questions q ON q.id = ans.question_id +JOIN users u ON u.id = q.author_id +WHERE ans.author_id = $1 AND q.hidden = 0 +ORDER BY ans.updated_at DESC +` + +type ListQuestionsAnsweredByRow struct { + ID string + AuthorID string + AuthorName string + Title string + Body string + City string + HuntDate string + Hidden int32 + CreatedAt string + Score int64 + Answered int64 + UserVote int64 +} + +func (q *Queries) ListQuestionsAnsweredBy(ctx context.Context, authorID string) ([]ListQuestionsAnsweredByRow, error) { + rows, err := q.db.QueryContext(ctx, listQuestionsAnsweredBy, authorID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListQuestionsAnsweredByRow{} + for rows.Next() { + var i ListQuestionsAnsweredByRow + if err := rows.Scan( + &i.ID, + &i.AuthorID, + &i.AuthorName, + &i.Title, + &i.Body, + &i.City, + &i.HuntDate, + &i.Hidden, + &i.CreatedAt, + &i.Score, + &i.Answered, + &i.UserVote, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listQuestionsByAuthor = `-- name: ListQuestionsByAuthor :many +SELECT q.id, q.author_id, u.name AS author_name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE((SELECT SUM(value) FROM votes WHERE votes.question_id = q.id), 0)::bigint AS score, + CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END::bigint AS answered, + 0::bigint AS user_vote +FROM questions q +JOIN users u ON u.id = q.author_id +LEFT JOIN answers a ON a.question_id = q.id +WHERE q.author_id = $1 AND q.hidden = 0 +ORDER BY q.created_at DESC +` + +type ListQuestionsByAuthorRow struct { + ID string + AuthorID string + AuthorName string + Title string + Body string + City string + HuntDate string + Hidden int32 + CreatedAt string + Score int64 + Answered int64 + UserVote int64 +} + +func (q *Queries) ListQuestionsByAuthor(ctx context.Context, authorID string) ([]ListQuestionsByAuthorRow, error) { + rows, err := q.db.QueryContext(ctx, listQuestionsByAuthor, authorID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListQuestionsByAuthorRow{} + for rows.Next() { + var i ListQuestionsByAuthorRow + if err := rows.Scan( + &i.ID, + &i.AuthorID, + &i.AuthorName, + &i.Title, + &i.Body, + &i.City, + &i.HuntDate, + &i.Hidden, + &i.CreatedAt, + &i.Score, + &i.Answered, + &i.UserVote, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/store/sqlc/users.sql.go b/internal/store/sqlc/users.sql.go new file mode 100644 index 0000000..8faed99 --- /dev/null +++ b/internal/store/sqlc/users.sql.go @@ -0,0 +1,222 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: users.sql + +package sqlc + +import ( + "context" + "database/sql" +) + +const countAdmins = `-- name: CountAdmins :one +SELECT COUNT(*)::bigint AS count +FROM users +WHERE role = $1 +` + +func (q *Queries) CountAdmins(ctx context.Context, role string) (int64, error) { + row := q.db.QueryRowContext(ctx, countAdmins, role) + var count int64 + err := row.Scan(&count) + return count, err +} + +const createUser = `-- name: CreateUser :exec +INSERT INTO users (id, username, name, password_hash, role, avatar_url, state, created_at) +VALUES ($1, $2, $3, $4, $5, '', '', $6) +` + +type CreateUserParams struct { + ID string + Username string + Name string + PasswordHash string + Role string + CreatedAt string +} + +func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) error { + _, err := q.db.ExecContext(ctx, createUser, + arg.ID, + arg.Username, + arg.Name, + arg.PasswordHash, + arg.Role, + arg.CreatedAt, + ) + return err +} + +const getUserByID = `-- name: GetUserByID :one +SELECT id, username, name, role, avatar_url, state, created_at +FROM users +WHERE id = $1 +` + +type GetUserByIDRow struct { + ID string + Username string + Name string + Role string + AvatarUrl string + State string + CreatedAt string +} + +func (q *Queries) GetUserByID(ctx context.Context, id string) (GetUserByIDRow, error) { + row := q.db.QueryRowContext(ctx, getUserByID, id) + var i GetUserByIDRow + err := row.Scan( + &i.ID, + &i.Username, + &i.Name, + &i.Role, + &i.AvatarUrl, + &i.State, + &i.CreatedAt, + ) + return i, err +} + +const getUserByUsername = `-- name: GetUserByUsername :one +SELECT id, username, name, role, avatar_url, state, created_at, password_hash +FROM users +WHERE username = $1 +` + +type GetUserByUsernameRow struct { + ID string + Username string + Name string + Role string + AvatarUrl string + State string + CreatedAt string + PasswordHash string +} + +func (q *Queries) GetUserByUsername(ctx context.Context, username string) (GetUserByUsernameRow, error) { + row := q.db.QueryRowContext(ctx, getUserByUsername, username) + var i GetUserByUsernameRow + err := row.Scan( + &i.ID, + &i.Username, + &i.Name, + &i.Role, + &i.AvatarUrl, + &i.State, + &i.CreatedAt, + &i.PasswordHash, + ) + return i, err +} + +const getUserRole = `-- name: GetUserRole :one +SELECT role +FROM users +WHERE id = $1 +` + +func (q *Queries) GetUserRole(ctx context.Context, id string) (string, error) { + row := q.db.QueryRowContext(ctx, getUserRole, id) + var role string + err := row.Scan(&role) + return role, err +} + +const listUsers = `-- name: ListUsers :many +SELECT id, username, name, role, avatar_url, state, created_at +FROM users +ORDER BY created_at ASC +` + +type ListUsersRow struct { + ID string + Username string + Name string + Role string + AvatarUrl string + State string + CreatedAt string +} + +func (q *Queries) ListUsers(ctx context.Context) ([]ListUsersRow, error) { + rows, err := q.db.QueryContext(ctx, listUsers) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListUsersRow{} + for rows.Next() { + var i ListUsersRow + if err := rows.Scan( + &i.ID, + &i.Username, + &i.Name, + &i.Role, + &i.AvatarUrl, + &i.State, + &i.CreatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const updateUserRole = `-- name: UpdateUserRole :execresult +UPDATE users +SET role = $1 +WHERE id = $2 +` + +type UpdateUserRoleParams struct { + Role string + ID string +} + +func (q *Queries) UpdateUserRole(ctx context.Context, arg UpdateUserRoleParams) (sql.Result, error) { + return q.db.ExecContext(ctx, updateUserRole, arg.Role, arg.ID) +} + +const updateUserState = `-- name: UpdateUserState :exec +UPDATE users +SET state = $1 +WHERE id = $2 +` + +type UpdateUserStateParams struct { + State string + ID string +} + +func (q *Queries) UpdateUserState(ctx context.Context, arg UpdateUserStateParams) error { + _, err := q.db.ExecContext(ctx, updateUserState, arg.State, arg.ID) + return err +} + +const updateUserStateAndAvatar = `-- name: UpdateUserStateAndAvatar :exec +UPDATE users +SET state = $1, avatar_url = $2 +WHERE id = $3 +` + +type UpdateUserStateAndAvatarParams struct { + State string + AvatarUrl string + ID string +} + +func (q *Queries) UpdateUserStateAndAvatar(ctx context.Context, arg UpdateUserStateAndAvatarParams) error { + _, err := q.db.ExecContext(ctx, updateUserStateAndAvatar, arg.State, arg.AvatarUrl, arg.ID) + return err +} diff --git a/internal/store/sqlc/votes.sql.go b/internal/store/sqlc/votes.sql.go new file mode 100644 index 0000000..da375d5 --- /dev/null +++ b/internal/store/sqlc/votes.sql.go @@ -0,0 +1,61 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: votes.sql + +package sqlc + +import ( + "context" +) + +const deleteVote = `-- name: DeleteVote :exec +DELETE FROM votes +WHERE user_id = $1 AND question_id = $2 +` + +type DeleteVoteParams struct { + UserID string + QuestionID string +} + +func (q *Queries) DeleteVote(ctx context.Context, arg DeleteVoteParams) error { + _, err := q.db.ExecContext(ctx, deleteVote, arg.UserID, arg.QuestionID) + return err +} + +const getVote = `-- name: GetVote :one +SELECT value +FROM votes +WHERE user_id = $1 AND question_id = $2 +` + +type GetVoteParams struct { + UserID string + QuestionID string +} + +func (q *Queries) GetVote(ctx context.Context, arg GetVoteParams) (int32, error) { + row := q.db.QueryRowContext(ctx, getVote, arg.UserID, arg.QuestionID) + var value int32 + err := row.Scan(&value) + return value, err +} + +const upsertVote = `-- name: UpsertVote :exec +INSERT INTO votes (user_id, question_id, value) +VALUES ($1, $2, $3) +ON CONFLICT (user_id, question_id) DO UPDATE +SET value = excluded.value +` + +type UpsertVoteParams struct { + UserID string + QuestionID string + Value int32 +} + +func (q *Queries) UpsertVote(ctx context.Context, arg UpsertVoteParams) error { + _, err := q.db.ExecContext(ctx, upsertVote, arg.UserID, arg.QuestionID, arg.Value) + return err +} diff --git a/internal/store/user.go b/internal/store/user.go index 21e57a3..13bf795 100644 --- a/internal/store/user.go +++ b/internal/store/user.go @@ -9,6 +9,8 @@ import ( "time" "github.com/google/uuid" + + "plumber/internal/store/sqlc" ) // ErrLastAdmin is returned when demoting the only remaining admin. @@ -22,7 +24,7 @@ const ( RoleAdmin Role = "admin" ) -// User is an account row. Methods run SQL against db. +// User is an account row. Methods run SQL against db via sqlc. type User struct { ID string Username string @@ -48,6 +50,20 @@ func NormalizeUsername(s string) string { return strings.ToLower(strings.TrimSpace(s)) } +func toUser(db *sql.DB, id, username, name, role, avatarURL, state, createdAt, passwordHash string) *User { + return &User{ + ID: id, + Username: username, + Name: name, + Role: Role(role), + AvatarURL: avatarURL, + State: state, + CreatedAt: createdAt, + PasswordHash: passwordHash, + db: db, + } +} + // Create inserts the user. Sets ID, Name, and CreatedAt when empty. func (u *User) Create(ctx context.Context) error { if u == nil || u.db == nil { @@ -66,9 +82,14 @@ func (u *User) Create(ctx context.Context) error { if u.CreatedAt == "" { u.CreatedAt = time.Now().UTC().Format(time.RFC3339) } - _, err := u.db.ExecContext(ctx, `INSERT INTO users (id, username, name, password_hash, role, avatar_url, state, created_at) VALUES ($1, $2, $3, $4, $5, '', '', $6)`, - u.ID, u.Username, u.Name, u.PasswordHash, string(u.Role), u.CreatedAt) - return err + return sqlc.New(u.db).CreateUser(ctx, sqlc.CreateUserParams{ + ID: u.ID, + Username: u.Username, + Name: u.Name, + PasswordHash: u.PasswordHash, + Role: string(u.Role), + CreatedAt: u.CreatedAt, + }) } // SetRole updates this user's role (last-admin safe). @@ -85,21 +106,24 @@ func (u *User) SetRole(ctx context.Context, role Role) error { } defer tx.Rollback() - var current string - err = tx.QueryRowContext(ctx, `SELECT role FROM users WHERE id = $1`, u.ID).Scan(¤t) + q := sqlc.New(tx) + current, err := q.GetUserRole(ctx, u.ID) if err != nil { return err } if Role(current) == RoleAdmin && role == RoleUser { - var n int - if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM users WHERE role = $1`, string(RoleAdmin)).Scan(&n); err != nil { + n, err := q.CountAdmins(ctx, string(RoleAdmin)) + if err != nil { return err } if n <= 1 { return ErrLastAdmin } } - res, err := tx.ExecContext(ctx, `UPDATE users SET role = $1 WHERE id = $2`, string(role), u.ID) + res, err := q.UpdateUserRole(ctx, sqlc.UpdateUserRoleParams{ + Role: string(role), + ID: u.ID, + }) if err != nil { return err } @@ -123,61 +147,47 @@ func (u *User) SaveProfile(ctx context.Context) error { return fmt.Errorf("user: no database") } u.State = strings.TrimSpace(u.State) + q := sqlc.New(u.db) if u.AvatarURL == "" { - _, err := u.db.ExecContext(ctx, `UPDATE users SET state = $1 WHERE id = $2`, u.State, u.ID) - return err + return q.UpdateUserState(ctx, sqlc.UpdateUserStateParams{State: u.State, ID: u.ID}) } - _, err := u.db.ExecContext(ctx, `UPDATE users SET state = $1, avatar_url = $2 WHERE id = $3`, u.State, u.AvatarURL, u.ID) - return err + return q.UpdateUserStateAndAvatar(ctx, sqlc.UpdateUserStateAndAvatarParams{ + State: u.State, + AvatarUrl: u.AvatarURL, + ID: u.ID, + }) } func CountAdmins(ctx context.Context, db *sql.DB) (int, error) { - var n int - err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users WHERE role = $1`, string(RoleAdmin)).Scan(&n) - return n, err + n, err := sqlc.New(db).CountAdmins(ctx, string(RoleAdmin)) + return int(n), err } func ListUsers(ctx context.Context, db *sql.DB) ([]User, error) { - rows, err := db.QueryContext(ctx, `SELECT id, username, name, role, avatar_url, state, created_at FROM users ORDER BY created_at ASC`) + rows, err := sqlc.New(db).ListUsers(ctx) if err != nil { return nil, err } - defer rows.Close() - var out []User - for rows.Next() { - var u User - var role string - if err := rows.Scan(&u.ID, &u.Username, &u.Name, &role, &u.AvatarURL, &u.State, &u.CreatedAt); err != nil { - return nil, err - } - u.Role = Role(role) - u.db = db - out = append(out, u) + out := make([]User, 0, len(rows)) + for _, r := range rows { + u := toUser(db, r.ID, r.Username, r.Name, r.Role, r.AvatarUrl, r.State, r.CreatedAt, "") + out = append(out, *u) } - return out, rows.Err() + return out, nil } func UserByID(ctx context.Context, db *sql.DB, id string) (*User, error) { - return scanUser(db, db.QueryRowContext(ctx, `SELECT id, username, name, role, avatar_url, state, created_at FROM users WHERE id = $1`, id), false) -} - -func UserByUsername(ctx context.Context, db *sql.DB, username string) (*User, error) { - return scanUser(db, db.QueryRowContext(ctx, `SELECT id, username, name, role, avatar_url, state, created_at, password_hash FROM users WHERE username = $1`, NormalizeUsername(username)), true) -} - -func scanUser(db *sql.DB, row *sql.Row, withSecrets bool) (*User, error) { - var u User - var role string - var err error - if withSecrets { - err = row.Scan(&u.ID, &u.Username, &u.Name, &role, &u.AvatarURL, &u.State, &u.CreatedAt, &u.PasswordHash) - } else { - err = row.Scan(&u.ID, &u.Username, &u.Name, &role, &u.AvatarURL, &u.State, &u.CreatedAt) - } + r, err := sqlc.New(db).GetUserByID(ctx, id) if err != nil { return nil, err } - u.Role = Role(role) - u.db = db - return &u, nil + return toUser(db, r.ID, r.Username, r.Name, r.Role, r.AvatarUrl, r.State, r.CreatedAt, ""), nil +} + +func UserByUsername(ctx context.Context, db *sql.DB, username string) (*User, error) { + r, err := sqlc.New(db).GetUserByUsername(ctx, NormalizeUsername(username)) + if err != nil { + return nil, err + } + return toUser(db, r.ID, r.Username, r.Name, r.Role, r.AvatarUrl, r.State, r.CreatedAt, r.PasswordHash), nil } diff --git a/internal/store/vote.go b/internal/store/vote.go index d3c07b6..c28efad 100644 --- a/internal/store/vote.go +++ b/internal/store/vote.go @@ -4,6 +4,8 @@ import ( "context" "database/sql" "fmt" + + "plumber/internal/store/sqlc" ) // Vote toggles or sets a user's vote on a question (value must be 1 or -1). @@ -16,16 +18,20 @@ func Vote(ctx context.Context, db *sql.DB, userID, questionID string, value int) return err } defer tx.Rollback() - var current sql.NullInt64 - err = tx.QueryRowContext(ctx, `SELECT value FROM votes WHERE user_id = $1 AND question_id = $2`, userID, questionID).Scan(¤t) + + q := sqlc.New(tx) + current, err := q.GetVote(ctx, sqlc.GetVoteParams{UserID: userID, QuestionID: questionID}) if err != nil && err != sql.ErrNoRows { return err } - if err == nil && current.Valid && int(current.Int64) == value { - _, err = tx.ExecContext(ctx, `DELETE FROM votes WHERE user_id = $1 AND question_id = $2`, userID, questionID) + if err == nil && int(current) == value { + err = q.DeleteVote(ctx, sqlc.DeleteVoteParams{UserID: userID, QuestionID: questionID}) } else { - _, err = tx.ExecContext(ctx, `INSERT INTO votes (user_id, question_id, value) VALUES ($1, $2, $3) -ON CONFLICT (user_id, question_id) DO UPDATE SET value = excluded.value`, userID, questionID, value) + err = q.UpsertVote(ctx, sqlc.UpsertVoteParams{ + UserID: userID, + QuestionID: questionID, + Value: int32(value), + }) } if err != nil { return err diff --git a/sqlc.yaml b/sqlc.yaml new file mode 100644 index 0000000..0f71770 --- /dev/null +++ b/sqlc.yaml @@ -0,0 +1,12 @@ +version: "2" +sql: + - engine: "postgresql" + schema: "schema.sql" + queries: "db/queries" + gen: + go: + package: "sqlc" + out: "internal/store/sqlc" + sql_package: "database/sql" + emit_json_tags: false + emit_empty_slices: true From 247fb05281946db439b1e8eac5b2b30729dac05c Mon Sep 17 00:00:00 2001 From: codegirl-007 Date: Sat, 22 Aug 2026 07:11:47 -0700 Subject: [PATCH 09/17] Replace scs postgresstore with a sqlc-backed SessionStore. Keep scs for cookies and session API while sessions DDL and queries live in the same sqlc stack as the rest of Postgres. --- db/queries/sessions.sql | 18 ++++ go.mod | 1 - go.sum | 4 - internal/store/postgres.go | 4 - internal/store/question.go | 6 +- internal/store/sessions.go | 125 ++++++++++++++++++++------- internal/store/sessions_test.go | 55 ++++++++++++ internal/store/sqlc/models.go | 10 +++ internal/store/sqlc/questions.sql.go | 30 ++++--- internal/store/sqlc/sessions.sql.go | 62 +++++++++++++ schema.sql | 7 ++ 11 files changed, 266 insertions(+), 56 deletions(-) create mode 100644 db/queries/sessions.sql create mode 100644 internal/store/sessions_test.go create mode 100644 internal/store/sqlc/sessions.sql.go diff --git a/db/queries/sessions.sql b/db/queries/sessions.sql new file mode 100644 index 0000000..81482a2 --- /dev/null +++ b/db/queries/sessions.sql @@ -0,0 +1,18 @@ +-- name: GetSession :one +SELECT data +FROM sessions +WHERE token = $1 AND expiry > now(); + +-- name: UpsertSession :exec +INSERT INTO sessions (token, data, expiry) +VALUES ($1, $2, $3) +ON CONFLICT (token) DO UPDATE +SET data = excluded.data, expiry = excluded.expiry; + +-- name: DeleteSession :exec +DELETE FROM sessions +WHERE token = $1; + +-- name: DeleteExpiredSessions :exec +DELETE FROM sessions +WHERE expiry <= now(); diff --git a/go.mod b/go.mod index 84dc9b5..844fc09 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,6 @@ module plumber go 1.25.0 require ( - github.com/alexedwards/scs/postgresstore v0.0.0-20251002162104-209de6e426de github.com/alexedwards/scs/v2 v2.9.0 github.com/aws/aws-sdk-go-v2 v1.43.7 github.com/aws/aws-sdk-go-v2/credentials v1.19.37 diff --git a/go.sum b/go.sum index 88aefcd..256af28 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,3 @@ -github.com/alexedwards/scs/postgresstore v0.0.0-20251002162104-209de6e426de h1:LDrMkjj4OCCQsq9SvIPQV1l3leMxqXZTCTxDFwMrqTE= -github.com/alexedwards/scs/postgresstore v0.0.0-20251002162104-209de6e426de/go.mod h1:TDDdV/xnjj+/4zBQ9a2k+i2AbuAdY7SQjPUh5zoTZ3M= github.com/alexedwards/scs/v2 v2.9.0 h1:xa05mVpwTBm1iLeTMNFfAWpKUm4fXAW7CeAViqBVS90= github.com/alexedwards/scs/v2 v2.9.0/go.mod h1:ToaROZxyKukJKT/xLcVQAChi5k6+Pn1Gvmdl7h3RRj8= github.com/aws/aws-sdk-go-v2 v1.43.7 h1:msCzvkeYJA9ehbV8mRRmkZLo/zJg/+yDVLNtflg83hQ= @@ -43,8 +41,6 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= -github.com/lib/pq v1.4.0 h1:TmtCFbH+Aw0AixwyttznSMQDgbR5Yed/Gg6S8Funrhc= -github.com/lib/pq v1.4.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= diff --git a/internal/store/postgres.go b/internal/store/postgres.go index cd5d24b..3f1af8f 100644 --- a/internal/store/postgres.go +++ b/internal/store/postgres.go @@ -67,10 +67,6 @@ func OpenPostgres(databaseURL, schema string) (*sql.DB, *SessionStore, error) { _ = db.Close() return nil, nil, fmt.Errorf("apply schema: %w", err) } - if err := applySessionsSchema(db); err != nil { - _ = db.Close() - return nil, nil, fmt.Errorf("apply sessions schema: %w", err) - } if err := migrateUserProfileColumns(db); err != nil { _ = db.Close() return nil, nil, fmt.Errorf("migrate profile columns: %w", err) diff --git a/internal/store/question.go b/internal/store/question.go index 8915e8f..0761c19 100644 --- a/internal/store/question.go +++ b/internal/store/question.go @@ -99,7 +99,7 @@ func rankedFrom( func ListHunt(ctx context.Context, db *sql.DB, huntDate, viewerID string) ([]RankedQuestion, error) { rows, err := sqlc.New(db).ListHunt(ctx, sqlc.ListHuntParams{ - UserID: viewerID, + ViewerID: viewerID, HuntDate: huntDate, }) if err != nil { @@ -114,8 +114,8 @@ func ListHunt(ctx context.Context, db *sql.DB, huntDate, viewerID string) ([]Ran func GetQuestion(ctx context.Context, db *sql.DB, id, viewerID string) (*RankedQuestion, error) { r, err := sqlc.New(db).GetQuestion(ctx, sqlc.GetQuestionParams{ - UserID: viewerID, - ID: id, + ViewerID: viewerID, + ID: id, }) if err != nil { return nil, err diff --git a/internal/store/sessions.go b/internal/store/sessions.go index 4d4edcf..b7fb062 100644 --- a/internal/store/sessions.go +++ b/internal/store/sessions.go @@ -1,53 +1,114 @@ package store import ( + "context" "database/sql" + "errors" + "sync" "time" - "github.com/alexedwards/scs/postgresstore" "github.com/alexedwards/scs/v2" + + "plumber/internal/store/sqlc" ) -const sessionsSchemaPostgres = ` -CREATE TABLE IF NOT EXISTS sessions ( - token TEXT PRIMARY KEY, - data BYTEA NOT NULL, - expiry TIMESTAMPTZ NOT NULL -); -CREATE INDEX IF NOT EXISTS sessions_expiry_idx ON sessions (expiry); -` - -// applySessionsSchema creates the scs sessions table if missing. -func applySessionsSchema(db *sql.DB) error { - return applySchema(db, sessionsSchemaPostgres) -} - -type sessionStopper interface { - StopCleanup() -} - -// SessionStore wraps scs Postgres session persistence and cleanup. +// SessionStore persists scs sessions in Postgres via sqlc and optionally +// deletes expired rows on an interval. type SessionStore struct { - store scs.Store - stopper sessionStopper + db *sql.DB + q *sqlc.Queries + stop chan struct{} + stopped chan struct{} + once sync.Once } -// NewSessionStore starts a postgresstore with the given cleanup interval. +// NewSessionStore creates a store backed by db. cleanupInterval > 0 starts a +// background goroutine that deletes expired sessions; 0 disables cleanup. func NewSessionStore(db *sql.DB, cleanupInterval time.Duration) *SessionStore { - ps := postgresstore.NewWithCleanupInterval(db, cleanupInterval) - return &SessionStore{store: ps, stopper: ps} + s := &SessionStore{ + db: db, + q: sqlc.New(db), + } + if cleanupInterval > 0 { + s.stop = make(chan struct{}) + s.stopped = make(chan struct{}) + go s.cleanupLoop(cleanupInterval) + } + return s } -// Store returns the scs.Store implementation. +// Store returns the scs.Store implementation (s itself). func (s *SessionStore) Store() scs.Store { - return s.store + return s +} + +// Find implements scs.Store. +func (s *SessionStore) Find(token string) ([]byte, bool, error) { + return s.FindCtx(context.Background(), token) +} + +// Commit implements scs.Store. +func (s *SessionStore) Commit(token string, data []byte, expiry time.Time) error { + return s.CommitCtx(context.Background(), token, data, expiry) +} + +// Delete implements scs.Store. +func (s *SessionStore) Delete(token string) error { + return s.DeleteCtx(context.Background(), token) +} + +// FindCtx implements scs.CtxStore. +func (s *SessionStore) FindCtx(ctx context.Context, token string) ([]byte, bool, error) { + data, err := s.q.GetSession(ctx, token) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, false, nil + } + return nil, false, err + } + return data, true, nil +} + +// CommitCtx implements scs.CtxStore. +func (s *SessionStore) CommitCtx(ctx context.Context, token string, data []byte, expiry time.Time) error { + return s.q.UpsertSession(ctx, sqlc.UpsertSessionParams{ + Token: token, + Data: data, + Expiry: expiry, + }) +} + +// DeleteCtx implements scs.CtxStore. +func (s *SessionStore) DeleteCtx(ctx context.Context, token string) error { + return s.q.DeleteSession(ctx, token) +} + +// StopCleanup stops the background expiry deleter. Safe to call multiple times. +func (s *SessionStore) StopCleanup() { + if s == nil || s.stop == nil { + return + } + s.once.Do(func() { + close(s.stop) + <-s.stopped + }) } // Close stops background session cleanup. func (s *SessionStore) Close() { - if s == nil || s.stopper == nil { - return - } - s.stopper.StopCleanup() - s.stopper = nil + s.StopCleanup() +} + +func (s *SessionStore) cleanupLoop(interval time.Duration) { + defer close(s.stopped) + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ticker.C: + _ = s.q.DeleteExpiredSessions(context.Background()) + case <-s.stop: + return + } + } } diff --git a/internal/store/sessions_test.go b/internal/store/sessions_test.go new file mode 100644 index 0000000..b9430f7 --- /dev/null +++ b/internal/store/sessions_test.go @@ -0,0 +1,55 @@ +package store + +import ( + "os" + "testing" + "time" +) + +func TestSessionStoreCommitFindDelete(t *testing.T) { + url := os.Getenv("TEST_DATABASE_URL") + if url == "" { + url = os.Getenv("DATABASE_URL") + } + if url == "" { + t.Skip("DATABASE_URL or TEST_DATABASE_URL not set") + } + schema, err := os.ReadFile("../../schema.sql") + if err != nil { + t.Fatal(err) + } + db, sessions, err := OpenPostgres(url, string(schema)) + if err != nil { + t.Fatal(err) + } + defer db.Close() + defer sessions.Close() + + token := "test-session-" + time.Now().Format("20060102150405.000000000") + data := []byte("hello-session") + expiry := time.Now().Add(time.Hour) + + if err := sessions.Commit(token, data, expiry); err != nil { + t.Fatalf("Commit: %v", err) + } + got, found, err := sessions.Find(token) + if err != nil { + t.Fatalf("Find: %v", err) + } + if !found { + t.Fatal("expected found") + } + if string(got) != string(data) { + t.Fatalf("data = %q, want %q", got, data) + } + if err := sessions.Delete(token); err != nil { + t.Fatalf("Delete: %v", err) + } + _, found, err = sessions.Find(token) + if err != nil { + t.Fatalf("Find after delete: %v", err) + } + if found { + t.Fatal("expected not found after delete") + } +} diff --git a/internal/store/sqlc/models.go b/internal/store/sqlc/models.go index 93ac364..7de647f 100644 --- a/internal/store/sqlc/models.go +++ b/internal/store/sqlc/models.go @@ -4,6 +4,10 @@ package sqlc +import ( + "time" +) + type Answer struct { QuestionID string AuthorID string @@ -23,6 +27,12 @@ type Question struct { CreatedAt string } +type Session struct { + Token string + Data []byte + Expiry time.Time +} + type User struct { ID string Username string diff --git a/internal/store/sqlc/questions.sql.go b/internal/store/sqlc/questions.sql.go index dc8b4e1..9b69b70 100644 --- a/internal/store/sqlc/questions.sql.go +++ b/internal/store/sqlc/questions.sql.go @@ -39,9 +39,12 @@ func (q *Queries) CreateQuestion(ctx context.Context, arg CreateQuestionParams) const getQuestion = `-- name: GetQuestion :one SELECT q.id, q.author_id, u.name AS author_name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, - COALESCE((SELECT SUM(value) FROM votes WHERE votes.question_id = q.id), 0)::bigint AS score, + COALESCE((SELECT SUM(votes.value) FROM votes WHERE votes.question_id = q.id), 0)::bigint AS score, CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END::bigint AS answered, - COALESCE((SELECT value FROM votes WHERE votes.user_id = $1 AND votes.question_id = q.id), 0)::bigint AS user_vote + COALESCE(( + SELECT votes.value FROM votes + WHERE votes.user_id = $1 AND votes.question_id = q.id + ), 0)::bigint AS user_vote FROM questions q JOIN users u ON u.id = q.author_id LEFT JOIN answers a ON a.question_id = q.id @@ -49,8 +52,8 @@ WHERE q.id = $2 ` type GetQuestionParams struct { - UserID string - ID string + ViewerID string + ID string } type GetQuestionRow struct { @@ -69,7 +72,7 @@ type GetQuestionRow struct { } func (q *Queries) GetQuestion(ctx context.Context, arg GetQuestionParams) (GetQuestionRow, error) { - row := q.db.QueryRowContext(ctx, getQuestion, arg.UserID, arg.ID) + row := q.db.QueryRowContext(ctx, getQuestion, arg.ViewerID, arg.ID) var i GetQuestionRow err := row.Scan( &i.ID, @@ -103,7 +106,10 @@ const listHunt = `-- name: ListHunt :many SELECT q.id, q.author_id, u.name AS author_name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, COALESCE(SUM(v.value), 0)::bigint AS score, CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END::bigint AS answered, - COALESCE((SELECT value FROM votes WHERE votes.user_id = $1 AND votes.question_id = q.id), 0)::bigint AS user_vote + COALESCE(( + SELECT votes.value FROM votes + WHERE votes.user_id = $1 AND votes.question_id = q.id + ), 0)::bigint AS user_vote FROM questions q JOIN users u ON u.id = q.author_id LEFT JOIN votes v ON v.question_id = q.id @@ -114,7 +120,7 @@ ORDER BY score DESC, q.created_at ASC ` type ListHuntParams struct { - UserID string + ViewerID string HuntDate string } @@ -134,7 +140,7 @@ type ListHuntRow struct { } func (q *Queries) ListHunt(ctx context.Context, arg ListHuntParams) ([]ListHuntRow, error) { - rows, err := q.db.QueryContext(ctx, listHunt, arg.UserID, arg.HuntDate) + rows, err := q.db.QueryContext(ctx, listHunt, arg.ViewerID, arg.HuntDate) if err != nil { return nil, err } @@ -171,7 +177,7 @@ func (q *Queries) ListHunt(ctx context.Context, arg ListHuntParams) ([]ListHuntR const listQuestionsAnsweredBy = `-- name: ListQuestionsAnsweredBy :many SELECT q.id, q.author_id, u.name AS author_name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, - COALESCE((SELECT SUM(value) FROM votes WHERE votes.question_id = q.id), 0)::bigint AS score, + COALESCE((SELECT SUM(votes.value) FROM votes WHERE votes.question_id = q.id), 0)::bigint AS score, 1::bigint AS answered, 0::bigint AS user_vote FROM answers ans @@ -196,8 +202,8 @@ type ListQuestionsAnsweredByRow struct { UserVote int64 } -func (q *Queries) ListQuestionsAnsweredBy(ctx context.Context, authorID string) ([]ListQuestionsAnsweredByRow, error) { - rows, err := q.db.QueryContext(ctx, listQuestionsAnsweredBy, authorID) +func (q *Queries) ListQuestionsAnsweredBy(ctx context.Context, adminID string) ([]ListQuestionsAnsweredByRow, error) { + rows, err := q.db.QueryContext(ctx, listQuestionsAnsweredBy, adminID) if err != nil { return nil, err } @@ -234,7 +240,7 @@ func (q *Queries) ListQuestionsAnsweredBy(ctx context.Context, authorID string) const listQuestionsByAuthor = `-- name: ListQuestionsByAuthor :many SELECT q.id, q.author_id, u.name AS author_name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, - COALESCE((SELECT SUM(value) FROM votes WHERE votes.question_id = q.id), 0)::bigint AS score, + COALESCE((SELECT SUM(votes.value) FROM votes WHERE votes.question_id = q.id), 0)::bigint AS score, CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END::bigint AS answered, 0::bigint AS user_vote FROM questions q diff --git a/internal/store/sqlc/sessions.sql.go b/internal/store/sqlc/sessions.sql.go new file mode 100644 index 0000000..9562dea --- /dev/null +++ b/internal/store/sqlc/sessions.sql.go @@ -0,0 +1,62 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: sessions.sql + +package sqlc + +import ( + "context" + "time" +) + +const deleteExpiredSessions = `-- name: DeleteExpiredSessions :exec +DELETE FROM sessions +WHERE expiry <= now() +` + +func (q *Queries) DeleteExpiredSessions(ctx context.Context) error { + _, err := q.db.ExecContext(ctx, deleteExpiredSessions) + return err +} + +const deleteSession = `-- name: DeleteSession :exec +DELETE FROM sessions +WHERE token = $1 +` + +func (q *Queries) DeleteSession(ctx context.Context, token string) error { + _, err := q.db.ExecContext(ctx, deleteSession, token) + return err +} + +const getSession = `-- name: GetSession :one +SELECT data +FROM sessions +WHERE token = $1 AND expiry > now() +` + +func (q *Queries) GetSession(ctx context.Context, token string) ([]byte, error) { + row := q.db.QueryRowContext(ctx, getSession, token) + var data []byte + err := row.Scan(&data) + return data, err +} + +const upsertSession = `-- name: UpsertSession :exec +INSERT INTO sessions (token, data, expiry) +VALUES ($1, $2, $3) +ON CONFLICT (token) DO UPDATE +SET data = excluded.data, expiry = excluded.expiry +` + +type UpsertSessionParams struct { + Token string + Data []byte + Expiry time.Time +} + +func (q *Queries) UpsertSession(ctx context.Context, arg UpsertSessionParams) error { + _, err := q.db.ExecContext(ctx, upsertSession, arg.Token, arg.Data, arg.Expiry) + return err +} diff --git a/schema.sql b/schema.sql index e3a8e89..67136d6 100644 --- a/schema.sql +++ b/schema.sql @@ -36,3 +36,10 @@ CREATE TABLE IF NOT EXISTS answers ( created_at TEXT NOT NULL, updated_at TEXT NOT NULL ); + +CREATE TABLE IF NOT EXISTS sessions ( + token TEXT PRIMARY KEY, + data BYTEA NOT NULL, + expiry TIMESTAMPTZ NOT NULL +); +CREATE INDEX IF NOT EXISTS sessions_expiry_idx ON sessions (expiry); From afd2476f3ce176c24ccd4d874ea5e712e987b87e Mon Sep 17 00:00:00 2001 From: codegirl-007 Date: Sat, 22 Aug 2026 07:24:39 -0700 Subject: [PATCH 10/17] Harden sessions, uploads, admin demotion, and HTTP timeouts. Address PR review findings: renew session tokens on auth, sniff/re-encode avatars, serialize last-admin checks, bound server timeouts, rune-safe truncation, and TEST_DATABASE_URL-only integration tests. --- .env.example | 2 + cmd/server/main.go | 9 +++- go.mod | 1 + go.sum | 2 + internal/store/sessions_test.go | 5 +-- internal/store/user.go | 8 ++++ internal/web/auth.go | 8 ++++ internal/web/profile.go | 73 ++++++++++++++++++++++++--------- internal/web/server.go | 23 +++++++++-- internal/web/server_test.go | 16 ++++---- todo.md | 2 +- 11 files changed, 113 insertions(+), 36 deletions(-) diff --git a/.env.example b/.env.example index a4d043c..ec4d4f2 100644 --- a/.env.example +++ b/.env.example @@ -3,6 +3,8 @@ LISTEN=:8080 # Required: PlanetScale Postgres URI (port 5432 so the app can create tables on boot). # Switch to 6432 (PgBouncer) later if you need pooling. DATABASE_URL=postgresql://user:password@host.example.com:5432/postgres?sslmode=verify-full +# Required for integration tests (do not point at the runtime DATABASE_URL). +# TEST_DATABASE_URL=postgresql://user:password@host.example.com:5432/plumber_test?sslmode=verify-full # Optional: first matching registrant becomes admin only if no admin exists yet. # Later promote/demote via /admin/users (admins only). ADMIN_USERNAME=yourusername diff --git a/cmd/server/main.go b/cmd/server/main.go index aed2530..b237b53 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -29,7 +29,14 @@ func main() { uploader := blob.FromEnv() handler := newHandler(db, sessions, uploader) - run(&http.Server{Addr: listenAddr(), Handler: handler}) + run(&http.Server{ + Addr: listenAddr(), + Handler: handler, + ReadHeaderTimeout: 5 * time.Second, + ReadTimeout: 30 * time.Second, + WriteTimeout: 60 * time.Second, + IdleTimeout: 90 * time.Second, + }) } func openDB() (*sql.DB, *store.SessionStore) { diff --git a/go.mod b/go.mod index 844fc09..ccba0df 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,7 @@ require ( github.com/jackc/pgx/v5 v5.10.0 github.com/joho/godotenv v1.5.1 golang.org/x/crypto v0.55.0 + golang.org/x/image v0.45.0 ) require ( diff --git a/go.sum b/go.sum index 256af28..0a8c3d7 100644 --- a/go.sum +++ b/go.sum @@ -50,6 +50,8 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= +golang.org/x/image v0.45.0 h1:FMb1nTbH5H9vF55SriQHgFw5GnNL9Jg6L25BwXKzhB0= +golang.org/x/image v0.45.0/go.mod h1:n62x/7RqlwXDvGsSU4u6IUTUf6KghUZ9Bt7cG/T9Fx4= golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= diff --git a/internal/store/sessions_test.go b/internal/store/sessions_test.go index b9430f7..d2caf4f 100644 --- a/internal/store/sessions_test.go +++ b/internal/store/sessions_test.go @@ -9,10 +9,7 @@ import ( func TestSessionStoreCommitFindDelete(t *testing.T) { url := os.Getenv("TEST_DATABASE_URL") if url == "" { - url = os.Getenv("DATABASE_URL") - } - if url == "" { - t.Skip("DATABASE_URL or TEST_DATABASE_URL not set") + t.Skip("TEST_DATABASE_URL not set") } schema, err := os.ReadFile("../../schema.sql") if err != nil { diff --git a/internal/store/user.go b/internal/store/user.go index 13bf795..7f4da01 100644 --- a/internal/store/user.go +++ b/internal/store/user.go @@ -92,6 +92,10 @@ func (u *User) Create(ctx context.Context) error { }) } +// adminRoleLockKey serializes SetRole so concurrent demotions cannot bypass the +// last-admin guard under READ COMMITTED. +const adminRoleLockKey int64 = 0x706c756d5f61646d // "plum_adm" + // SetRole updates this user's role (last-admin safe). func (u *User) SetRole(ctx context.Context, role Role) error { if u == nil || u.db == nil { @@ -106,6 +110,10 @@ func (u *User) SetRole(ctx context.Context, role Role) error { } defer tx.Rollback() + if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock($1)`, adminRoleLockKey); err != nil { + return err + } + q := sqlc.New(tx) current, err := q.GetUserRole(ctx, u.ID) if err != nil { diff --git a/internal/web/auth.go b/internal/web/auth.go index 5bf63d3..307900f 100644 --- a/internal/web/auth.go +++ b/internal/web/auth.go @@ -54,6 +54,10 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { }) return } + if err := s.sessions.RenewToken(r.Context()); err != nil { + http.Error(w, "could not start session", http.StatusInternalServerError) + return + } s.sessions.Put(r.Context(), "user_id", u.ID) http.Redirect(w, r, next, http.StatusSeeOther) } @@ -108,6 +112,10 @@ func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) { s.exec(w, "register", p) return } + if err := s.sessions.RenewToken(r.Context()); err != nil { + http.Error(w, "could not start session", http.StatusInternalServerError) + return + } s.sessions.Put(r.Context(), "user_id", u.ID) http.Redirect(w, r, "/", http.StatusSeeOther) } diff --git a/internal/web/profile.go b/internal/web/profile.go index fb9a750..9bf771b 100644 --- a/internal/web/profile.go +++ b/internal/web/profile.go @@ -1,12 +1,18 @@ package web import ( + "bytes" + "fmt" + "image" + "image/jpeg" + "image/png" "io" "net/http" "path" "strings" "github.com/google/uuid" + _ "golang.org/x/image/webp" "plumber/internal/blob" "plumber/internal/geo" @@ -63,23 +69,21 @@ func (s *Server) handleProfile(w http.ResponseWriter, r *http.Request) { s.renderProfile(w, r, u, "Avatar uploads are not configured on this server.", state) return } - ct := hdr.Header.Get("Content-Type") - ext, contentType, ok := avatarType(hdr.Filename, ct) - if !ok { - s.renderProfile(w, r, u, "Avatar must be a JPEG, PNG, or WebP image.", state) - return - } if hdr.Size > 2<<20 { s.renderProfile(w, r, u, "Avatar must be 2MB or smaller.", state) return } + body, ext, contentType, prepErr := prepareAvatar(file, 2<<20) + if prepErr != nil { + s.renderProfile(w, r, u, "Avatar must be a JPEG, PNG, or WebP image.", state) + return + } key := path.Join("avatars", u.ID, uuid.NewString()+ext) - limited := io.LimitReader(file, (2<<20)+1) url, upErr := s.cfg.Blob.Upload(r.Context(), blob.FileUpload{ Key: key, - Body: limited, + Body: bytes.NewReader(body), ContentType: contentType, - Size: hdr.Size, + Size: int64(len(body)), }) if upErr != nil { s.renderProfile(w, r, u, "Could not upload avatar. Try again later.", state) @@ -103,18 +107,49 @@ func (s *Server) handleProfile(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/profile", http.StatusSeeOther) } -func avatarType(filename, contentType string) (ext, normalized string, ok bool) { - contentType = strings.ToLower(strings.TrimSpace(contentType)) - filename = strings.ToLower(filename) +// prepareAvatar reads at most maxBytes, sniffs/decodes the image, and re-encodes +// it so only valid image bytes are stored publicly. +func prepareAvatar(r io.Reader, maxBytes int64) (body []byte, ext, contentType string, err error) { + limited := io.LimitReader(r, maxBytes+1) + raw, err := io.ReadAll(limited) + if err != nil { + return nil, "", "", err + } + if int64(len(raw)) > maxBytes { + return nil, "", "", fmt.Errorf("avatar too large") + } + if len(raw) == 0 { + return nil, "", "", fmt.Errorf("empty avatar") + } + + sniff := http.DetectContentType(raw) switch { - case strings.HasPrefix(contentType, "image/jpeg"), strings.HasSuffix(filename, ".jpg"), strings.HasSuffix(filename, ".jpeg"): - return ".jpg", "image/jpeg", true - case strings.HasPrefix(contentType, "image/png"), strings.HasSuffix(filename, ".png"): - return ".png", "image/png", true - case strings.HasPrefix(contentType, "image/webp"), strings.HasSuffix(filename, ".webp"): - return ".webp", "image/webp", true + case strings.HasPrefix(sniff, "image/jpeg"), + strings.HasPrefix(sniff, "image/png"), + strings.HasPrefix(sniff, "image/webp"): default: - return "", "", false + return nil, "", "", fmt.Errorf("unsupported type %s", sniff) + } + + img, format, err := image.Decode(bytes.NewReader(raw)) + if err != nil { + return nil, "", "", err + } + + var out bytes.Buffer + switch format { + case "jpeg": + if err := jpeg.Encode(&out, img, &jpeg.Options{Quality: 90}); err != nil { + return nil, "", "", err + } + return out.Bytes(), ".jpg", "image/jpeg", nil + case "png", "webp": + if err := png.Encode(&out, img); err != nil { + return nil, "", "", err + } + return out.Bytes(), ".png", "image/png", nil + default: + return nil, "", "", fmt.Errorf("unsupported format %s", format) } } diff --git a/internal/web/server.go b/internal/web/server.go index a6dd92d..c05666b 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -311,13 +311,13 @@ func (s *Server) handleSubmit(w http.ResponseWriter, r *http.Request) { return } if len(title) > 120 { - title = title[:120] + title = truncateRunes(title, 120) } if len(body) > 8000 { - body = body[:8000] + body = truncateRunes(body, 8000) } if len(city) > 80 { - city = city[:80] + city = truncateRunes(city, 80) } q := store.NewQuestion(s.db) q.AuthorID = u.ID @@ -449,7 +449,7 @@ func (s *Server) handleAnswer(w http.ResponseWriter, r *http.Request) { return } if len(body) > 12000 { - body = body[:12000] + body = truncateRunes(body, 12000) } ans := store.NewAnswer(s.db) ans.QuestionID = id @@ -518,6 +518,21 @@ func (s *Server) exec(w http.ResponseWriter, name string, data any) { } } +// truncateRunes shortens s to at most max runes without splitting a code point. +func truncateRunes(s string, max int) string { + if max <= 0 { + return "" + } + n := 0 + for byteIdx := range s { + if n == max { + return s[:byteIdx] + } + n++ + } + return s +} + func randomHex(n int) string { b := make([]byte, n) if _, err := rand.Read(b); err != nil { diff --git a/internal/web/server_test.go b/internal/web/server_test.go index d6d9fb7..530a8bd 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -4,6 +4,8 @@ import ( "bytes" "context" "database/sql" + "image" + "image/png" "mime/multipart" "net/http" "net/http/httptest" @@ -23,17 +25,14 @@ import ( func testDBURL() string { _ = godotenv.Load() - if u := strings.TrimSpace(os.Getenv("TEST_DATABASE_URL")); u != "" { - return u - } - return strings.TrimSpace(os.Getenv("DATABASE_URL")) + return strings.TrimSpace(os.Getenv("TEST_DATABASE_URL")) } func newTestServer(t *testing.T, cfg Config) (*Server, *sql.DB) { t.Helper() url := testDBURL() if url == "" { - t.Skip("set TEST_DATABASE_URL or DATABASE_URL for web tests") + t.Skip("set TEST_DATABASE_URL for web tests") } db, sessions, err := store.OpenPostgres(url, plumber.SchemaSQL) if err != nil { @@ -162,7 +161,7 @@ func TestRegisterLoginAsk(t *testing.T) { func TestSessionSurvivesServerRestart(t *testing.T) { url := testDBURL() if url == "" { - t.Skip("set TEST_DATABASE_URL or DATABASE_URL for web tests") + t.Skip("set TEST_DATABASE_URL for web tests") } db, sessions, err := store.OpenPostgres(url, plumber.SchemaSQL) if err != nil { @@ -511,7 +510,10 @@ func TestProfileAdminAnsweredListAndAvatarUpload(t *testing.T) { if err != nil { t.Fatal(err) } - _, _ = part.Write([]byte("fakepngbytes")) + img := image.NewRGBA(image.Rect(0, 0, 1, 1)) + if err := png.Encode(part, img); err != nil { + t.Fatal(err) + } _ = w.Close() req = httptest.NewRequest(http.MethodPost, "/profile", &buf) req.Header.Set("Content-Type", w.FormDataContentType()) diff --git a/todo.md b/todo.md index 5cac465..dbe675b 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ From the project review. Priority order within each section. - [x] **Persist sessions** — Sessions live in the app DB (`sessions` table) via `postgresstore`. Opaque cookie unchanged; unused `SESSION_SECRET` removed from config / `.env.example`. - [x] **Drop Dockerfile** — Deploying on DigitalOcean App Platform (buildpack from `go.mod`); no container image needed. -- [ ] **Rune-safe truncation** — `title[:120]`, `body[:8000]`, `city[:80]`, answer body, etc. can split multi-byte UTF-8. Truncate by runes (or safely). +- [x] **Rune-safe truncation** — `title[:120]`, `body[:8000]`, `city[:80]`, answer body, etc. can split multi-byte UTF-8. Truncate by runes (or safely). - [x] **Admin bootstrap** — `ADMIN_USERNAME` seeds the first admin on register only when no admin exists. Promote/demote via `/admin/users` (admins only); roles stay in `users.role`. ## Docs & ops From f4cec32afb174e767f0c6357b108a05554006590 Mon Sep 17 00:00:00 2001 From: codegirl-007 Date: Sat, 22 Aug 2026 07:36:13 -0700 Subject: [PATCH 11/17] Make web tests database-free and finish review hardening. Introduce a Store interface with Postgres and in-memory backends, cover mutations/CSRF/session rotation without Postgres, bound avatar decode dimensions, add truncate/prepareAvatar unit tests, and run go test -race in CI. --- .github/workflows/ci.yml | 17 ++ cmd/server/main.go | 2 +- internal/store/memory.go | 327 +++++++++++++++++++++++ internal/store/memory_test.go | 56 ++++ internal/store/postgres_store.go | 86 ++++++ internal/store/store.go | 26 ++ internal/web/admin.go | 8 +- internal/web/auth.go | 15 +- internal/web/helpers_test.go | 105 ++++++++ internal/web/profile.go | 30 ++- internal/web/server.go | 51 ++-- internal/web/server_test.go | 445 ++++++++++++++++++------------- 12 files changed, 945 insertions(+), 223 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 internal/store/memory.go create mode 100644 internal/store/memory_test.go create mode 100644 internal/store/postgres_store.go create mode 100644 internal/store/store.go create mode 100644 internal/web/helpers_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..eb0f63c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,17 @@ +name: CI + +on: + push: + branches: [app, master, main] + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + - name: Test + run: go test -race ./... diff --git a/cmd/server/main.go b/cmd/server/main.go index b237b53..b73377e 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -53,7 +53,7 @@ func openDB() (*sql.DB, *store.SessionStore) { } func newHandler(db *sql.DB, sessions *store.SessionStore, uploader blob.Uploader) http.Handler { - srv, err := web.New(db, sessions.Store(), plumber.TemplateFS, plumber.StaticFS, web.Config{ + srv, err := web.New(store.NewPostgres(db), sessions.Store(), plumber.TemplateFS, plumber.StaticFS, web.Config{ AdminUsername: os.Getenv("ADMIN_USERNAME"), SecureCookie: os.Getenv("SECURE_COOKIE") == "1", Blob: uploader, diff --git a/internal/store/memory.go b/internal/store/memory.go new file mode 100644 index 0000000..a2e8cad --- /dev/null +++ b/internal/store/memory.go @@ -0,0 +1,327 @@ +package store + +import ( + "context" + "database/sql" + "fmt" + "sort" + "strings" + "sync" + "time" + + "github.com/google/uuid" + + "plumber/internal/pacific" +) + +// Memory is an in-process Store for tests. +type Memory struct { + mu sync.Mutex + users map[string]*User // id -> user + byName map[string]string // username -> id + questions map[string]*RankedQuestion // id -> question + answers map[string]*Answer // questionID -> answer + votes map[string]map[string]int // questionID -> userID -> value +} + +// NewMemory returns an empty Memory store. +func NewMemory() *Memory { + return &Memory{ + users: map[string]*User{}, + byName: map[string]string{}, + questions: map[string]*RankedQuestion{}, + answers: map[string]*Answer{}, + votes: map[string]map[string]int{}, + } +} + +func (m *Memory) CreateUser(_ context.Context, u *User) error { + m.mu.Lock() + defer m.mu.Unlock() + if u.Role != RoleUser && u.Role != RoleAdmin { + return fmt.Errorf("invalid role") + } + u.Username = NormalizeUsername(u.Username) + if _, ok := m.byName[u.Username]; ok { + return fmt.Errorf("username taken") + } + if u.ID == "" { + u.ID = uuid.NewString() + } + if u.Name == "" { + u.Name = u.Username + } + if u.CreatedAt == "" { + u.CreatedAt = time.Now().UTC().Format(time.RFC3339) + } + cp := *u + cp.db = nil + m.users[cp.ID] = &cp + m.byName[cp.Username] = cp.ID + *u = cp + return nil +} + +func (m *Memory) UserByID(_ context.Context, id string) (*User, error) { + m.mu.Lock() + defer m.mu.Unlock() + u, ok := m.users[id] + if !ok { + return nil, sql.ErrNoRows + } + cp := *u + return &cp, nil +} + +func (m *Memory) UserByUsername(_ context.Context, username string) (*User, error) { + m.mu.Lock() + defer m.mu.Unlock() + id, ok := m.byName[NormalizeUsername(username)] + if !ok { + return nil, sql.ErrNoRows + } + cp := *m.users[id] + return &cp, nil +} + +func (m *Memory) ListUsers(_ context.Context) ([]User, error) { + m.mu.Lock() + defer m.mu.Unlock() + out := make([]User, 0, len(m.users)) + for _, u := range m.users { + out = append(out, *u) + } + sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt < out[j].CreatedAt }) + return out, nil +} + +func (m *Memory) CountAdmins(_ context.Context) (int, error) { + m.mu.Lock() + defer m.mu.Unlock() + n := 0 + for _, u := range m.users { + if u.Role == RoleAdmin { + n++ + } + } + return n, nil +} + +// SetUserRole serializes demotions under m.mu (same critical section as count). +func (m *Memory) SetUserRole(_ context.Context, id string, role Role) error { + m.mu.Lock() + defer m.mu.Unlock() + if role != RoleUser && role != RoleAdmin { + return fmt.Errorf("invalid role") + } + u, ok := m.users[id] + if !ok { + return sql.ErrNoRows + } + if u.Role == RoleAdmin && role == RoleUser { + n := 0 + for _, x := range m.users { + if x.Role == RoleAdmin { + n++ + } + } + if n <= 1 { + return ErrLastAdmin + } + } + u.Role = role + return nil +} + +func (m *Memory) SaveUserProfile(_ context.Context, u *User) error { + m.mu.Lock() + defer m.mu.Unlock() + cur, ok := m.users[u.ID] + if !ok { + return sql.ErrNoRows + } + cur.State = strings.TrimSpace(u.State) + if u.AvatarURL != "" { + cur.AvatarURL = u.AvatarURL + } + u.State = cur.State + u.AvatarURL = cur.AvatarURL + return nil +} + +func (m *Memory) CreateQuestion(_ context.Context, q *RankedQuestion) error { + m.mu.Lock() + defer m.mu.Unlock() + q.Title = strings.TrimSpace(q.Title) + q.Body = strings.TrimSpace(q.Body) + q.City = strings.TrimSpace(q.City) + if q.ID == "" { + q.ID = uuid.NewString() + } + if q.HuntDate == "" { + q.HuntDate = pacific.Today() + } + if q.CreatedAt == "" { + q.CreatedAt = time.Now().UTC().Format(time.RFC3339) + } + author, ok := m.users[q.AuthorID] + if !ok { + return fmt.Errorf("unknown author") + } + cp := *q + cp.AuthorName = author.Name + cp.db = nil + m.questions[cp.ID] = &cp + *q = cp + return nil +} + +func (m *Memory) annotate(q *RankedQuestion, viewerID string) RankedQuestion { + out := *q + score := 0 + userVote := 0 + if votes, ok := m.votes[q.ID]; ok { + for uid, v := range votes { + score += v + if uid == viewerID { + userVote = v + } + } + } + _, answered := m.answers[q.ID] + out.Score = score + out.Answered = answered + out.UserVote = userVote + out.db = nil + return out +} + +func (m *Memory) GetQuestion(_ context.Context, id, viewerID string) (*RankedQuestion, error) { + m.mu.Lock() + defer m.mu.Unlock() + q, ok := m.questions[id] + if !ok { + return nil, sql.ErrNoRows + } + out := m.annotate(q, viewerID) + return &out, nil +} + +func (m *Memory) ListHunt(_ context.Context, huntDate, viewerID string) ([]RankedQuestion, error) { + m.mu.Lock() + defer m.mu.Unlock() + out := make([]RankedQuestion, 0) + for _, q := range m.questions { + if q.HuntDate != huntDate || q.Hidden { + continue + } + out = append(out, m.annotate(q, viewerID)) + } + sort.Slice(out, func(i, j int) bool { + if out[i].Score != out[j].Score { + return out[i].Score > out[j].Score + } + return out[i].CreatedAt < out[j].CreatedAt + }) + return out, nil +} + +func (m *Memory) ListQuestionsByAuthor(_ context.Context, authorID string) ([]RankedQuestion, error) { + m.mu.Lock() + defer m.mu.Unlock() + out := make([]RankedQuestion, 0) + for _, q := range m.questions { + if q.AuthorID != authorID || q.Hidden { + continue + } + out = append(out, m.annotate(q, "")) + } + sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt > out[j].CreatedAt }) + return out, nil +} + +func (m *Memory) ListQuestionsAnsweredBy(_ context.Context, adminID string) ([]RankedQuestion, error) { + m.mu.Lock() + defer m.mu.Unlock() + out := make([]RankedQuestion, 0) + for qid, a := range m.answers { + if a.AuthorID != adminID { + continue + } + q, ok := m.questions[qid] + if !ok || q.Hidden { + continue + } + rq := m.annotate(q, "") + rq.Answered = true + out = append(out, rq) + } + sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt > out[j].CreatedAt }) + return out, nil +} + +func (m *Memory) HideQuestion(_ context.Context, id string) error { + m.mu.Lock() + defer m.mu.Unlock() + q, ok := m.questions[id] + if !ok { + return sql.ErrNoRows + } + q.Hidden = true + return nil +} + +func (m *Memory) GetAnswer(_ context.Context, questionID string) (*Answer, error) { + m.mu.Lock() + defer m.mu.Unlock() + a, ok := m.answers[questionID] + if !ok { + return nil, sql.ErrNoRows + } + cp := *a + if u, ok := m.users[a.AuthorID]; ok { + cp.AuthorName = u.Name + } + return &cp, nil +} + +func (m *Memory) UpsertAnswer(_ context.Context, a *Answer) error { + m.mu.Lock() + defer m.mu.Unlock() + if _, ok := m.questions[a.QuestionID]; !ok { + return fmt.Errorf("unknown question") + } + a.Body = strings.TrimSpace(a.Body) + now := time.Now().UTC().Format(time.RFC3339) + if existing, ok := m.answers[a.QuestionID]; ok { + a.CreatedAt = existing.CreatedAt + } else if a.CreatedAt == "" { + a.CreatedAt = now + } + a.UpdatedAt = now + cp := *a + cp.db = nil + m.answers[a.QuestionID] = &cp + *a = cp + return nil +} + +func (m *Memory) Vote(_ context.Context, userID, questionID string, value int) error { + m.mu.Lock() + defer m.mu.Unlock() + if value != 1 && value != -1 { + return fmt.Errorf("invalid vote") + } + if _, ok := m.questions[questionID]; !ok { + return sql.ErrNoRows + } + if m.votes[questionID] == nil { + m.votes[questionID] = map[string]int{} + } + if cur, ok := m.votes[questionID][userID]; ok && cur == value { + delete(m.votes[questionID], userID) + return nil + } + m.votes[questionID][userID] = value + return nil +} diff --git a/internal/store/memory_test.go b/internal/store/memory_test.go new file mode 100644 index 0000000..c5e3239 --- /dev/null +++ b/internal/store/memory_test.go @@ -0,0 +1,56 @@ +package store + +import ( + "context" + "sync" + "testing" +) + +func TestMemoryConcurrentLastAdminDemotion(t *testing.T) { + m := NewMemory() + ctx := context.Background() + a := &User{Username: "admin_a", PasswordHash: "x", Role: RoleAdmin} + b := &User{Username: "admin_b", PasswordHash: "x", Role: RoleAdmin} + if err := m.CreateUser(ctx, a); err != nil { + t.Fatal(err) + } + if err := m.CreateUser(ctx, b); err != nil { + t.Fatal(err) + } + + var wg sync.WaitGroup + errs := make(chan error, 2) + wg.Add(2) + go func() { + defer wg.Done() + errs <- m.SetUserRole(ctx, a.ID, RoleUser) + }() + go func() { + defer wg.Done() + errs <- m.SetUserRole(ctx, b.ID, RoleUser) + }() + wg.Wait() + close(errs) + + var ok, lastAdmin int + for err := range errs { + switch err { + case nil: + ok++ + case ErrLastAdmin: + lastAdmin++ + default: + t.Fatalf("unexpected error: %v", err) + } + } + if ok != 1 || lastAdmin != 1 { + t.Fatalf("want 1 success and 1 ErrLastAdmin, got ok=%d lastAdmin=%d", ok, lastAdmin) + } + n, err := m.CountAdmins(ctx) + if err != nil { + t.Fatal(err) + } + if n != 1 { + t.Fatalf("admins remaining = %d, want 1", n) + } +} diff --git a/internal/store/postgres_store.go b/internal/store/postgres_store.go new file mode 100644 index 0000000..e054677 --- /dev/null +++ b/internal/store/postgres_store.go @@ -0,0 +1,86 @@ +package store + +import ( + "context" + "database/sql" +) + +// Postgres implements Store against a sqlc-backed database. +type Postgres struct { + db *sql.DB +} + +// NewPostgres wraps db as a Store. +func NewPostgres(db *sql.DB) *Postgres { + return &Postgres{db: db} +} + +func (p *Postgres) CreateUser(ctx context.Context, u *User) error { + u.db = p.db + return u.Create(ctx) +} + +func (p *Postgres) UserByID(ctx context.Context, id string) (*User, error) { + return UserByID(ctx, p.db, id) +} + +func (p *Postgres) UserByUsername(ctx context.Context, username string) (*User, error) { + return UserByUsername(ctx, p.db, username) +} + +func (p *Postgres) ListUsers(ctx context.Context) ([]User, error) { + return ListUsers(ctx, p.db) +} + +func (p *Postgres) CountAdmins(ctx context.Context) (int, error) { + return CountAdmins(ctx, p.db) +} + +func (p *Postgres) SetUserRole(ctx context.Context, id string, role Role) error { + u := &User{ID: id, db: p.db} + return u.SetRole(ctx, role) +} + +func (p *Postgres) SaveUserProfile(ctx context.Context, u *User) error { + u.db = p.db + return u.SaveProfile(ctx) +} + +func (p *Postgres) CreateQuestion(ctx context.Context, q *RankedQuestion) error { + q.db = p.db + return q.Create(ctx) +} + +func (p *Postgres) GetQuestion(ctx context.Context, id, viewerID string) (*RankedQuestion, error) { + return GetQuestion(ctx, p.db, id, viewerID) +} + +func (p *Postgres) ListHunt(ctx context.Context, huntDate, viewerID string) ([]RankedQuestion, error) { + return ListHunt(ctx, p.db, huntDate, viewerID) +} + +func (p *Postgres) ListQuestionsByAuthor(ctx context.Context, authorID string) ([]RankedQuestion, error) { + return ListQuestionsByAuthor(ctx, p.db, authorID) +} + +func (p *Postgres) ListQuestionsAnsweredBy(ctx context.Context, adminID string) ([]RankedQuestion, error) { + return ListQuestionsAnsweredBy(ctx, p.db, adminID) +} + +func (p *Postgres) HideQuestion(ctx context.Context, id string) error { + q := &RankedQuestion{ID: id, db: p.db} + return q.Hide(ctx) +} + +func (p *Postgres) GetAnswer(ctx context.Context, questionID string) (*Answer, error) { + return GetAnswer(ctx, p.db, questionID) +} + +func (p *Postgres) UpsertAnswer(ctx context.Context, a *Answer) error { + a.db = p.db + return a.Upsert(ctx) +} + +func (p *Postgres) Vote(ctx context.Context, userID, questionID string, value int) error { + return Vote(ctx, p.db, userID, questionID, value) +} diff --git a/internal/store/store.go b/internal/store/store.go new file mode 100644 index 0000000..8a93a1c --- /dev/null +++ b/internal/store/store.go @@ -0,0 +1,26 @@ +package store + +import "context" + +// Store is the application persistence API used by the web layer. +type Store interface { + CreateUser(ctx context.Context, u *User) error + UserByID(ctx context.Context, id string) (*User, error) + UserByUsername(ctx context.Context, username string) (*User, error) + ListUsers(ctx context.Context) ([]User, error) + CountAdmins(ctx context.Context) (int, error) + SetUserRole(ctx context.Context, id string, role Role) error + SaveUserProfile(ctx context.Context, u *User) error + + CreateQuestion(ctx context.Context, q *RankedQuestion) error + GetQuestion(ctx context.Context, id, viewerID string) (*RankedQuestion, error) + ListHunt(ctx context.Context, huntDate, viewerID string) ([]RankedQuestion, error) + ListQuestionsByAuthor(ctx context.Context, authorID string) ([]RankedQuestion, error) + ListQuestionsAnsweredBy(ctx context.Context, adminID string) ([]RankedQuestion, error) + HideQuestion(ctx context.Context, id string) error + + GetAnswer(ctx context.Context, questionID string) (*Answer, error) + UpsertAnswer(ctx context.Context, a *Answer) error + + Vote(ctx context.Context, userID, questionID string, value int) error +} diff --git a/internal/web/admin.go b/internal/web/admin.go index b44c966..a840cad 100644 --- a/internal/web/admin.go +++ b/internal/web/admin.go @@ -28,7 +28,7 @@ func (s *Server) handleAdminUsers(w http.ResponseWriter, r *http.Request) { if s.requireAdmin(w, r) == nil { return } - users, err := store.ListUsers(r.Context(), s.db) + users, err := s.store.ListUsers(r.Context()) if err != nil { http.Error(w, "could not load users", http.StatusInternalServerError) return @@ -48,14 +48,14 @@ func (s *Server) handleAdminSetRole(w http.ResponseWriter, r *http.Request) { } id := chi.URLParam(r, "id") role := store.Role(r.PostFormValue("role")) - u, err := store.UserByID(r.Context(), s.db, id) + _, err := s.store.UserByID(r.Context(), id) if err != nil { http.Error(w, "could not update role", http.StatusBadRequest) return } - err = u.SetRole(r.Context(), role) + err = s.store.SetUserRole(r.Context(), id, role) if errors.Is(err, store.ErrLastAdmin) { - users, listErr := store.ListUsers(r.Context(), s.db) + users, listErr := s.store.ListUsers(r.Context()) if listErr != nil { http.Error(w, "could not demote last admin", http.StatusBadRequest) return diff --git a/internal/web/auth.go b/internal/web/auth.go index 307900f..683b537 100644 --- a/internal/web/auth.go +++ b/internal/web/auth.go @@ -43,7 +43,7 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { username := strings.TrimSpace(r.PostFormValue("username")) password := r.PostFormValue("password") next := safeNext(r.PostFormValue("next")) - u, err := store.UserByUsername(r.Context(), s.db, username) + u, err := s.store.UserByUsername(r.Context(), username) if err != nil || bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password)) != nil { w.WriteHeader(http.StatusUnauthorized) s.exec(w, "login", authPage{ @@ -94,7 +94,7 @@ func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) { } role := store.RoleUser if s.cfg.AdminUsername != "" && store.NormalizeUsername(username) == store.NormalizeUsername(s.cfg.AdminUsername) { - n, err := store.CountAdmins(r.Context(), s.db) + n, err := s.store.CountAdmins(r.Context()) if err != nil { http.Error(w, "could not create account", http.StatusInternalServerError) return @@ -103,11 +103,12 @@ func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) { role = store.RoleAdmin } } - u := store.NewUser(s.db) - u.Username = username - u.PasswordHash = string(hash) - u.Role = role - if err := u.Create(r.Context()); err != nil { + u := &store.User{ + Username: username, + PasswordHash: string(hash), + Role: role, + } + if err := s.store.CreateUser(r.Context(), u); err != nil { p.Error = "That username is taken." s.exec(w, "register", p) return diff --git a/internal/web/helpers_test.go b/internal/web/helpers_test.go new file mode 100644 index 0000000..4c95805 --- /dev/null +++ b/internal/web/helpers_test.go @@ -0,0 +1,105 @@ +package web + +import ( + "bytes" + "encoding/binary" + "hash/crc32" + "image" + "image/jpeg" + "image/png" + "strings" + "testing" +) + +func TestTruncateRunes(t *testing.T) { + tests := []struct { + in string + max int + want string + }{ + {"abc", 10, "abc"}, + {"abcdef", 3, "abc"}, + {"héllo", 3, "hél"}, + {"🙂🙂🙂", 2, "🙂🙂"}, + {"世界和平", 2, "世界"}, + {"abc", 0, ""}, + {"abc", -1, ""}, + {"", 5, ""}, + } + for _, tc := range tests { + if got := truncateRunes(tc.in, tc.max); got != tc.want { + t.Fatalf("truncateRunes(%q, %d)=%q want %q", tc.in, tc.max, got, tc.want) + } + } +} + +func TestPrepareAvatar(t *testing.T) { + var pngBuf bytes.Buffer + if err := png.Encode(&pngBuf, image.NewRGBA(image.Rect(0, 0, 2, 2))); err != nil { + t.Fatal(err) + } + var jpegBuf bytes.Buffer + if err := jpeg.Encode(&jpegBuf, image.NewRGBA(image.Rect(0, 0, 2, 2)), &jpeg.Options{Quality: 90}); err != nil { + t.Fatal(err) + } + + oversized := bytes.Repeat([]byte{0x89}, (2<<20)+2) + + tests := []struct { + name string + in []byte + max int64 + wantExt string + wantErr string + }{ + {name: "png", in: pngBuf.Bytes(), max: 2 << 20, wantExt: ".png"}, + {name: "jpeg", in: jpegBuf.Bytes(), max: 2 << 20, wantExt: ".jpg"}, + {name: "empty", in: nil, max: 2 << 20, wantErr: "empty"}, + {name: "invalid", in: []byte("not-an-image"), max: 2 << 20, wantErr: "unsupported"}, + {name: "oversized", in: oversized, max: 2 << 20, wantErr: "too large"}, + {name: "huge dims", in: pngWithDims(100000, 100000), max: 2 << 20, wantErr: "dimensions"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + body, ext, ct, err := prepareAvatar(bytes.NewReader(tc.in), tc.max) + if tc.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("err=%v want substring %q", err, tc.wantErr) + } + return + } + if err != nil { + t.Fatal(err) + } + if ext != tc.wantExt { + t.Fatalf("ext=%q want %q", ext, tc.wantExt) + } + if len(body) == 0 || ct == "" { + t.Fatalf("empty output body/ct") + } + }) + } +} + +func pngWithDims(w, h int) []byte { + var buf bytes.Buffer + buf.Write([]byte{0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a}) + var ihdr bytes.Buffer + _ = binary.Write(&ihdr, binary.BigEndian, uint32(w)) + _ = binary.Write(&ihdr, binary.BigEndian, uint32(h)) + ihdr.Write([]byte{8, 2, 0, 0, 0}) // bit depth, color type, compression, filter, interlace + writePNGChunk(&buf, "IHDR", ihdr.Bytes()) + writePNGChunk(&buf, "IDAT", []byte{0x08, 0xd7, 0x63, 0xf8, 0xcf, 0xc0, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01}) + writePNGChunk(&buf, "IEND", nil) + return buf.Bytes() +} + +func writePNGChunk(buf *bytes.Buffer, name string, data []byte) { + _ = binary.Write(buf, binary.BigEndian, uint32(len(data))) + buf.WriteString(name) + buf.Write(data) + crc := crc32.NewIEEE() + _, _ = crc.Write([]byte(name)) + _, _ = crc.Write(data) + _ = binary.Write(buf, binary.BigEndian, crc.Sum32()) +} diff --git a/internal/web/profile.go b/internal/web/profile.go index 9bf771b..536c5ca 100644 --- a/internal/web/profile.go +++ b/internal/web/profile.go @@ -99,7 +99,7 @@ func (s *Server) handleProfile(w http.ResponseWriter, r *http.Request) { if avatarURL != "" { u.AvatarURL = avatarURL } - if err := u.SaveProfile(r.Context()); err != nil { + if err := s.store.SaveUserProfile(r.Context(), u); err != nil { http.Error(w, "could not save profile", http.StatusInternalServerError) return } @@ -131,13 +131,29 @@ func prepareAvatar(r io.Reader, maxBytes int64) (body []byte, ext, contentType s return nil, "", "", fmt.Errorf("unsupported type %s", sniff) } - img, format, err := image.Decode(bytes.NewReader(raw)) + cfg, format, err := image.DecodeConfig(bytes.NewReader(raw)) if err != nil { return nil, "", "", err } + const maxDim = 4096 + const maxPixels = 4096 * 4096 + if cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width > maxDim || cfg.Height > maxDim { + return nil, "", "", fmt.Errorf("image dimensions out of range") + } + if int64(cfg.Width)*int64(cfg.Height) > maxPixels { + return nil, "", "", fmt.Errorf("image too many pixels") + } + + img, decodedFormat, err := image.Decode(bytes.NewReader(raw)) + if err != nil { + return nil, "", "", err + } + if format != "" { + decodedFormat = format + } var out bytes.Buffer - switch format { + switch decodedFormat { case "jpeg": if err := jpeg.Encode(&out, img, &jpeg.Options{Quality: 90}); err != nil { return nil, "", "", err @@ -149,7 +165,7 @@ func prepareAvatar(r io.Reader, maxBytes int64) (body []byte, ext, contentType s } return out.Bytes(), ".png", "image/png", nil default: - return nil, "", "", fmt.Errorf("unsupported format %s", format) + return nil, "", "", fmt.Errorf("unsupported format %s", decodedFormat) } } @@ -161,16 +177,16 @@ func (s *Server) renderProfile(w http.ResponseWriter, r *http.Request, u *store. ) if u.Admin() { label = "Questions you answered" - questions, err = store.ListQuestionsAnsweredBy(r.Context(), s.db, u.ID) + questions, err = s.store.ListQuestionsAnsweredBy(r.Context(), u.ID) } else { label = "Your questions" - questions, err = store.ListQuestionsByAuthor(r.Context(), s.db, u.ID) + questions, err = s.store.ListQuestionsByAuthor(r.Context(), u.ID) } if err != nil { http.Error(w, "could not load questions", http.StatusInternalServerError) return } - if fresh, e := store.UserByID(r.Context(), s.db, u.ID); e == nil { + if fresh, e := s.store.UserByID(r.Context(), u.ID); e == nil { u = fresh } p := s.basePage(r, "Profile") diff --git a/internal/web/server.go b/internal/web/server.go index c05666b..4be3153 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -3,7 +3,6 @@ package web import ( "context" "crypto/rand" - "database/sql" "encoding/hex" "fmt" "html/template" @@ -31,7 +30,7 @@ type Config struct { } type Server struct { - db *sql.DB + store store.Store sessions *scs.SessionManager tmpl *template.Template cfg Config @@ -85,7 +84,7 @@ type voteCtx struct { Question store.RankedQuestion } -func New(db *sql.DB, sessionStore scs.Store, templateFS fs.FS, staticFS fs.FS, cfg Config) (*Server, error) { +func New(st store.Store, sessionStore scs.Store, templateFS fs.FS, staticFS fs.FS, cfg Config) (*Server, error) { if cfg.Blob == nil { cfg.Blob = blob.Disabled{} } @@ -125,7 +124,7 @@ func New(db *sql.DB, sessionStore scs.Store, templateFS fs.FS, staticFS fs.FS, c } return &Server{ - db: db, + store: st, sessions: sessions, tmpl: tmpl, cfg: cfg, @@ -181,7 +180,7 @@ func (s *Server) withUser(next http.Handler) http.Handler { } id := s.sessions.GetString(r.Context(), "user_id") if id != "" { - u, err := store.UserByID(r.Context(), s.db, id) + u, err := s.store.UserByID(r.Context(), id) if err == nil { r = r.WithContext(context.WithValue(r.Context(), userKey, u)) } @@ -259,7 +258,7 @@ func (s *Server) renderHunt(w http.ResponseWriter, r *http.Request, date string) if u := currentUser(r); u != nil { viewer = u.ID } - questions, err := store.ListHunt(r.Context(), s.db, date, viewer) + questions, err := s.store.ListHunt(r.Context(), date, viewer) if err != nil { http.Error(w, "could not load questions", http.StatusInternalServerError) return @@ -319,12 +318,13 @@ func (s *Server) handleSubmit(w http.ResponseWriter, r *http.Request) { if len(city) > 80 { city = truncateRunes(city, 80) } - q := store.NewQuestion(s.db) - q.AuthorID = u.ID - q.Title = title - q.Body = body - q.City = city - if err := q.Create(r.Context()); err != nil { + q := &store.RankedQuestion{ + AuthorID: u.ID, + Title: title, + Body: body, + City: city, + } + if err := s.store.CreateQuestion(r.Context(), q); err != nil { http.Error(w, "could not save question", http.StatusInternalServerError) return } @@ -337,14 +337,14 @@ func (s *Server) handleQuestion(w http.ResponseWriter, r *http.Request) { if u := currentUser(r); u != nil { viewer = u.ID } - q, err := store.GetQuestion(r.Context(), s.db, id, viewer) + q, err := s.store.GetQuestion(r.Context(), id, viewer) if err != nil || (q.Hidden && !currentUser(r).Admin()) { http.NotFound(w, r) return } var ans *store.Answer if q.Answered { - ans, _ = store.GetAnswer(r.Context(), s.db, q.ID) + ans, _ = s.store.GetAnswer(r.Context(), q.ID) } s.exec(w, "question", questionPage{ page: s.basePage(r, q.Title), @@ -377,7 +377,7 @@ func (s *Server) handleVote(w http.ResponseWriter, r *http.Request) { http.Error(w, "invalid vote", http.StatusBadRequest) return } - if err := store.Vote(r.Context(), s.db, u.ID, id, value); err != nil { + if err := s.store.Vote(r.Context(), u.ID, id, value); err != nil { http.Error(w, "could not vote", http.StatusInternalServerError) return } @@ -388,7 +388,7 @@ func (s *Server) handleVote(w http.ResponseWriter, r *http.Request) { s.renderLeaderboard(w, r, date) return } - q, err := store.GetQuestion(r.Context(), s.db, id, u.ID) + q, err := s.store.GetQuestion(r.Context(), id, u.ID) if err != nil { http.Error(w, "not found", http.StatusNotFound) return @@ -421,7 +421,7 @@ func (s *Server) renderLeaderboard(w http.ResponseWriter, r *http.Request, date if u := currentUser(r); u != nil { viewer = u.ID } - questions, err := store.ListHunt(r.Context(), s.db, date, viewer) + questions, err := s.store.ListHunt(r.Context(), date, viewer) if err != nil { http.Error(w, "could not load questions", http.StatusInternalServerError) return @@ -451,15 +451,16 @@ func (s *Server) handleAnswer(w http.ResponseWriter, r *http.Request) { if len(body) > 12000 { body = truncateRunes(body, 12000) } - ans := store.NewAnswer(s.db) - ans.QuestionID = id - ans.AuthorID = u.ID - ans.Body = body - if err := ans.Upsert(r.Context()); err != nil { + ans := &store.Answer{ + QuestionID: id, + AuthorID: u.ID, + Body: body, + } + if err := s.store.UpsertAnswer(r.Context(), ans); err != nil { http.Error(w, "could not save answer", http.StatusInternalServerError) return } - saved, err := store.GetAnswer(r.Context(), s.db, id) + saved, err := s.store.GetAnswer(r.Context(), id) if err != nil { http.Error(w, "could not load answer", http.StatusInternalServerError) return @@ -481,12 +482,12 @@ func (s *Server) handleHide(w http.ResponseWriter, r *http.Request) { return } id := chi.URLParam(r, "id") - q, err := store.GetQuestion(r.Context(), s.db, id, u.ID) + q, err := s.store.GetQuestion(r.Context(), id, u.ID) if err != nil { http.NotFound(w, r) return } - if err := q.Hide(r.Context()); err != nil { + if err := s.store.HideQuestion(r.Context(), id); err != nil { http.Error(w, "could not hide", http.StatusInternalServerError) return } diff --git a/internal/web/server_test.go b/internal/web/server_test.go index 530a8bd..c7a0da4 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -3,85 +3,83 @@ package web import ( "bytes" "context" - "database/sql" "image" "image/png" "mime/multipart" "net/http" "net/http/httptest" - "os" "strings" "testing" - "github.com/alexedwards/scs/v2" + "github.com/alexedwards/scs/v2/memstore" "github.com/google/uuid" - "github.com/joho/godotenv" "golang.org/x/crypto/bcrypt" "plumber" "plumber/internal/blob" + "plumber/internal/pacific" "plumber/internal/store" ) -func testDBURL() string { - _ = godotenv.Load() - return strings.TrimSpace(os.Getenv("TEST_DATABASE_URL")) +func newTestServer(t *testing.T, cfg Config) (*Server, *store.Memory) { + t.Helper() + mem := store.NewMemory() + return newTestServerStore(t, mem, cfg), mem } -func newTestServer(t *testing.T, cfg Config) (*Server, *sql.DB) { +func newTestServerStore(t *testing.T, st store.Store, cfg Config) *Server { t.Helper() - url := testDBURL() - if url == "" { - t.Skip("set TEST_DATABASE_URL for web tests") - } - db, sessions, err := store.OpenPostgres(url, plumber.SchemaSQL) - if err != nil { - t.Fatalf("open postgres: %v", err) - } - t.Cleanup(func() { - sessions.Close() - _ = db.Close() - }) if cfg.Blob == nil { cfg.Blob = blob.Disabled{} } - srv, err := New(db, sessions.Store(), plumber.TemplateFS, plumber.StaticFS, cfg) + srv, err := New(st, memstore.New(), plumber.TemplateFS, plumber.StaticFS, cfg) if err != nil { t.Fatal(err) } - return srv, db + return srv } func uniq(prefix string) string { return prefix + "_" + strings.ReplaceAll(uuid.NewString()[:8], "-", "") } -func seedUser(t *testing.T, db *sql.DB, username, password string, role store.Role) *store.User { +func seedUser(t *testing.T, st store.Store, username, password string, role store.Role) *store.User { t.Helper() hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost) if err != nil { t.Fatal(err) } - u := store.NewUser(db) - u.Username = username - u.PasswordHash = string(hash) - u.Role = role - if err := u.Create(context.Background()); err != nil { + u := &store.User{ + Username: username, + PasswordHash: string(hash), + Role: role, + } + if err := st.CreateUser(context.Background(), u); err != nil { t.Fatal(err) } return u } +func sessionValue(cookies []*http.Cookie) string { + for _, c := range cookies { + if c.Name == "plumber_session" { + return c.Value + } + } + return "" +} + func loginUser(t *testing.T, h http.Handler, username, password string) []*http.Cookie { t.Helper() rec := httptest.NewRecorder() h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/login", nil)) - cookies := rec.Result().Cookies() + pre := rec.Result().Cookies() + preToken := sessionValue(pre) csrf := csrfFrom(rec.Body.String()) form := strings.NewReader("_csrf=" + csrf + "&username=" + username + "&password=" + password) req := httptest.NewRequest(http.MethodPost, "/login", form) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - for _, c := range cookies { + for _, c := range pre { req.AddCookie(c) } rec = httptest.NewRecorder() @@ -89,7 +87,48 @@ func loginUser(t *testing.T, h http.Handler, username, password string) []*http. if rec.Code != http.StatusSeeOther { t.Fatalf("login %s: %d %s", username, rec.Code, rec.Body.String()) } - return mergeCookies(cookies, rec.Result().Cookies()) + post := mergeCookies(pre, rec.Result().Cookies()) + postToken := sessionValue(post) + if preToken == "" || postToken == "" || preToken == postToken { + t.Fatalf("expected session token rotation on login; pre=%q post=%q", preToken, postToken) + } + // Old anonymous token must not unlock authenticated routes. + req = httptest.NewRequest(http.MethodGet, "/profile", nil) + for _, c := range pre { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("pre-auth cookie should not access profile, got %d", rec.Code) + } + return post +} + +func registerUser(t *testing.T, h http.Handler, username, password string) []*http.Cookie { + t.Helper() + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/register", nil)) + pre := rec.Result().Cookies() + preToken := sessionValue(pre) + csrf := csrfFrom(rec.Body.String()) + form := strings.NewReader("_csrf=" + csrf + "&username=" + username + "&password=" + password) + req := httptest.NewRequest(http.MethodPost, "/register", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range pre { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("register %s: %d %s", username, rec.Code, rec.Body.String()) + } + post := mergeCookies(pre, rec.Result().Cookies()) + postToken := sessionValue(post) + if preToken == "" || postToken == "" || preToken == postToken { + t.Fatalf("expected session token rotation on register; pre=%q post=%q", preToken, postToken) + } + return post } func TestHomeEmptyAndViewport(t *testing.T) { @@ -113,36 +152,18 @@ func TestRegisterLoginAsk(t *testing.T) { srv, _ := newTestServer(t, Config{}) h := srv.Handler() name := uniq("ask") + session := registerUser(t, h, name, "hunter22") rec := httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/register", nil)) - cookie := rec.Result().Cookies() - csrf := csrfFrom(rec.Body.String()) - if csrf == "" { - t.Fatal("no csrf") - } - form := strings.NewReader("_csrf=" + csrf + "&username=" + name + "&password=hunter22") - req := httptest.NewRequest(http.MethodPost, "/register", form) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - for _, c := range cookie { - req.AddCookie(c) - } - rec = httptest.NewRecorder() - h.ServeHTTP(rec, req) - if rec.Code != http.StatusSeeOther { - t.Fatalf("register status %d %s", rec.Code, rec.Body.String()) - } - session := rec.Result().Cookies() - req = httptest.NewRequest(http.MethodGet, "/submit", nil) + req := httptest.NewRequest(http.MethodGet, "/submit", nil) for _, c := range session { req.AddCookie(c) } - rec = httptest.NewRecorder() h.ServeHTTP(rec, req) if rec.Code != 200 { t.Fatalf("submit form %d", rec.Code) } - csrf = csrfFrom(rec.Body.String()) - form = strings.NewReader("_csrf=" + csrf + "&title=Leaky+faucet&body=Drip+all+night.&city=Oakland") + csrf := csrfFrom(rec.Body.String()) + form := strings.NewReader("_csrf=" + csrf + "&title=Leaky+faucet&body=Drip+all+night.&city=Oakland") req = httptest.NewRequest(http.MethodPost, "/submit", form) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") for _, c := range session { @@ -158,107 +179,20 @@ func TestRegisterLoginAsk(t *testing.T) { } } -func TestSessionSurvivesServerRestart(t *testing.T) { - url := testDBURL() - if url == "" { - t.Skip("set TEST_DATABASE_URL for web tests") - } - db, sessions, err := store.OpenPostgres(url, plumber.SchemaSQL) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { - sessions.Close() - _ = db.Close() - }) - sessionStore := sessions.Store() - - srv1, err := New(db, sessionStore, plumber.TemplateFS, plumber.StaticFS, Config{}) - if err != nil { - t.Fatal(err) - } - h1 := srv1.Handler() - name := uniq("sess") - - rec := httptest.NewRecorder() - h1.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/register", nil)) - preCookies := rec.Result().Cookies() - csrf := csrfFrom(rec.Body.String()) - form := strings.NewReader("_csrf=" + csrf + "&username=" + name + "&password=hunter22") - req := httptest.NewRequest(http.MethodPost, "/register", form) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - for _, c := range preCookies { - req.AddCookie(c) - } - rec = httptest.NewRecorder() - h1.ServeHTTP(rec, req) - if rec.Code != http.StatusSeeOther { - t.Fatalf("register status %d %s", rec.Code, rec.Body.String()) - } - sessionCookies := mergeCookies(preCookies, rec.Result().Cookies()) - - srv2, err := New(db, sessionStore, plumber.TemplateFS, plumber.StaticFS, Config{}) - if err != nil { - t.Fatal(err) - } - req = httptest.NewRequest(http.MethodGet, "/submit", nil) - for _, c := range sessionCookies { - req.AddCookie(c) - } - rec = httptest.NewRecorder() - srv2.Handler().ServeHTTP(rec, req) - if rec.Code != http.StatusOK { - t.Fatalf("expected authenticated submit form after restart, got %d: %s", rec.Code, rec.Body.String()) - } - if !strings.Contains(rec.Body.String(), "Ask a question") { - t.Fatal("session did not survive restart") - } -} - -func registerUser(t *testing.T, h http.Handler, username, password string) []*http.Cookie { - t.Helper() - rec := httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/register", nil)) - cookies := rec.Result().Cookies() - csrf := csrfFrom(rec.Body.String()) - form := strings.NewReader("_csrf=" + csrf + "&username=" + username + "&password=" + password) - req := httptest.NewRequest(http.MethodPost, "/register", form) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - for _, c := range cookies { - req.AddCookie(c) - } - rec = httptest.NewRecorder() - h.ServeHTTP(rec, req) - if rec.Code != http.StatusSeeOther { - t.Fatalf("register %s: %d %s", username, rec.Code, rec.Body.String()) - } - return mergeCookies(cookies, rec.Result().Cookies()) -} - func TestAdminSeedOnlyWhenNoAdmins(t *testing.T) { - srv, db := newTestServer(t, Config{}) - n, err := store.CountAdmins(context.Background(), db) - if err != nil { - t.Fatal(err) - } - if n > 0 { - t.Skip("admin already exists in database; bootstrap seed not exercised") - } + mem := store.NewMemory() adminName := uniq("seed") - srv.cfg.AdminUsername = adminName + srv := newTestServerStore(t, mem, Config{AdminUsername: adminName}) h := srv.Handler() registerUser(t, h, adminName, "hunter22") - u, err := store.UserByUsername(context.Background(), db, adminName) + u, err := mem.UserByUsername(context.Background(), adminName) if err != nil || !u.Admin() { t.Fatalf("first matching registrant should be admin: %+v %v", u, err) } later := uniq("later") - srv2, err := New(db, scs.New().Store, plumber.TemplateFS, plumber.StaticFS, Config{AdminUsername: later}) - if err != nil { - t.Fatal(err) - } + srv2 := newTestServerStore(t, mem, Config{AdminUsername: later}) registerUser(t, srv2.Handler(), later, "hunter22") - u2, err := store.UserByUsername(context.Background(), db, later) + u2, err := mem.UserByUsername(context.Background(), later) if err != nil { t.Fatal(err) } @@ -268,12 +202,12 @@ func TestAdminSeedOnlyWhenNoAdmins(t *testing.T) { } func TestAdminUsersPageAccessAndRoles(t *testing.T) { - srv, db := newTestServer(t, Config{}) + srv, mem := newTestServer(t, Config{}) h := srv.Handler() hubName := uniq("hub") bobName := uniq("bob") carolName := uniq("carol") - seedUser(t, db, hubName, "hunter22", store.RoleAdmin) + seedUser(t, mem, hubName, "hunter22", store.RoleAdmin) adminCookies := loginUser(t, h, hubName, "hunter22") registerUser(t, h, bobName, "hunter22") @@ -290,7 +224,7 @@ func TestAdminUsersPageAccessAndRoles(t *testing.T) { t.Fatal("missing bob on admin page") } - bob, err := store.UserByUsername(context.Background(), db, bobName) + bob, err := mem.UserByUsername(context.Background(), bobName) if err != nil { t.Fatal(err) } @@ -306,15 +240,15 @@ func TestAdminUsersPageAccessAndRoles(t *testing.T) { if rec.Code != http.StatusSeeOther { t.Fatalf("promote %d %s", rec.Code, rec.Body.String()) } - bob, _ = store.UserByUsername(context.Background(), db, bobName) + bob, _ = mem.UserByUsername(context.Background(), bobName) if !bob.Admin() { t.Fatal("bob should be admin") } - bobCookies := registerUser(t, h, carolName, "hunter22") + carolCookies := registerUser(t, h, carolName, "hunter22") rec = httptest.NewRecorder() req = httptest.NewRequest(http.MethodGet, "/admin/users", nil) - for _, c := range bobCookies { + for _, c := range carolCookies { req.AddCookie(c) } h.ServeHTTP(rec, req) @@ -322,7 +256,6 @@ func TestAdminUsersPageAccessAndRoles(t *testing.T) { t.Fatalf("non-admin expected 403, got %d", rec.Code) } - // Demote bob back to user rec = httptest.NewRecorder() req = httptest.NewRequest(http.MethodGet, "/admin/users", nil) for _, c := range adminCookies { @@ -342,15 +275,7 @@ func TestAdminUsersPageAccessAndRoles(t *testing.T) { t.Fatalf("demote bob %d", rec.Code) } - admins, err := store.CountAdmins(context.Background(), db) - if err != nil { - t.Fatal(err) - } - if admins != 1 { - t.Skip("shared database has other admins; last-admin demote not isolated") - } - - hub, err := store.UserByUsername(context.Background(), db, hubName) + hub, err := mem.UserByUsername(context.Background(), hubName) if err != nil { t.Fatal(err) } @@ -375,7 +300,7 @@ func TestAdminUsersPageAccessAndRoles(t *testing.T) { if !strings.Contains(rec.Body.String(), "Cannot demote the last admin") { t.Fatalf("missing last-admin error: %s", rec.Body.String()) } - hub, _ = store.UserByUsername(context.Background(), db, hubName) + hub, _ = mem.UserByUsername(context.Background(), hubName) if !hub.Admin() { t.Fatal("hub must remain admin") } @@ -395,7 +320,7 @@ func (f *fakeBlob) Upload(_ context.Context, obj blob.FileUpload) (string, error } func TestProfilePageAndState(t *testing.T) { - srv, db := newTestServer(t, Config{}) + srv, mem := newTestServer(t, Config{}) h := srv.Handler() name := uniq("alice") cookies := registerUser(t, h, name, "hunter22") @@ -432,7 +357,7 @@ func TestProfilePageAndState(t *testing.T) { if rec.Code != http.StatusSeeOther { t.Fatalf("save profile %d %s", rec.Code, rec.Body.String()) } - u, err := store.UserByUsername(context.Background(), db, name) + u, err := mem.UserByUsername(context.Background(), name) if err != nil || u.State != "CA" { t.Fatalf("state not saved: %+v %v", u, err) } @@ -463,27 +388,29 @@ func TestProfilePageAndState(t *testing.T) { func TestProfileAdminAnsweredListAndAvatarUpload(t *testing.T) { fb := &fakeBlob{} - srv, db := newTestServer(t, Config{Blob: fb}) + srv, mem := newTestServer(t, Config{Blob: fb}) h := srv.Handler() hubName := uniq("hub") aliceName := uniq("alice") - hub := seedUser(t, db, hubName, "hunter22", store.RoleAdmin) - alice := seedUser(t, db, aliceName, "hunter22", store.RoleUser) + hub := seedUser(t, mem, hubName, "hunter22", store.RoleAdmin) + alice := seedUser(t, mem, aliceName, "hunter22", store.RoleUser) adminCookies := loginUser(t, h, hubName, "hunter22") - q := store.NewQuestion(db) - q.AuthorID = alice.ID - q.Title = "Drip" - q.Body = "Under sink" - q.City = "Oakland" - if err := q.Create(context.Background()); err != nil { + q := &store.RankedQuestion{ + AuthorID: alice.ID, + Title: "Drip", + Body: "Under sink", + City: "Oakland", + } + if err := mem.CreateQuestion(context.Background(), q); err != nil { t.Fatal(err) } - ans := store.NewAnswer(db) - ans.QuestionID = q.ID - ans.AuthorID = hub.ID - ans.Body = "Replace the cartridge." - if err := ans.Upsert(context.Background()); err != nil { + ans := &store.Answer{ + QuestionID: q.ID, + AuthorID: hub.ID, + Body: "Replace the cartridge.", + } + if err := mem.UpsertAnswer(context.Background(), ans); err != nil { t.Fatal(err) } @@ -528,12 +455,172 @@ func TestProfileAdminAnsweredListAndAvatarUpload(t *testing.T) { if fb.calls != 1 { t.Fatalf("expected 1 upload, got %d", fb.calls) } - hub, _ = store.UserByUsername(context.Background(), db, hubName) + hub, _ = mem.UserByUsername(context.Background(), hubName) if !strings.Contains(hub.AvatarURL, "cdn.example.com/avatars/") { t.Fatalf("avatar url %q", hub.AvatarURL) } } +func TestMutationsVoteAnswerHideAndCSRF(t *testing.T) { + srv, mem := newTestServer(t, Config{}) + h := srv.Handler() + adminName := uniq("admin") + userName := uniq("user") + admin := seedUser(t, mem, adminName, "hunter22", store.RoleAdmin) + user := seedUser(t, mem, userName, "hunter22", store.RoleUser) + adminCookies := loginUser(t, h, adminName, "hunter22") + userCookies := loginUser(t, h, userName, "hunter22") + + q := &store.RankedQuestion{ + AuthorID: user.ID, + Title: "Pipe noise", + Body: "Clanking", + City: "SF", + HuntDate: pacific.Today(), + } + if err := mem.CreateQuestion(context.Background(), q); err != nil { + t.Fatal(err) + } + + // Missing CSRF + form := strings.NewReader("value=1&view=question") + req := httptest.NewRequest(http.MethodPost, "/questions/"+q.ID+"/vote", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range userCookies { + req.AddCookie(c) + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Fatalf("missing csrf want 403, got %d", rec.Code) + } + + // Anonymous HTMX vote → sign-in prompt + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/login", nil) + h.ServeHTTP(rec, req) + anon := rec.Result().Cookies() + csrf := csrfFrom(rec.Body.String()) + form = strings.NewReader("_csrf=" + csrf + "&value=1&view=question") + req = httptest.NewRequest(http.MethodPost, "/questions/"+q.ID+"/vote", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("HX-Request", "true") + for _, c := range anon { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "Sign in") { + t.Fatalf("anon htmx vote: %d %s", rec.Code, rec.Body.String()) + } + + // User vote + HTMX fragment + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/questions/"+q.ID, nil) + for _, c := range userCookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + csrf = csrfFrom(rec.Body.String()) + form = strings.NewReader("_csrf=" + csrf + "&value=1&view=question") + req = httptest.NewRequest(http.MethodPost, "/questions/"+q.ID+"/vote", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("HX-Request", "true") + for _, c := range userCookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("vote htmx %d %s", rec.Code, rec.Body.String()) + } + got, err := mem.GetQuestion(context.Background(), q.ID, user.ID) + if err != nil || got.UserVote != 1 || got.Score != 1 { + t.Fatalf("vote not applied: %+v %v", got, err) + } + + // Non-admin answer rejected + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/questions/"+q.ID, nil) + for _, c := range userCookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + csrf = csrfFrom(rec.Body.String()) + form = strings.NewReader("_csrf=" + csrf + "&body=Nope") + req = httptest.NewRequest(http.MethodPost, "/questions/"+q.ID+"/answer", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range userCookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Fatalf("non-admin answer want 403, got %d", rec.Code) + } + + // Admin answer success (HTMX) + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/questions/"+q.ID, nil) + for _, c := range adminCookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + csrf = csrfFrom(rec.Body.String()) + form = strings.NewReader("_csrf=" + csrf + "&body=Tighten+the+nuts.") + req = httptest.NewRequest(http.MethodPost, "/questions/"+q.ID+"/answer", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("HX-Request", "true") + for _, c := range adminCookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "Tighten the nuts") { + t.Fatalf("admin answer: %d %s", rec.Code, rec.Body.String()) + } + if _, err := mem.GetAnswer(context.Background(), q.ID); err != nil { + t.Fatal(err) + } + + // Hide invalid id + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/questions/"+q.ID, nil) + for _, c := range adminCookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + csrf = csrfFrom(rec.Body.String()) + form = strings.NewReader("_csrf=" + csrf) + req = httptest.NewRequest(http.MethodPost, "/questions/does-not-exist/hide", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range adminCookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusNotFound { + t.Fatalf("hide missing want 404, got %d", rec.Code) + } + + // Admin hide success + form = strings.NewReader("_csrf=" + csrf) + req = httptest.NewRequest(http.MethodPost, "/questions/"+q.ID+"/hide", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range adminCookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("hide %d %s", rec.Code, rec.Body.String()) + } + hidden, err := mem.GetQuestion(context.Background(), q.ID, admin.ID) + if err != nil || !hidden.Hidden { + t.Fatalf("question not hidden: %+v %v", hidden, err) + } +} + func mergeCookies(sets ...[]*http.Cookie) []*http.Cookie { byName := map[string]*http.Cookie{} for _, set := range sets { From 1a8c4eda1409eb65dbc9bf1a7eb7c2500c0f2cec Mon Sep 17 00:00:00 2001 From: codegirl-007 Date: Sat, 22 Aug 2026 07:58:58 -0700 Subject: [PATCH 12/17] Tighten avatar decode and encoded size limits. Reject images over 1024px before pixel decode, resize down to 512 for storage, and cap re-encoded output at the upload byte limit. --- internal/web/helpers_test.go | 16 +++++++++++ internal/web/profile.go | 55 ++++++++++++++++++++++++++++++++---- 2 files changed, 65 insertions(+), 6 deletions(-) diff --git a/internal/web/helpers_test.go b/internal/web/helpers_test.go index 4c95805..434cc61 100644 --- a/internal/web/helpers_test.go +++ b/internal/web/helpers_test.go @@ -42,6 +42,10 @@ func TestPrepareAvatar(t *testing.T) { if err := jpeg.Encode(&jpegBuf, image.NewRGBA(image.Rect(0, 0, 2, 2)), &jpeg.Options{Quality: 90}); err != nil { t.Fatal(err) } + var largePNG bytes.Buffer + if err := png.Encode(&largePNG, image.NewRGBA(image.Rect(0, 0, 800, 600))); err != nil { + t.Fatal(err) + } oversized := bytes.Repeat([]byte{0x89}, (2<<20)+2) @@ -54,10 +58,12 @@ func TestPrepareAvatar(t *testing.T) { }{ {name: "png", in: pngBuf.Bytes(), max: 2 << 20, wantExt: ".png"}, {name: "jpeg", in: jpegBuf.Bytes(), max: 2 << 20, wantExt: ".jpg"}, + {name: "resize large", in: largePNG.Bytes(), max: 2 << 20, wantExt: ".png"}, {name: "empty", in: nil, max: 2 << 20, wantErr: "empty"}, {name: "invalid", in: []byte("not-an-image"), max: 2 << 20, wantErr: "unsupported"}, {name: "oversized", in: oversized, max: 2 << 20, wantErr: "too large"}, {name: "huge dims", in: pngWithDims(100000, 100000), max: 2 << 20, wantErr: "dimensions"}, + {name: "over decode cap", in: pngWithDims(2048, 2048), max: 2 << 20, wantErr: "dimensions"}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { @@ -77,6 +83,16 @@ func TestPrepareAvatar(t *testing.T) { if len(body) == 0 || ct == "" { t.Fatalf("empty output body/ct") } + if int64(len(body)) > tc.max { + t.Fatalf("encoded size %d exceeds max %d", len(body), tc.max) + } + cfg, _, err := image.DecodeConfig(bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + if cfg.Width > 512 || cfg.Height > 512 { + t.Fatalf("avatar dims %dx%d exceed 512", cfg.Width, cfg.Height) + } }) } } diff --git a/internal/web/profile.go b/internal/web/profile.go index 536c5ca..9a775f5 100644 --- a/internal/web/profile.go +++ b/internal/web/profile.go @@ -12,6 +12,7 @@ import ( "strings" "github.com/google/uuid" + "golang.org/x/image/draw" _ "golang.org/x/image/webp" "plumber/internal/blob" @@ -107,8 +108,8 @@ func (s *Server) handleProfile(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/profile", http.StatusSeeOther) } -// prepareAvatar reads at most maxBytes, sniffs/decodes the image, and re-encodes -// it so only valid image bytes are stored publicly. +// prepareAvatar reads at most maxBytes, sniffs/decodes the image, resizes to a +// small avatar, and re-encodes so only bounded valid image bytes are stored. func prepareAvatar(r io.Reader, maxBytes int64) (body []byte, ext, contentType string, err error) { limited := io.LimitReader(r, maxBytes+1) raw, err := io.ReadAll(limited) @@ -135,9 +136,10 @@ func prepareAvatar(r io.Reader, maxBytes int64) (body []byte, ext, contentType s if err != nil { return nil, "", "", err } - const maxDim = 4096 - const maxPixels = 4096 * 4096 - if cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width > maxDim || cfg.Height > maxDim { + // Cap decoded size before allocating pixel buffers (~4 MiB RGBA at 1024²). + const maxDecodeDim = 1024 + const maxPixels = maxDecodeDim * maxDecodeDim + if cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width > maxDecodeDim || cfg.Height > maxDecodeDim { return nil, "", "", fmt.Errorf("image dimensions out of range") } if int64(cfg.Width)*int64(cfg.Height) > maxPixels { @@ -152,23 +154,64 @@ func prepareAvatar(r io.Reader, maxBytes int64) (body []byte, ext, contentType s decodedFormat = format } + const maxAvatarDim = 512 + img = fitAvatar(img, maxAvatarDim) + var out bytes.Buffer switch decodedFormat { case "jpeg": - if err := jpeg.Encode(&out, img, &jpeg.Options{Quality: 90}); err != nil { + if err := jpeg.Encode(&out, img, &jpeg.Options{Quality: 85}); err != nil { return nil, "", "", err } + if int64(out.Len()) > maxBytes { + return nil, "", "", fmt.Errorf("encoded avatar too large") + } return out.Bytes(), ".jpg", "image/jpeg", nil case "png", "webp": if err := png.Encode(&out, img); err != nil { return nil, "", "", err } + if int64(out.Len()) > maxBytes { + // Fall back to JPEG when PNG balloons past the upload cap. + out.Reset() + if err := jpeg.Encode(&out, img, &jpeg.Options{Quality: 85}); err != nil { + return nil, "", "", err + } + if int64(out.Len()) > maxBytes { + return nil, "", "", fmt.Errorf("encoded avatar too large") + } + return out.Bytes(), ".jpg", "image/jpeg", nil + } return out.Bytes(), ".png", "image/png", nil default: return nil, "", "", fmt.Errorf("unsupported format %s", decodedFormat) } } +// fitAvatar scales img down so both sides are at most maxDim. +func fitAvatar(img image.Image, maxDim int) image.Image { + b := img.Bounds() + w, h := b.Dx(), b.Dy() + if w <= maxDim && h <= maxDim { + return img + } + scale := float64(maxDim) / float64(w) + if float64(h)*scale > float64(maxDim) { + scale = float64(maxDim) / float64(h) + } + nw := int(float64(w) * scale) + nh := int(float64(h) * scale) + if nw < 1 { + nw = 1 + } + if nh < 1 { + nh = 1 + } + dst := image.NewRGBA(image.Rect(0, 0, nw, nh)) + draw.CatmullRom.Scale(dst, dst.Bounds(), img, b, draw.Over, nil) + return dst +} + func (s *Server) renderProfile(w http.ResponseWriter, r *http.Request, u *store.User, errMsg, stateVal string) { var ( questions []store.RankedQuestion From 96b0ce795a0e38e697f6db8882a7c2f54a32c5c1 Mon Sep 17 00:00:00 2001 From: codegirl-007 Date: Sat, 22 Aug 2026 09:55:32 -0700 Subject: [PATCH 13/17] Address follow-up review: cheaper avatars, list limits, less chatter. Switch avatar resize to ApproxBiLinear, cap hunt/profile/admin list queries, drop redundant admin/profile lookups, dedupe CI on app PRs, and refresh stale todo.md notes. --- .github/workflows/ci.yml | 4 ++-- db/queries/questions.sql | 9 +++++--- db/queries/users.sql | 3 ++- internal/store/memory.go | 12 +++++++++++ internal/store/postgres_test.go | 20 +++++------------- internal/store/question.go | 11 ++++++++-- internal/store/sqlc/questions.sql.go | 24 ++++++++++++++++----- internal/store/sqlc/users.sql.go | 5 +++-- internal/store/store.go | 7 +++++++ internal/store/user.go | 2 +- internal/web/admin.go | 7 +------ internal/web/profile.go | 5 +---- todo.md | 31 ++++++++++++++-------------- 13 files changed, 83 insertions(+), 57 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eb0f63c..6df0713 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,9 +1,9 @@ name: CI on: - push: - branches: [app, master, main] pull_request: + push: + branches: [master, main] jobs: test: diff --git a/db/queries/questions.sql b/db/queries/questions.sql index a0a9029..70d62cb 100644 --- a/db/queries/questions.sql +++ b/db/queries/questions.sql @@ -21,7 +21,8 @@ LEFT JOIN votes v ON v.question_id = q.id LEFT JOIN answers a ON a.question_id = q.id WHERE q.hunt_date = sqlc.arg(hunt_date) AND q.hidden = 0 GROUP BY q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, a.question_id -ORDER BY score DESC, q.created_at ASC; +ORDER BY score DESC, q.created_at ASC +LIMIT sqlc.arg(row_limit); -- name: GetQuestion :one SELECT q.id, q.author_id, u.name AS author_name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, @@ -45,7 +46,8 @@ FROM questions q JOIN users u ON u.id = q.author_id LEFT JOIN answers a ON a.question_id = q.id WHERE q.author_id = sqlc.arg(author_id) AND q.hidden = 0 -ORDER BY q.created_at DESC; +ORDER BY q.created_at DESC +LIMIT sqlc.arg(row_limit); -- name: ListQuestionsAnsweredBy :many SELECT q.id, q.author_id, u.name AS author_name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, @@ -56,4 +58,5 @@ FROM answers ans JOIN questions q ON q.id = ans.question_id JOIN users u ON u.id = q.author_id WHERE ans.author_id = sqlc.arg(admin_id) AND q.hidden = 0 -ORDER BY ans.updated_at DESC; +ORDER BY ans.updated_at DESC +LIMIT sqlc.arg(row_limit); diff --git a/db/queries/users.sql b/db/queries/users.sql index 508a327..954fced 100644 --- a/db/queries/users.sql +++ b/db/queries/users.sql @@ -15,7 +15,8 @@ WHERE username = $1; -- name: ListUsers :many SELECT id, username, name, role, avatar_url, state, created_at FROM users -ORDER BY created_at ASC; +ORDER BY created_at ASC +LIMIT sqlc.arg(row_limit); -- name: CountAdmins :one SELECT COUNT(*)::bigint AS count diff --git a/internal/store/memory.go b/internal/store/memory.go index a2e8cad..39c86a7 100644 --- a/internal/store/memory.go +++ b/internal/store/memory.go @@ -92,6 +92,9 @@ func (m *Memory) ListUsers(_ context.Context) ([]User, error) { out = append(out, *u) } sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt < out[j].CreatedAt }) + if len(out) > AdminUsersLimit { + out = out[:AdminUsersLimit] + } return out, nil } @@ -223,6 +226,9 @@ func (m *Memory) ListHunt(_ context.Context, huntDate, viewerID string) ([]Ranke } return out[i].CreatedAt < out[j].CreatedAt }) + if len(out) > HuntListLimit { + out = out[:HuntListLimit] + } return out, nil } @@ -237,6 +243,9 @@ func (m *Memory) ListQuestionsByAuthor(_ context.Context, authorID string) ([]Ra out = append(out, m.annotate(q, "")) } sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt > out[j].CreatedAt }) + if len(out) > ProfileListLimit { + out = out[:ProfileListLimit] + } return out, nil } @@ -257,6 +266,9 @@ func (m *Memory) ListQuestionsAnsweredBy(_ context.Context, adminID string) ([]R out = append(out, rq) } sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt > out[j].CreatedAt }) + if len(out) > ProfileListLimit { + out = out[:ProfileListLimit] + } return out, nil } diff --git a/internal/store/postgres_test.go b/internal/store/postgres_test.go index c854834..6a6a2bd 100644 --- a/internal/store/postgres_test.go +++ b/internal/store/postgres_test.go @@ -1,6 +1,9 @@ package store -import "testing" +import ( + "strings" + "testing" +) func TestNormalizeUsername(t *testing.T) { if got := NormalizeUsername(" Alice_1 "); got != "alice_1" { @@ -14,20 +17,7 @@ func TestPostgresDSNDefaultsSSLMode(t *testing.T) { if err != nil { t.Fatal(err) } - if !containsAny(out, "sslmode=verify-full") { + if !strings.Contains(out, "sslmode=verify-full") { t.Fatalf("missing default sslmode: %s", out) } } - -func containsAny(s string, parts ...string) bool { - for _, p := range parts { - if len(p) > 0 && (len(s) >= len(p)) { - for i := 0; i+len(p) <= len(s); i++ { - if s[i:i+len(p)] == p { - return true - } - } - } - } - return false -} diff --git a/internal/store/question.go b/internal/store/question.go index 0761c19..c00d50b 100644 --- a/internal/store/question.go +++ b/internal/store/question.go @@ -101,6 +101,7 @@ func ListHunt(ctx context.Context, db *sql.DB, huntDate, viewerID string) ([]Ran rows, err := sqlc.New(db).ListHunt(ctx, sqlc.ListHuntParams{ ViewerID: viewerID, HuntDate: huntDate, + RowLimit: HuntListLimit, }) if err != nil { return nil, err @@ -125,7 +126,10 @@ func GetQuestion(ctx context.Context, db *sql.DB, id, viewerID string) (*RankedQ } func ListQuestionsByAuthor(ctx context.Context, db *sql.DB, authorID string) ([]RankedQuestion, error) { - rows, err := sqlc.New(db).ListQuestionsByAuthor(ctx, authorID) + rows, err := sqlc.New(db).ListQuestionsByAuthor(ctx, sqlc.ListQuestionsByAuthorParams{ + AuthorID: authorID, + RowLimit: ProfileListLimit, + }) if err != nil { return nil, err } @@ -137,7 +141,10 @@ func ListQuestionsByAuthor(ctx context.Context, db *sql.DB, authorID string) ([] } func ListQuestionsAnsweredBy(ctx context.Context, db *sql.DB, adminID string) ([]RankedQuestion, error) { - rows, err := sqlc.New(db).ListQuestionsAnsweredBy(ctx, adminID) + rows, err := sqlc.New(db).ListQuestionsAnsweredBy(ctx, sqlc.ListQuestionsAnsweredByParams{ + AdminID: adminID, + RowLimit: ProfileListLimit, + }) if err != nil { return nil, err } diff --git a/internal/store/sqlc/questions.sql.go b/internal/store/sqlc/questions.sql.go index 9b69b70..31bcf09 100644 --- a/internal/store/sqlc/questions.sql.go +++ b/internal/store/sqlc/questions.sql.go @@ -117,11 +117,13 @@ LEFT JOIN answers a ON a.question_id = q.id WHERE q.hunt_date = $2 AND q.hidden = 0 GROUP BY q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, a.question_id ORDER BY score DESC, q.created_at ASC +LIMIT $3 ` type ListHuntParams struct { ViewerID string HuntDate string + RowLimit int32 } type ListHuntRow struct { @@ -140,7 +142,7 @@ type ListHuntRow struct { } func (q *Queries) ListHunt(ctx context.Context, arg ListHuntParams) ([]ListHuntRow, error) { - rows, err := q.db.QueryContext(ctx, listHunt, arg.ViewerID, arg.HuntDate) + rows, err := q.db.QueryContext(ctx, listHunt, arg.ViewerID, arg.HuntDate, arg.RowLimit) if err != nil { return nil, err } @@ -185,8 +187,14 @@ JOIN questions q ON q.id = ans.question_id JOIN users u ON u.id = q.author_id WHERE ans.author_id = $1 AND q.hidden = 0 ORDER BY ans.updated_at DESC +LIMIT $2 ` +type ListQuestionsAnsweredByParams struct { + AdminID string + RowLimit int32 +} + type ListQuestionsAnsweredByRow struct { ID string AuthorID string @@ -202,8 +210,8 @@ type ListQuestionsAnsweredByRow struct { UserVote int64 } -func (q *Queries) ListQuestionsAnsweredBy(ctx context.Context, adminID string) ([]ListQuestionsAnsweredByRow, error) { - rows, err := q.db.QueryContext(ctx, listQuestionsAnsweredBy, adminID) +func (q *Queries) ListQuestionsAnsweredBy(ctx context.Context, arg ListQuestionsAnsweredByParams) ([]ListQuestionsAnsweredByRow, error) { + rows, err := q.db.QueryContext(ctx, listQuestionsAnsweredBy, arg.AdminID, arg.RowLimit) if err != nil { return nil, err } @@ -248,8 +256,14 @@ JOIN users u ON u.id = q.author_id LEFT JOIN answers a ON a.question_id = q.id WHERE q.author_id = $1 AND q.hidden = 0 ORDER BY q.created_at DESC +LIMIT $2 ` +type ListQuestionsByAuthorParams struct { + AuthorID string + RowLimit int32 +} + type ListQuestionsByAuthorRow struct { ID string AuthorID string @@ -265,8 +279,8 @@ type ListQuestionsByAuthorRow struct { UserVote int64 } -func (q *Queries) ListQuestionsByAuthor(ctx context.Context, authorID string) ([]ListQuestionsByAuthorRow, error) { - rows, err := q.db.QueryContext(ctx, listQuestionsByAuthor, authorID) +func (q *Queries) ListQuestionsByAuthor(ctx context.Context, arg ListQuestionsByAuthorParams) ([]ListQuestionsByAuthorRow, error) { + rows, err := q.db.QueryContext(ctx, listQuestionsByAuthor, arg.AuthorID, arg.RowLimit) if err != nil { return nil, err } diff --git a/internal/store/sqlc/users.sql.go b/internal/store/sqlc/users.sql.go index 8faed99..9c764be 100644 --- a/internal/store/sqlc/users.sql.go +++ b/internal/store/sqlc/users.sql.go @@ -130,6 +130,7 @@ const listUsers = `-- name: ListUsers :many SELECT id, username, name, role, avatar_url, state, created_at FROM users ORDER BY created_at ASC +LIMIT $1 ` type ListUsersRow struct { @@ -142,8 +143,8 @@ type ListUsersRow struct { CreatedAt string } -func (q *Queries) ListUsers(ctx context.Context) ([]ListUsersRow, error) { - rows, err := q.db.QueryContext(ctx, listUsers) +func (q *Queries) ListUsers(ctx context.Context, rowLimit int32) ([]ListUsersRow, error) { + rows, err := q.db.QueryContext(ctx, listUsers, rowLimit) if err != nil { return nil, err } diff --git a/internal/store/store.go b/internal/store/store.go index 8a93a1c..bd481bf 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -2,6 +2,13 @@ package store import "context" +// List row caps keep hunt/profile/admin pages bounded. +const ( + HuntListLimit = 100 + ProfileListLimit = 50 + AdminUsersLimit = 200 +) + // Store is the application persistence API used by the web layer. type Store interface { CreateUser(ctx context.Context, u *User) error diff --git a/internal/store/user.go b/internal/store/user.go index 7f4da01..ed28d57 100644 --- a/internal/store/user.go +++ b/internal/store/user.go @@ -172,7 +172,7 @@ func CountAdmins(ctx context.Context, db *sql.DB) (int, error) { } func ListUsers(ctx context.Context, db *sql.DB) ([]User, error) { - rows, err := sqlc.New(db).ListUsers(ctx) + rows, err := sqlc.New(db).ListUsers(ctx, AdminUsersLimit) if err != nil { return nil, err } diff --git a/internal/web/admin.go b/internal/web/admin.go index a840cad..0ee32b6 100644 --- a/internal/web/admin.go +++ b/internal/web/admin.go @@ -48,12 +48,7 @@ func (s *Server) handleAdminSetRole(w http.ResponseWriter, r *http.Request) { } id := chi.URLParam(r, "id") role := store.Role(r.PostFormValue("role")) - _, err := s.store.UserByID(r.Context(), id) - if err != nil { - http.Error(w, "could not update role", http.StatusBadRequest) - return - } - err = s.store.SetUserRole(r.Context(), id, role) + err := s.store.SetUserRole(r.Context(), id, role) if errors.Is(err, store.ErrLastAdmin) { users, listErr := s.store.ListUsers(r.Context()) if listErr != nil { diff --git a/internal/web/profile.go b/internal/web/profile.go index 9a775f5..01ef47b 100644 --- a/internal/web/profile.go +++ b/internal/web/profile.go @@ -208,7 +208,7 @@ func fitAvatar(img image.Image, maxDim int) image.Image { nh = 1 } dst := image.NewRGBA(image.Rect(0, 0, nw, nh)) - draw.CatmullRom.Scale(dst, dst.Bounds(), img, b, draw.Over, nil) + draw.ApproxBiLinear.Scale(dst, dst.Bounds(), img, b, draw.Over, nil) return dst } @@ -229,9 +229,6 @@ func (s *Server) renderProfile(w http.ResponseWriter, r *http.Request, u *store. http.Error(w, "could not load questions", http.StatusInternalServerError) return } - if fresh, e := s.store.UserByID(r.Context(), u.ID); e == nil { - u = fresh - } p := s.basePage(r, "Profile") p.User = u s.exec(w, "profile", profilePage{ diff --git a/todo.md b/todo.md index dbe675b..b78651e 100644 --- a/todo.md +++ b/todo.md @@ -2,31 +2,30 @@ From the project review. Priority order within each section. -## Fix soon +## Done recently -- [x] **Persist sessions** — Sessions live in the app DB (`sessions` table) via `postgresstore`. Opaque cookie unchanged; unused `SESSION_SECRET` removed from config / `.env.example`. -- [x] **Drop Dockerfile** — Deploying on DigitalOcean App Platform (buildpack from `go.mod`); no container image needed. -- [x] **Rune-safe truncation** — `title[:120]`, `body[:8000]`, `city[:80]`, answer body, etc. can split multi-byte UTF-8. Truncate by runes (or safely). -- [x] **Admin bootstrap** — `ADMIN_USERNAME` seeds the first admin on register only when no admin exists. Promote/demote via `/admin/users` (admins only); roles stay in `users.role`. +- [x] **Persist sessions** — Custom sqlc-backed `SessionStore` (scs API kept; no `postgresstore`). +- [x] **Drop Dockerfile** — DigitalOcean App Platform buildpack from `go.mod`. +- [x] **Rune-safe truncation** — Form fields truncate by runes. +- [x] **Admin bootstrap** — `ADMIN_USERNAME` seeds first admin only when none exist; `/admin/users` for promote/demote. +- [x] **Graceful shutdown** — Signal-aware `http.Server.Shutdown` with timeouts. +- [x] **Handler tests** — Vote HTMX, answer/hide, CSRF, session rotation via in-memory `Store` (no Postgres for web suite). +- [x] **App Platform listen port** — Prefers `PORT`, then `LISTEN`, then `:8080`. +- [x] **Prod DB = PlanetScale Postgres** — Required `DATABASE_URL`; DSN cleanup for PlanetScale/libpq-only params. ## Docs & ops - [ ] **README** — How to run locally, env vars (from `.env.example`), admin bootstrap, PlanetScale `DATABASE_URL`, App Platform notes (`PORT`, `SECURE_COOKIE=1`). -- [ ] **Migrations story** — Schema is applied on boot from `schema.sql` (+ sessions DDL). OK for v1; plan real migrations before schema drifts. -- [x] **App Platform listen port** — Prefers `PORT`, then `LISTEN`, then `:8080`. -- [x] **Prod DB = PlanetScale Postgres** — App opens Postgres via required `DATABASE_URL`; DSN cleanup strips PlanetScale/libpq-only params (`sslrootcert=system`, `sslnegotiation`). Use dashboard URI on **5432** for boot schema create; **6432** (PgBouncer) later if you need pooling. +- [ ] **Migrations story** — Schema is applied on boot from `schema.sql`. OK for v1; plan real migrations before schema drifts. ## Smaller / later - [ ] Rate-limit login/register (bcrypt helps; still open to brute-force). -- [ ] Graceful shutdown instead of bare `ListenAndServe`. -- [ ] More tests: vote HTMX paths, admin answer/hide, archive redirects; optional Postgres integration test. +- [ ] Cursor pagination UI when hunt/profile lists hit their row limits. +- [ ] Optional Postgres integration tests (`TEST_DATABASE_URL`) for sqlc SessionStore / advisory locks. ## Suggested order of attack -1. ~~Persist sessions~~ done. -2. ~~Drop Dockerfile~~ done (App Platform). -3. ~~Wire `PORT`~~ done. -4. ~~Admin roles page~~ done. -5. Short README (run, env, admin, App Platform + PlanetScale). -6. Rune-safe truncation + a couple of handler tests (vote, admin hide). +1. Short README (run, env, admin, App Platform + PlanetScale). +2. Migrations plan before the next schema change. +3. Rate-limit auth endpoints. From 59513ab75e798faccf0fa6536ee83e034a8b1a25 Mon Sep 17 00:00:00 2001 From: codegirl-007 Date: Sat, 22 Aug 2026 11:47:42 -0700 Subject: [PATCH 14/17] Harden auth: setup secret, throttling, session destroy, secure cookies. Replace username-based admin bootstrap with a one-time setup secret, rate-limit login/register, equalize login bcrypt timing, cap passwords at 72 bytes, destroy sessions on logout, and require Secure cookies when PORT is set. --- .env.example | 11 +++-- cmd/server/main.go | 20 +++++++-- internal/web/auth.go | 74 +++++++++++++++++++++++++++------ internal/web/auth_test.go | 57 +++++++++++++++++++++++++ internal/web/server.go | 45 +++++++++++++------- internal/web/server_test.go | 33 ++++++++++----- internal/web/throttle.go | 83 +++++++++++++++++++++++++++++++++++++ templates/register.html | 7 +++- todo.md | 7 ++-- 9 files changed, 287 insertions(+), 50 deletions(-) create mode 100644 internal/web/auth_test.go create mode 100644 internal/web/throttle.go diff --git a/.env.example b/.env.example index ec4d4f2..475bedf 100644 --- a/.env.example +++ b/.env.example @@ -5,11 +5,14 @@ LISTEN=:8080 DATABASE_URL=postgresql://user:password@host.example.com:5432/postgres?sslmode=verify-full # Required for integration tests (do not point at the runtime DATABASE_URL). # TEST_DATABASE_URL=postgresql://user:password@host.example.com:5432/plumber_test?sslmode=verify-full -# Optional: first matching registrant becomes admin only if no admin exists yet. -# Later promote/demote via /admin/users (admins only). -ADMIN_USERNAME=yourusername -# Set to 1 when serving over HTTPS +# One-time first-admin bootstrap: registrant must also POST setup_secret matching this value, +# and only while no admin exists yet. Leave unset after bootstrap. Prefer a long random string. +# ADMIN_SETUP_SECRET= +# When PORT is set (App Platform), cookies are Secure by default; SECURE_COOKIE=0 is rejected. +# Locally, set to 1 when serving over HTTPS: SECURE_COOKIE=0 +# Set to 1 only behind a trusted reverse proxy that sets X-Forwarded-For. +# TRUST_PROXY=0 # DigitalOcean Spaces (profile avatars). Leave unset to disable uploads. # SPACES_KEY= # SPACES_SECRET= diff --git a/cmd/server/main.go b/cmd/server/main.go index b73377e..ee3a8ba 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -54,9 +54,10 @@ func openDB() (*sql.DB, *store.SessionStore) { func newHandler(db *sql.DB, sessions *store.SessionStore, uploader blob.Uploader) http.Handler { srv, err := web.New(store.NewPostgres(db), sessions.Store(), plumber.TemplateFS, plumber.StaticFS, web.Config{ - AdminUsername: os.Getenv("ADMIN_USERNAME"), - SecureCookie: os.Getenv("SECURE_COOKIE") == "1", - Blob: uploader, + AdminSetupSecret: strings.TrimSpace(os.Getenv("ADMIN_SETUP_SECRET")), + SecureCookie: secureCookieFromEnv(), + TrustProxy: os.Getenv("TRUST_PROXY") == "1", + Blob: uploader, }) if err != nil { log.Fatalf("server: %v", err) @@ -64,6 +65,19 @@ func newHandler(db *sql.DB, sessions *store.SessionStore, uploader blob.Uploader return srv.Handler() } +// secureCookieFromEnv defaults to secure when PORT is set (PaaS/production) +// and refuses an explicit disable in that environment. +func secureCookieFromEnv() bool { + v := strings.TrimSpace(os.Getenv("SECURE_COOKIE")) + if strings.TrimSpace(os.Getenv("PORT")) != "" { + if v == "0" { + log.Fatal("SECURE_COOKIE=0 is not allowed when PORT is set") + } + return true + } + return v == "1" +} + func run(httpSrv *http.Server) { errCh := make(chan error, 1) go func() { diff --git a/internal/web/auth.go b/internal/web/auth.go index 683b537..1b5c9e9 100644 --- a/internal/web/auth.go +++ b/internal/web/auth.go @@ -1,6 +1,7 @@ package web import ( + "crypto/subtle" "net/http" "net/url" "regexp" @@ -14,6 +15,23 @@ import ( var usernameRe = regexp.MustCompile(`^[a-zA-Z0-9_]{3,20}$`) +const ( + minPasswordRunes = 8 + maxPasswordBytes = 72 // bcrypt truncation limit +) + +// loginDummyHash is compared when the username is unknown so login timing +// does not reveal whether an account exists (same bcrypt cost as real hashes). +var loginDummyHash = mustBcrypt("timing-dummy-not-a-real-password") + +func mustBcrypt(s string) []byte { + h, err := bcrypt.GenerateFromPassword([]byte(s), bcrypt.DefaultCost) + if err != nil { + panic(err) + } + return h +} + func safeNext(raw string) string { if raw == "" { return "/" @@ -25,6 +43,16 @@ func safeNext(raw string) string { return u.RequestURI() } +func passwordValid(password string) (ok bool, msg string) { + if utf8.RuneCountInString(password) < minPasswordRunes { + return false, "Password must be at least 8 characters." + } + if len(password) > maxPasswordBytes { + return false, "Password must be at most 72 bytes." + } + return true, "" +} + func (s *Server) handleLoginForm(w http.ResponseWriter, r *http.Request) { if currentUser(r) != nil { http.Redirect(w, r, safeNext(r.URL.Query().Get("next")), http.StatusSeeOther) @@ -43,8 +71,16 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { username := strings.TrimSpace(r.PostFormValue("username")) password := r.PostFormValue("password") next := safeNext(r.PostFormValue("next")) + if !s.allowLoginAttempt(w, r, store.NormalizeUsername(username)) { + return + } + u, err := s.store.UserByUsername(r.Context(), username) - if err != nil || bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password)) != nil { + hash := loginDummyHash + if err == nil { + hash = []byte(u.PasswordHash) + } + if err != nil || bcrypt.CompareHashAndPassword(hash, []byte(password)) != nil { w.WriteHeader(http.StatusUnauthorized) s.exec(w, "login", authPage{ page: s.basePage(r, "Sign in"), @@ -74,16 +110,20 @@ func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) { if !s.requireCSRF(w, r) { return } + if !s.allowRegisterAttempt(w, r) { + return + } username := strings.TrimSpace(r.PostFormValue("username")) password := r.PostFormValue("password") + setupSecret := r.PostFormValue("setup_secret") p := authPage{page: s.basePage(r, "Create account"), Username: username} if !usernameRe.MatchString(username) { p.Error = "Username must be 3–20 letters, numbers, or underscores." s.exec(w, "register", p) return } - if utf8.RuneCountInString(password) < 8 { - p.Error = "Password must be at least 8 characters." + if ok, msg := passwordValid(password); !ok { + p.Error = msg s.exec(w, "register", p) return } @@ -93,15 +133,8 @@ func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) { return } role := store.RoleUser - if s.cfg.AdminUsername != "" && store.NormalizeUsername(username) == store.NormalizeUsername(s.cfg.AdminUsername) { - n, err := s.store.CountAdmins(r.Context()) - if err != nil { - http.Error(w, "could not create account", http.StatusInternalServerError) - return - } - if n == 0 { - role = store.RoleAdmin - } + if s.consumeAdminSetup(r, setupSecret) { + role = store.RoleAdmin } u := &store.User{ Username: username, @@ -121,6 +154,23 @@ func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/", http.StatusSeeOther) } +// consumeAdminSetup grants first-admin when a strong one-time setup secret matches +// and no admin exists yet. Username alone is never enough. +func (s *Server) consumeAdminSetup(r *http.Request, provided string) bool { + want := s.cfg.AdminSetupSecret + if want == "" || provided == "" { + return false + } + if subtle.ConstantTimeCompare([]byte(provided), []byte(want)) != 1 { + return false + } + n, err := s.store.CountAdmins(r.Context()) + if err != nil || n > 0 { + return false + } + return true +} + func (s *Server) handleAuthPrompt(w http.ResponseWriter, r *http.Request) { s.exec(w, "signin-prompt", s.basePage(r, "")) } diff --git a/internal/web/auth_test.go b/internal/web/auth_test.go new file mode 100644 index 0000000..83a11cd --- /dev/null +++ b/internal/web/auth_test.go @@ -0,0 +1,57 @@ +package web + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestPasswordMaxBytes(t *testing.T) { + if ok, _ := passwordValid(strings.Repeat("a", 8)); !ok { + t.Fatal("8 ascii runes should pass") + } + if ok, msg := passwordValid(strings.Repeat("a", 73)); ok || !strings.Contains(msg, "72") { + t.Fatalf("73 bytes should fail: ok=%v msg=%q", ok, msg) + } +} + +func TestLogoutDestroysSession(t *testing.T) { + srv, _ := newTestServer(t, Config{}) + h := srv.Handler() + name := uniq("out") + cookies := registerUser(t, h, name, "hunter22") + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/profile", nil) + for _, c := range cookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("profile before logout %d", rec.Code) + } + csrf := csrfFrom(rec.Body.String()) + form := strings.NewReader("_csrf=" + csrf) + req = httptest.NewRequest(http.MethodPost, "/logout", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range cookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("logout %d", rec.Code) + } + postLogout := mergeCookies(cookies, rec.Result().Cookies()) + + req = httptest.NewRequest(http.MethodGet, "/profile", nil) + for _, c := range postLogout { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("profile after logout should redirect, got %d", rec.Code) + } +} diff --git a/internal/web/server.go b/internal/web/server.go index 4be3153..eee10be 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -24,17 +24,24 @@ import ( ) type Config struct { - AdminUsername string - SecureCookie bool - Blob blob.Uploader + // AdminSetupSecret, when set, can promote the first registrant who also + // posts the matching setup_secret. It is ignored once any admin exists. + AdminSetupSecret string + SecureCookie bool + // TrustProxy enables X-Forwarded-For / RealIP only behind a known proxy. + TrustProxy bool + Blob blob.Uploader } type Server struct { - store store.Store - sessions *scs.SessionManager - tmpl *template.Template - cfg Config - static http.Handler + store store.Store + sessions *scs.SessionManager + tmpl *template.Template + cfg Config + static http.Handler + loginIP *throttle + loginUser *throttle + registerIP *throttle } type page struct { @@ -124,18 +131,23 @@ func New(st store.Store, sessionStore scs.Store, templateFS fs.FS, staticFS fs.F } return &Server{ - store: st, - sessions: sessions, - tmpl: tmpl, - cfg: cfg, - static: http.StripPrefix("/static/", http.FileServer(http.FS(sub))), + store: st, + sessions: sessions, + tmpl: tmpl, + cfg: cfg, + static: http.StripPrefix("/static/", http.FileServer(http.FS(sub))), + loginIP: newThrottle(20, 15*time.Minute), + loginUser: newThrottle(10, 15*time.Minute), + registerIP: newThrottle(10, 15*time.Minute), }, nil } func (s *Server) Handler() http.Handler { r := chi.NewRouter() r.Use(middleware.RequestID) - r.Use(middleware.RealIP) + if s.cfg.TrustProxy { + r.Use(middleware.RealIP) + } r.Use(middleware.Logger) r.Use(middleware.Recoverer) r.Use(func(next http.Handler) http.Handler { @@ -507,7 +519,10 @@ func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) { if !s.requireCSRF(w, r) { return } - s.sessions.Remove(r.Context(), "user_id") + if err := s.sessions.Destroy(r.Context()); err != nil { + http.Error(w, "could not sign out", http.StatusInternalServerError) + return + } http.Redirect(w, r, "/", http.StatusSeeOther) } diff --git a/internal/web/server_test.go b/internal/web/server_test.go index c7a0da4..69fb926 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -105,15 +105,18 @@ func loginUser(t *testing.T, h http.Handler, username, password string) []*http. return post } -func registerUser(t *testing.T, h http.Handler, username, password string) []*http.Cookie { +func registerUser(t *testing.T, h http.Handler, username, password string, setupSecret ...string) []*http.Cookie { t.Helper() rec := httptest.NewRecorder() h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/register", nil)) pre := rec.Result().Cookies() preToken := sessionValue(pre) csrf := csrfFrom(rec.Body.String()) - form := strings.NewReader("_csrf=" + csrf + "&username=" + username + "&password=" + password) - req := httptest.NewRequest(http.MethodPost, "/register", form) + form := "_csrf=" + csrf + "&username=" + username + "&password=" + password + if len(setupSecret) > 0 && setupSecret[0] != "" { + form += "&setup_secret=" + setupSecret[0] + } + req := httptest.NewRequest(http.MethodPost, "/register", strings.NewReader(form)) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") for _, c := range pre { req.AddCookie(c) @@ -179,25 +182,35 @@ func TestRegisterLoginAsk(t *testing.T) { } } -func TestAdminSeedOnlyWhenNoAdmins(t *testing.T) { +func TestAdminSetupSecretOnlyWhenNoAdmins(t *testing.T) { mem := store.NewMemory() + secret := "one-time-admin-setup-secret" adminName := uniq("seed") - srv := newTestServerStore(t, mem, Config{AdminUsername: adminName}) + srv := newTestServerStore(t, mem, Config{AdminSetupSecret: secret}) h := srv.Handler() - registerUser(t, h, adminName, "hunter22") + + plain := uniq("plain") + registerUser(t, h, plain, "hunter22") + uPlain, err := mem.UserByUsername(context.Background(), plain) + if err != nil || uPlain.Admin() { + t.Fatalf("register without setup secret must stay user: %+v %v", uPlain, err) + } + + registerUser(t, h, adminName, "hunter22", secret) u, err := mem.UserByUsername(context.Background(), adminName) if err != nil || !u.Admin() { - t.Fatalf("first matching registrant should be admin: %+v %v", u, err) + t.Fatalf("setup secret registrant should be admin: %+v %v", u, err) } + later := uniq("later") - srv2 := newTestServerStore(t, mem, Config{AdminUsername: later}) - registerUser(t, srv2.Handler(), later, "hunter22") + srv2 := newTestServerStore(t, mem, Config{AdminSetupSecret: secret}) + registerUser(t, srv2.Handler(), later, "hunter22", secret) u2, err := mem.UserByUsername(context.Background(), later) if err != nil { t.Fatal(err) } if u2.Admin() { - t.Fatal("later admin username must stay user when an admin already exists") + t.Fatal("setup secret must not grant admin once an admin already exists") } } diff --git a/internal/web/throttle.go b/internal/web/throttle.go new file mode 100644 index 0000000..73f31c0 --- /dev/null +++ b/internal/web/throttle.go @@ -0,0 +1,83 @@ +package web + +import ( + "net" + "net/http" + "strings" + "sync" + "time" +) + +// throttle is a simple sliding-window rate limiter for auth endpoints. +type throttle struct { + mu sync.Mutex + hits map[string][]time.Time + limit int + window time.Duration +} + +func newThrottle(limit int, window time.Duration) *throttle { + return &throttle{ + hits: map[string][]time.Time{}, + limit: limit, + window: window, + } +} + +func (t *throttle) allow(key string) bool { + if t == nil || key == "" { + return true + } + t.mu.Lock() + defer t.mu.Unlock() + now := time.Now() + cutoff := now.Add(-t.window) + xs := t.hits[key] + n := 0 + for _, ts := range xs { + if ts.After(cutoff) { + xs[n] = ts + n++ + } + } + xs = xs[:n] + if len(xs) >= t.limit { + t.hits[key] = xs + return false + } + t.hits[key] = append(xs, now) + return true +} + +func (s *Server) clientIP(r *http.Request) string { + if s.cfg.TrustProxy { + if xff := r.Header.Get("X-Forwarded-For"); xff != "" { + return strings.TrimSpace(strings.Split(xff, ",")[0]) + } + } + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return r.RemoteAddr + } + return host +} + +func authTooMany(w http.ResponseWriter) { + http.Error(w, "too many attempts; try again later", http.StatusTooManyRequests) +} + +func (s *Server) allowLoginAttempt(w http.ResponseWriter, r *http.Request, usernameKey string) bool { + if !s.loginIP.allow(s.clientIP(r)) || !s.loginUser.allow(usernameKey) { + authTooMany(w) + return false + } + return true +} + +func (s *Server) allowRegisterAttempt(w http.ResponseWriter, r *http.Request) bool { + if !s.registerIP.allow(s.clientIP(r)) { + authTooMany(w) + return false + } + return true +} diff --git a/templates/register.html b/templates/register.html index 1e2c273..432483d 100644 --- a/templates/register.html +++ b/templates/register.html @@ -10,8 +10,11 @@

3–20 letters, numbers, or underscores.

- -

At least 8 characters.

+ +

At least 8 characters (max 72 bytes).

+ + +

Only needed once to create the first admin. Leave blank otherwise.

Already have an account? Sign in

diff --git a/todo.md b/todo.md index b78651e..c509604 100644 --- a/todo.md +++ b/todo.md @@ -7,11 +7,12 @@ From the project review. Priority order within each section. - [x] **Persist sessions** — Custom sqlc-backed `SessionStore` (scs API kept; no `postgresstore`). - [x] **Drop Dockerfile** — DigitalOcean App Platform buildpack from `go.mod`. - [x] **Rune-safe truncation** — Form fields truncate by runes. -- [x] **Admin bootstrap** — `ADMIN_USERNAME` seeds first admin only when none exist; `/admin/users` for promote/demote. +- [x] **Admin bootstrap** — One-time `ADMIN_SETUP_SECRET` on register (not username alone); `/admin/users` for promote/demote. - [x] **Graceful shutdown** — Signal-aware `http.Server.Shutdown` with timeouts. - [x] **Handler tests** — Vote HTMX, answer/hide, CSRF, session rotation via in-memory `Store` (no Postgres for web suite). - [x] **App Platform listen port** — Prefers `PORT`, then `LISTEN`, then `:8080`. - [x] **Prod DB = PlanetScale Postgres** — Required `DATABASE_URL`; DSN cleanup for PlanetScale/libpq-only params. +- [x] **Auth hardening** — Rate limits, timing-safe login, password ≤72 bytes, logout destroys session, Secure cookies required when `PORT` is set. ## Docs & ops @@ -20,12 +21,10 @@ From the project review. Priority order within each section. ## Smaller / later -- [ ] Rate-limit login/register (bcrypt helps; still open to brute-force). - [ ] Cursor pagination UI when hunt/profile lists hit their row limits. - [ ] Optional Postgres integration tests (`TEST_DATABASE_URL`) for sqlc SessionStore / advisory locks. ## Suggested order of attack -1. Short README (run, env, admin, App Platform + PlanetScale). +1. Short README (run, env, admin setup secret, App Platform + PlanetScale). 2. Migrations plan before the next schema change. -3. Rate-limit auth endpoints. From 5bdaa8977fa62722211f12ad20c29302e9c18e75 Mon Sep 17 00:00:00 2001 From: codegirl-007 Date: Sat, 22 Aug 2026 11:54:10 -0700 Subject: [PATCH 15/17] Fix auth throttle DoS and serialize admin bootstrap. Evict/cap limiter keys, replace hard username lockouts with IP+user progressive delays cleared on success, and create bootstrap admins under the same advisory/mutex lock as role changes. --- internal/store/memory.go | 10 ++ internal/store/memory_test.go | 49 ++++++++- internal/store/postgres_store.go | 63 ++++++++++- internal/web/auth.go | 24 ++--- internal/web/server.go | 8 +- internal/web/throttle.go | 176 ++++++++++++++++++++++++++++--- internal/web/throttle_test.go | 122 +++++++++++++++++++++ 7 files changed, 413 insertions(+), 39 deletions(-) create mode 100644 internal/web/throttle_test.go diff --git a/internal/store/memory.go b/internal/store/memory.go index 39c86a7..7db3e67 100644 --- a/internal/store/memory.go +++ b/internal/store/memory.go @@ -54,7 +54,17 @@ func (m *Memory) CreateUser(_ context.Context, u *User) error { if u.CreatedAt == "" { u.CreatedAt = time.Now().UTC().Format(time.RFC3339) } + role := u.Role + if role == RoleAdmin { + for _, existing := range m.users { + if existing.Role == RoleAdmin { + role = RoleUser + break + } + } + } cp := *u + cp.Role = role cp.db = nil m.users[cp.ID] = &cp m.byName[cp.Username] = cp.ID diff --git a/internal/store/memory_test.go b/internal/store/memory_test.go index c5e3239..6c63541 100644 --- a/internal/store/memory_test.go +++ b/internal/store/memory_test.go @@ -9,14 +9,20 @@ import ( func TestMemoryConcurrentLastAdminDemotion(t *testing.T) { m := NewMemory() ctx := context.Background() - a := &User{Username: "admin_a", PasswordHash: "x", Role: RoleAdmin} - b := &User{Username: "admin_b", PasswordHash: "x", Role: RoleAdmin} + a := &User{Username: "admin_a", PasswordHash: "x", Role: RoleUser} + b := &User{Username: "admin_b", PasswordHash: "x", Role: RoleUser} if err := m.CreateUser(ctx, a); err != nil { t.Fatal(err) } if err := m.CreateUser(ctx, b); err != nil { t.Fatal(err) } + if err := m.SetUserRole(ctx, a.ID, RoleAdmin); err != nil { + t.Fatal(err) + } + if err := m.SetUserRole(ctx, b.ID, RoleAdmin); err != nil { + t.Fatal(err) + } var wg sync.WaitGroup errs := make(chan error, 2) @@ -54,3 +60,42 @@ func TestMemoryConcurrentLastAdminDemotion(t *testing.T) { t.Fatalf("admins remaining = %d, want 1", n) } } + +func TestMemoryConcurrentBootstrapAdmin(t *testing.T) { + m := NewMemory() + ctx := context.Background() + a := &User{Username: "boot_a", PasswordHash: "x", Role: RoleAdmin} + b := &User{Username: "boot_b", PasswordHash: "x", Role: RoleAdmin} + + var wg sync.WaitGroup + errs := make(chan error, 2) + wg.Add(2) + go func() { + defer wg.Done() + errs <- m.CreateUser(ctx, a) + }() + go func() { + defer wg.Done() + errs <- m.CreateUser(ctx, b) + }() + wg.Wait() + close(errs) + for err := range errs { + if err != nil { + t.Fatal(err) + } + } + n, err := m.CountAdmins(ctx) + if err != nil { + t.Fatal(err) + } + if n != 1 { + t.Fatalf("bootstrap race left %d admins, want 1", n) + } + if a.Role == RoleAdmin && b.Role == RoleAdmin { + t.Fatal("both users kept RoleAdmin") + } + if a.Role != RoleAdmin && b.Role != RoleAdmin { + t.Fatal("neither user is admin") + } +} diff --git a/internal/store/postgres_store.go b/internal/store/postgres_store.go index e054677..8dbe634 100644 --- a/internal/store/postgres_store.go +++ b/internal/store/postgres_store.go @@ -3,6 +3,12 @@ package store import ( "context" "database/sql" + "fmt" + "time" + + "github.com/google/uuid" + + "plumber/internal/store/sqlc" ) // Postgres implements Store against a sqlc-backed database. @@ -16,8 +22,63 @@ func NewPostgres(db *sql.DB) *Postgres { } func (p *Postgres) CreateUser(ctx context.Context, u *User) error { + if u == nil { + return fmt.Errorf("user: nil") + } + if u.Role != RoleUser && u.Role != RoleAdmin { + return fmt.Errorf("invalid role") + } + u.Username = NormalizeUsername(u.Username) + if u.ID == "" { + u.ID = uuid.NewString() + } + if u.Name == "" { + u.Name = u.Username + } + if u.CreatedAt == "" { + u.CreatedAt = time.Now().UTC().Format(time.RFC3339) + } + + if u.Role != RoleAdmin { + u.db = p.db + return u.Create(ctx) + } + + // Bootstrap admin: serialize count+insert so two setup-secret registers + // cannot both observe zero admins. + tx, err := p.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock($1)`, adminRoleLockKey); err != nil { + return err + } + q := sqlc.New(tx) + n, err := q.CountAdmins(ctx, string(RoleAdmin)) + if err != nil { + return err + } + role := RoleAdmin + if n > 0 { + role = RoleUser + } + if err := q.CreateUser(ctx, sqlc.CreateUserParams{ + ID: u.ID, + Username: u.Username, + Name: u.Name, + PasswordHash: u.PasswordHash, + Role: string(role), + CreatedAt: u.CreatedAt, + }); err != nil { + return err + } + if err := tx.Commit(); err != nil { + return err + } + u.Role = role u.db = p.db - return u.Create(ctx) + return nil } func (p *Postgres) UserByID(ctx context.Context, id string) (*User, error) { diff --git a/internal/web/auth.go b/internal/web/auth.go index 1b5c9e9..ac56f81 100644 --- a/internal/web/auth.go +++ b/internal/web/auth.go @@ -71,7 +71,9 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { username := strings.TrimSpace(r.PostFormValue("username")) password := r.PostFormValue("password") next := safeNext(r.PostFormValue("next")) - if !s.allowLoginAttempt(w, r, store.NormalizeUsername(username)) { + userKey := store.NormalizeUsername(username) + ip := s.clientIP(r) + if !s.allowLoginAttempt(w, r, userKey) { return } @@ -81,6 +83,7 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { hash = []byte(u.PasswordHash) } if err != nil || bcrypt.CompareHashAndPassword(hash, []byte(password)) != nil { + s.loginFail.record(loginFailKey(ip, userKey)) w.WriteHeader(http.StatusUnauthorized) s.exec(w, "login", authPage{ page: s.basePage(r, "Sign in"), @@ -90,6 +93,7 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { }) return } + s.loginFail.clear(loginFailKey(ip, userKey)) if err := s.sessions.RenewToken(r.Context()); err != nil { http.Error(w, "could not start session", http.StatusInternalServerError) return @@ -133,8 +137,8 @@ func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) { return } role := store.RoleUser - if s.consumeAdminSetup(r, setupSecret) { - role = store.RoleAdmin + if setupSecretMatches(s.cfg.AdminSetupSecret, setupSecret) { + role = store.RoleAdmin // store downgrades if an admin already exists } u := &store.User{ Username: username, @@ -154,21 +158,11 @@ func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/", http.StatusSeeOther) } -// consumeAdminSetup grants first-admin when a strong one-time setup secret matches -// and no admin exists yet. Username alone is never enough. -func (s *Server) consumeAdminSetup(r *http.Request, provided string) bool { - want := s.cfg.AdminSetupSecret +func setupSecretMatches(want, provided string) bool { if want == "" || provided == "" { return false } - if subtle.ConstantTimeCompare([]byte(provided), []byte(want)) != 1 { - return false - } - n, err := s.store.CountAdmins(r.Context()) - if err != nil || n > 0 { - return false - } - return true + return subtle.ConstantTimeCompare([]byte(provided), []byte(want)) == 1 } func (s *Server) handleAuthPrompt(w http.ResponseWriter, r *http.Request) { diff --git a/internal/web/server.go b/internal/web/server.go index eee10be..5d84339 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -40,8 +40,8 @@ type Server struct { cfg Config static http.Handler loginIP *throttle - loginUser *throttle registerIP *throttle + loginFail *failureTracker } type page struct { @@ -136,9 +136,9 @@ func New(st store.Store, sessionStore scs.Store, templateFS fs.FS, staticFS fs.F tmpl: tmpl, cfg: cfg, static: http.StripPrefix("/static/", http.FileServer(http.FS(sub))), - loginIP: newThrottle(20, 15*time.Minute), - loginUser: newThrottle(10, 15*time.Minute), - registerIP: newThrottle(10, 15*time.Minute), + loginIP: newThrottle(20, 15*time.Minute, defaultThrottleMaxKeys), + registerIP: newThrottle(10, 15*time.Minute, defaultThrottleMaxKeys), + loginFail: newFailureTracker(15*time.Minute, defaultThrottleMaxKeys), }, nil } diff --git a/internal/web/throttle.go b/internal/web/throttle.go index 73f31c0..9956015 100644 --- a/internal/web/throttle.go +++ b/internal/web/throttle.go @@ -8,19 +8,26 @@ import ( "time" ) -// throttle is a simple sliding-window rate limiter for auth endpoints. +const defaultThrottleMaxKeys = 10_000 + +// throttle is a sliding-window rate limiter with expired-key eviction and a cap. type throttle struct { - mu sync.Mutex - hits map[string][]time.Time - limit int - window time.Duration + mu sync.Mutex + hits map[string][]time.Time + limit int + window time.Duration + maxKeys int } -func newThrottle(limit int, window time.Duration) *throttle { +func newThrottle(limit int, window time.Duration, maxKeys int) *throttle { + if maxKeys <= 0 { + maxKeys = defaultThrottleMaxKeys + } return &throttle{ - hits: map[string][]time.Time{}, - limit: limit, - window: window, + hits: map[string][]time.Time{}, + limit: limit, + window: window, + maxKeys: maxKeys, } } @@ -31,8 +38,46 @@ func (t *throttle) allow(key string) bool { t.mu.Lock() defer t.mu.Unlock() now := time.Now() + t.evictExpiredLocked(now) + + xs := pruneTimes(t.hits[key], now.Add(-t.window)) + if len(xs) >= t.limit { + if len(xs) == 0 { + delete(t.hits, key) + } else { + t.hits[key] = xs + } + return false + } + if _, exists := t.hits[key]; !exists && len(t.hits) >= t.maxKeys { + t.evictExpiredLocked(now) + if len(t.hits) >= t.maxKeys { + return false + } + } + t.hits[key] = append(xs, now) + return true +} + +func (t *throttle) lenKeys() int { + t.mu.Lock() + defer t.mu.Unlock() + return len(t.hits) +} + +func (t *throttle) evictExpiredLocked(now time.Time) { cutoff := now.Add(-t.window) - xs := t.hits[key] + for k, xs := range t.hits { + xs = pruneTimes(xs, cutoff) + if len(xs) == 0 { + delete(t.hits, k) + } else { + t.hits[k] = xs + } + } +} + +func pruneTimes(xs []time.Time, cutoff time.Time) []time.Time { n := 0 for _, ts := range xs { if ts.After(cutoff) { @@ -40,13 +85,102 @@ func (t *throttle) allow(key string) bool { n++ } } - xs = xs[:n] - if len(xs) >= t.limit { - t.hits[key] = xs - return false + return xs[:n] +} + +// failureTracker records auth failures for progressive delay (not a hard lockout). +type failureTracker struct { + mu sync.Mutex + fails map[string]failState + window time.Duration + maxKeys int +} + +type failState struct { + count int + last time.Time +} + +func newFailureTracker(window time.Duration, maxKeys int) *failureTracker { + if maxKeys <= 0 { + maxKeys = defaultThrottleMaxKeys + } + return &failureTracker{ + fails: map[string]failState{}, + window: window, + maxKeys: maxKeys, + } +} + +func (f *failureTracker) delay(key string) time.Duration { + if f == nil || key == "" { + return 0 + } + f.mu.Lock() + defer f.mu.Unlock() + now := time.Now() + f.evictExpiredLocked(now) + st, ok := f.fails[key] + if !ok { + return 0 + } + return progressiveDelay(st.count) +} + +func (f *failureTracker) record(key string) { + if f == nil || key == "" { + return + } + f.mu.Lock() + defer f.mu.Unlock() + now := time.Now() + f.evictExpiredLocked(now) + st := f.fails[key] + if st.count == 0 && len(f.fails) >= f.maxKeys { + return + } + st.count++ + st.last = now + f.fails[key] = st +} + +func (f *failureTracker) clear(key string) { + if f == nil || key == "" { + return + } + f.mu.Lock() + defer f.mu.Unlock() + delete(f.fails, key) +} + +func (f *failureTracker) lenKeys() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.fails) +} + +func (f *failureTracker) evictExpiredLocked(now time.Time) { + cutoff := now.Add(-f.window) + for k, st := range f.fails { + if st.last.Before(cutoff) { + delete(f.fails, k) + } + } +} + +func progressiveDelay(failCount int) time.Duration { + switch { + case failCount <= 1: + return 0 + case failCount == 2: + return 200 * time.Millisecond + case failCount == 3: + return 500 * time.Millisecond + case failCount == 4: + return time.Second + default: + return 2 * time.Second } - t.hits[key] = append(xs, now) - return true } func (s *Server) clientIP(r *http.Request) string { @@ -66,11 +200,19 @@ func authTooMany(w http.ResponseWriter) { http.Error(w, "too many attempts; try again later", http.StatusTooManyRequests) } +func loginFailKey(ip, usernameKey string) string { + return ip + "\x00" + usernameKey +} + func (s *Server) allowLoginAttempt(w http.ResponseWriter, r *http.Request, usernameKey string) bool { - if !s.loginIP.allow(s.clientIP(r)) || !s.loginUser.allow(usernameKey) { + ip := s.clientIP(r) + if !s.loginIP.allow(ip) { authTooMany(w) return false } + if d := s.loginFail.delay(loginFailKey(ip, usernameKey)); d > 0 { + time.Sleep(d) + } return true } diff --git a/internal/web/throttle_test.go b/internal/web/throttle_test.go new file mode 100644 index 0000000..b234980 --- /dev/null +++ b/internal/web/throttle_test.go @@ -0,0 +1,122 @@ +package web + +import ( + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" +) + +func TestThrottleWindowAndEviction(t *testing.T) { + th := newThrottle(2, 50*time.Millisecond, 100) + if !th.allow("a") || !th.allow("a") { + t.Fatal("first two should pass") + } + if th.allow("a") { + t.Fatal("third within window should fail") + } + time.Sleep(60 * time.Millisecond) + if !th.allow("a") { + t.Fatal("after window should pass") + } + // Expired empty keys should be removed on next allow of another key path. + time.Sleep(60 * time.Millisecond) + _ = th.allow("b") + if th.lenKeys() > 2 { + t.Fatalf("expected eviction of stale keys, got %d", th.lenKeys()) + } +} + +func TestThrottleMaxKeys(t *testing.T) { + th := newThrottle(5, time.Minute, 2) + if !th.allow("one") || !th.allow("two") { + t.Fatal("first keys should pass") + } + if th.allow("three") { + t.Fatal("over maxKeys should reject new key") + } + if th.lenKeys() != 2 { + t.Fatalf("keys=%d want 2", th.lenKeys()) + } +} + +func TestThrottleConcurrent(t *testing.T) { + th := newThrottle(50, time.Minute, 1000) + var wg sync.WaitGroup + var okCount int + var mu sync.Mutex + for i := 0; i < 100; i++ { + wg.Add(1) + go func() { + defer wg.Done() + if th.allow("same") { + mu.Lock() + okCount++ + mu.Unlock() + } + }() + } + wg.Wait() + if okCount != 50 { + t.Fatalf("ok=%d want 50", okCount) + } +} + +func TestFailureTrackerProgressiveAndClear(t *testing.T) { + f := newFailureTracker(time.Minute, 100) + if d := f.delay("k"); d != 0 { + t.Fatalf("fresh delay=%v", d) + } + f.record("k") + f.record("k") + if d := f.delay("k"); d != 200*time.Millisecond { + t.Fatalf("delay after 2 fails=%v", d) + } + f.clear("k") + if d := f.delay("k"); d != 0 { + t.Fatalf("after clear delay=%v", d) + } +} + +func TestFailureTrackerEvictsExpired(t *testing.T) { + f := newFailureTracker(30*time.Millisecond, 100) + f.record("old") + time.Sleep(40 * time.Millisecond) + _ = f.delay("other") // triggers eviction + if f.lenKeys() != 0 { + t.Fatalf("expired key remained, keys=%d", f.lenKeys()) + } +} + +func TestClientIPTrustProxy(t *testing.T) { + srv := &Server{cfg: Config{TrustProxy: true}} + req := httptest.NewRequest(http.MethodGet, "/", nil) + req.RemoteAddr = "10.0.0.1:1234" + req.Header.Set("X-Forwarded-For", "203.0.113.9, 10.0.0.1") + if got := srv.clientIP(req); got != "203.0.113.9" { + t.Fatalf("trusted xff got %q", got) + } + + srv.cfg.TrustProxy = false + if got := srv.clientIP(req); got != "10.0.0.1" { + t.Fatalf("untrusted should use RemoteAddr host, got %q", got) + } +} + +func TestNoGlobalUsernameHardLockout(t *testing.T) { + // Victim IP should still be allowed after another IP burns attempts for the same username. + srv := &Server{ + loginIP: newThrottle(20, time.Minute, 100), + loginFail: newFailureTracker(time.Minute, 100), + } + for i := 0; i < 20; i++ { + srv.loginFail.record(loginFailKey("1.1.1.1", "alice")) + } + victim := httptest.NewRequest(http.MethodPost, "/login", nil) + victim.RemoteAddr = "2.2.2.2:9" + w := httptest.NewRecorder() + if !srv.allowLoginAttempt(w, victim, "alice") { + t.Fatal("victim IP must not be hard-locked by username-only attempts") + } +} From 29b0536215d5113674fe09ef982e0b66bed15592 Mon Sep 17 00:00:00 2001 From: codegirl-007 Date: Sat, 22 Aug 2026 12:16:59 -0700 Subject: [PATCH 16/17] Address production-readiness review: clearer errors, safer votes, and ops hardening. Distinguish auth/lookup failures, make votes idempotent on visible questions, bound shutdown, page admin users, LRU throttle, trusted-proxy CIDRs, avatar cleanup, versioned migrations, and session cleanup logging. --- .env.example | 5 +- cmd/server/main.go | 34 ++++++- db/queries/sessions.sql | 2 +- db/queries/users.sql | 12 ++- db/queries/votes.sql | 16 ++- internal/blob/spaces.go | 45 +++++++- internal/store/memory.go | 47 +++++++-- internal/store/migrate.go | 69 +++++++++++++ internal/store/postgres.go | 8 +- internal/store/postgres_store.go | 6 +- internal/store/sessions.go | 14 ++- internal/store/sqlc/sessions.sql.go | 11 +- internal/store/sqlc/users.sql.go | 30 +++++- internal/store/sqlc/votes.sql.go | 39 +++++-- internal/store/store.go | 13 ++- internal/store/user.go | 27 +++-- internal/store/vote.go | 66 ++++++++---- internal/web/admin.go | 38 +++++-- internal/web/auth.go | 28 ++++- internal/web/profile.go | 36 +++++-- internal/web/server.go | 29 +++++- internal/web/server_test.go | 2 + internal/web/throttle.go | 152 +++++++++++++++++++++------- internal/web/throttle_test.go | 17 ++-- templates/admin_users.html | 8 ++ templates/partials/_vote.html | 4 +- 26 files changed, 612 insertions(+), 146 deletions(-) diff --git a/.env.example b/.env.example index 475bedf..71f6ffc 100644 --- a/.env.example +++ b/.env.example @@ -11,8 +11,9 @@ DATABASE_URL=postgresql://user:password@host.example.com:5432/postgres?sslmode=v # When PORT is set (App Platform), cookies are Secure by default; SECURE_COOKIE=0 is rejected. # Locally, set to 1 when serving over HTTPS: SECURE_COOKIE=0 -# Set to 1 only behind a trusted reverse proxy that sets X-Forwarded-For. -# TRUST_PROXY=0 +# Comma-separated CIDRs of reverse proxies allowed to set X-Forwarded-For +# (direct peer must match). Leave unset to ignore XFF and use RemoteAddr. +# TRUSTED_PROXY_CIDRS=10.0.0.0/8,192.168.0.0/16 # DigitalOcean Spaces (profile avatars). Leave unset to disable uploads. # SPACES_KEY= # SPACES_SECRET= diff --git a/cmd/server/main.go b/cmd/server/main.go index ee3a8ba..ec20f60 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -5,6 +5,7 @@ import ( "database/sql" "errors" "log" + "net" "net/http" "os" "os/signal" @@ -56,7 +57,7 @@ func newHandler(db *sql.DB, sessions *store.SessionStore, uploader blob.Uploader srv, err := web.New(store.NewPostgres(db), sessions.Store(), plumber.TemplateFS, plumber.StaticFS, web.Config{ AdminSetupSecret: strings.TrimSpace(os.Getenv("ADMIN_SETUP_SECRET")), SecureCookie: secureCookieFromEnv(), - TrustProxy: os.Getenv("TRUST_PROXY") == "1", + TrustedProxies: parseTrustedProxies(os.Getenv("TRUSTED_PROXY_CIDRS")), Blob: uploader, }) if err != nil { @@ -65,6 +66,22 @@ func newHandler(db *sql.DB, sessions *store.SessionStore, uploader blob.Uploader return srv.Handler() } +func parseTrustedProxies(raw string) []*net.IPNet { + var out []*net.IPNet + for _, part := range strings.Split(raw, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + _, n, err := net.ParseCIDR(part) + if err != nil { + log.Fatalf("TRUSTED_PROXY_CIDRS: bad CIDR %q: %v", part, err) + } + out = append(out, n) + } + return out +} + // secureCookieFromEnv defaults to secure when PORT is set (PaaS/production) // and refuses an explicit disable in that environment. func secureCookieFromEnv() bool { @@ -96,12 +113,19 @@ func run(httpSrv *http.Server) { case sig := <-sigCh: log.Printf("shutdown signal: %v", sig) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - if err := httpSrv.Shutdown(ctx); err != nil { + err := httpSrv.Shutdown(ctx) + cancel() + if err != nil { log.Printf("shutdown: %v", err) + _ = httpSrv.Close() } - if err := <-errCh; err != nil && !errors.Is(err, http.ErrServerClosed) { - log.Fatal(err) + select { + case err := <-errCh: + if err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Printf("server exit: %v", err) + } + case <-time.After(3 * time.Second): + log.Printf("server exit: timed out waiting for ListenAndServe") } } } diff --git a/db/queries/sessions.sql b/db/queries/sessions.sql index 81482a2..5f8e71a 100644 --- a/db/queries/sessions.sql +++ b/db/queries/sessions.sql @@ -13,6 +13,6 @@ SET data = excluded.data, expiry = excluded.expiry; DELETE FROM sessions WHERE token = $1; --- name: DeleteExpiredSessions :exec +-- name: DeleteExpiredSessions :execrows DELETE FROM sessions WHERE expiry <= now(); diff --git a/db/queries/users.sql b/db/queries/users.sql index 954fced..02e4271 100644 --- a/db/queries/users.sql +++ b/db/queries/users.sql @@ -15,7 +15,17 @@ WHERE username = $1; -- name: ListUsers :many SELECT id, username, name, role, avatar_url, state, created_at FROM users -ORDER BY created_at ASC +WHERE ( + sqlc.arg(search) = '' + OR username ILIKE '%' || sqlc.arg(search) || '%' + OR name ILIKE '%' || sqlc.arg(search) || '%' +) +AND ( + sqlc.arg(cursor_created) = '' + OR created_at < sqlc.arg(cursor_created) + OR (created_at = sqlc.arg(cursor_created) AND id < sqlc.arg(cursor_id)) +) +ORDER BY created_at DESC, id DESC LIMIT sqlc.arg(row_limit); -- name: CountAdmins :one diff --git a/db/queries/votes.sql b/db/queries/votes.sql index 7268fed..a8917ba 100644 --- a/db/queries/votes.sql +++ b/db/queries/votes.sql @@ -3,12 +3,22 @@ SELECT value FROM votes WHERE user_id = $1 AND question_id = $2; +-- name: QuestionIsVisible :one +SELECT EXISTS( + SELECT 1 FROM questions WHERE id = $1 AND hidden = 0 +)::bool; + -- name: DeleteVote :exec DELETE FROM votes WHERE user_id = $1 AND question_id = $2; --- name: UpsertVote :exec +-- name: UpsertVoteOnVisible :execrows INSERT INTO votes (user_id, question_id, value) -VALUES ($1, $2, $3) +SELECT $1, $2, $3 +FROM questions q +WHERE q.id = $2 AND q.hidden = 0 ON CONFLICT (user_id, question_id) DO UPDATE -SET value = excluded.value; +SET value = excluded.value +WHERE EXISTS ( + SELECT 1 FROM questions q2 WHERE q2.id = excluded.question_id AND q2.hidden = 0 +); diff --git a/internal/blob/spaces.go b/internal/blob/spaces.go index 1a69d36..0493d01 100644 --- a/internal/blob/spaces.go +++ b/internal/blob/spaces.go @@ -17,6 +17,7 @@ import ( type Uploader interface { Enabled() bool Upload(ctx context.Context, obj FileUpload) (publicURL string, err error) + Delete(ctx context.Context, key string) error } // FileUpload is a file body to store (e.g. an avatar). @@ -51,6 +52,8 @@ func (Disabled) Upload(context.Context, FileUpload) (string, error) { return "", fmt.Errorf("avatar uploads are not configured") } +func (Disabled) Delete(context.Context, string) error { return nil } + // FromEnv builds an Uploader from SPACES_* environment variables. func FromEnv() Uploader { return NewSpaces(SpacesConfig{ @@ -99,11 +102,45 @@ func (s *spaces) Upload(ctx context.Context, obj FileUpload) (string, error) { if _, err := s.client.PutObject(ctx, input); err != nil { return "", err } - if s.cfg.CDNBase != "" { - return s.cfg.CDNBase + "/" + key, nil + return s.publicURL(key), nil +} + +func (s *spaces) Delete(ctx context.Context, key string) error { + key = strings.TrimPrefix(key, "/") + if key == "" { + return nil + } + _, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{ + Bucket: aws.String(s.cfg.Bucket), + Key: aws.String(key), + }) + return err +} + +func (s *spaces) publicURL(key string) string { + if s.cfg.CDNBase != "" { + return s.cfg.CDNBase + "/" + key } - // Virtual-hosted–style Spaces URL. host := strings.TrimPrefix(s.cfg.Endpoint, "https://") host = strings.TrimPrefix(host, "http://") - return fmt.Sprintf("https://%s.%s/%s", s.cfg.Bucket, host, key), nil + return fmt.Sprintf("https://%s.%s/%s", s.cfg.Bucket, host, key) +} + +// KeyFromPublicURL extracts the object key from a Spaces/CDN URL when possible. +func KeyFromPublicURL(publicURL, cdnBase, bucket, endpoint string) string { + publicURL = strings.TrimSpace(publicURL) + if publicURL == "" { + return "" + } + cdnBase = strings.TrimRight(strings.TrimSpace(cdnBase), "/") + if cdnBase != "" && strings.HasPrefix(publicURL, cdnBase+"/") { + return strings.TrimPrefix(publicURL, cdnBase+"/") + } + host := strings.TrimPrefix(strings.TrimSpace(endpoint), "https://") + host = strings.TrimPrefix(host, "http://") + prefix := fmt.Sprintf("https://%s.%s/", bucket, host) + if strings.HasPrefix(publicURL, prefix) { + return strings.TrimPrefix(publicURL, prefix) + } + return "" } diff --git a/internal/store/memory.go b/internal/store/memory.go index 7db3e67..93e6280 100644 --- a/internal/store/memory.go +++ b/internal/store/memory.go @@ -43,7 +43,7 @@ func (m *Memory) CreateUser(_ context.Context, u *User) error { } u.Username = NormalizeUsername(u.Username) if _, ok := m.byName[u.Username]; ok { - return fmt.Errorf("username taken") + return ErrDuplicateUsername } if u.ID == "" { u.ID = uuid.NewString() @@ -94,18 +94,44 @@ func (m *Memory) UserByUsername(_ context.Context, username string) (*User, erro return &cp, nil } -func (m *Memory) ListUsers(_ context.Context) ([]User, error) { +func (m *Memory) ListUsers(_ context.Context, q ListUsersQuery) ([]User, string, string, error) { m.mu.Lock() defer m.mu.Unlock() + limit := q.Limit + if limit <= 0 { + limit = AdminUsersLimit + } + search := strings.ToLower(strings.TrimSpace(q.Search)) out := make([]User, 0, len(m.users)) for _, u := range m.users { + if search != "" && + !strings.Contains(strings.ToLower(u.Username), search) && + !strings.Contains(strings.ToLower(u.Name), search) { + continue + } + if q.CursorCreated != "" { + if u.CreatedAt > q.CursorCreated { + continue + } + if u.CreatedAt == q.CursorCreated && u.ID >= q.CursorID { + continue + } + } out = append(out, *u) } - sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt < out[j].CreatedAt }) - if len(out) > AdminUsersLimit { - out = out[:AdminUsersLimit] + sort.Slice(out, func(i, j int) bool { + if out[i].CreatedAt != out[j].CreatedAt { + return out[i].CreatedAt > out[j].CreatedAt + } + return out[i].ID > out[j].ID + }) + var nextCreated, nextID string + if len(out) > limit { + last := out[limit-1] + nextCreated, nextID = last.CreatedAt, last.ID + out = out[:limit] } - return out, nil + return out, nextCreated, nextID, nil } func (m *Memory) CountAdmins(_ context.Context) (int, error) { @@ -331,16 +357,17 @@ func (m *Memory) UpsertAnswer(_ context.Context, a *Answer) error { func (m *Memory) Vote(_ context.Context, userID, questionID string, value int) error { m.mu.Lock() defer m.mu.Unlock() - if value != 1 && value != -1 { + if value != 1 && value != -1 && value != 0 { return fmt.Errorf("invalid vote") } - if _, ok := m.questions[questionID]; !ok { - return sql.ErrNoRows + q, ok := m.questions[questionID] + if !ok || q.Hidden { + return ErrHiddenOrMissing } if m.votes[questionID] == nil { m.votes[questionID] = map[string]int{} } - if cur, ok := m.votes[questionID][userID]; ok && cur == value { + if value == 0 { delete(m.votes[questionID], userID) return nil } diff --git a/internal/store/migrate.go b/internal/store/migrate.go index bec080c..49c0f61 100644 --- a/internal/store/migrate.go +++ b/internal/store/migrate.go @@ -3,6 +3,7 @@ package store import ( "database/sql" "fmt" + "log" ) // migrateUserProfileColumns adds avatar_url and state when missing (existing DBs). @@ -16,3 +17,71 @@ func migrateUserProfileColumns(db *sql.DB) error { } return nil } + +const migrateLockKey int64 = 0x706c756d5f6d6967 // "plum_mig" + +// applyMigrations runs versioned migrations under an advisory lock. +// Fresh databases apply schemaSQL as version 001; later versions are incremental. +func applyMigrations(db *sql.DB, schemaSQL string) error { + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + if _, err := tx.Exec(`SELECT pg_advisory_xact_lock($1)`, migrateLockKey); err != nil { + return fmt.Errorf("migrate lock: %w", err) + } + if _, err := tx.Exec(` +CREATE TABLE IF NOT EXISTS schema_migrations ( + version TEXT PRIMARY KEY, + applied_at TIMESTAMPTZ NOT NULL DEFAULT now() +)`); err != nil { + return fmt.Errorf("schema_migrations: %w", err) + } + if err := tx.Commit(); err != nil { + return err + } + + applied, err := appliedVersions(db) + if err != nil { + return err + } + + migrations := []struct { + version string + run func(*sql.DB) error + }{ + {"001_schema", func(db *sql.DB) error { return applySchema(db, schemaSQL) }}, + {"002_user_profile_columns", migrateUserProfileColumns}, + } + for _, m := range migrations { + if applied[m.version] { + continue + } + log.Printf("migrate: applying %s", m.version) + if err := m.run(db); err != nil { + return fmt.Errorf("migrate %s: %w", m.version, err) + } + if _, err := db.Exec(`INSERT INTO schema_migrations (version) VALUES ($1)`, m.version); err != nil { + return fmt.Errorf("record %s: %w", m.version, err) + } + } + return nil +} + +func appliedVersions(db *sql.DB) (map[string]bool, error) { + rows, err := db.Query(`SELECT version FROM schema_migrations`) + if err != nil { + return nil, err + } + defer rows.Close() + out := map[string]bool{} + for rows.Next() { + var v string + if err := rows.Scan(&v); err != nil { + return nil, err + } + out[v] = true + } + return out, rows.Err() +} diff --git a/internal/store/postgres.go b/internal/store/postgres.go index 3f1af8f..fefde24 100644 --- a/internal/store/postgres.go +++ b/internal/store/postgres.go @@ -63,13 +63,9 @@ func OpenPostgres(databaseURL, schema string) (*sql.DB, *SessionStore, error) { _ = db.Close() return nil, nil, fmt.Errorf("postgres ping: %w", err) } - if err := applySchema(db, schema); err != nil { + if err := applyMigrations(db, schema); err != nil { _ = db.Close() - return nil, nil, fmt.Errorf("apply schema: %w", err) - } - if err := migrateUserProfileColumns(db); err != nil { - _ = db.Close() - return nil, nil, fmt.Errorf("migrate profile columns: %w", err) + return nil, nil, fmt.Errorf("migrate: %w", err) } sessions := NewSessionStore(db, 5*time.Minute) return db, sessions, nil diff --git a/internal/store/postgres_store.go b/internal/store/postgres_store.go index 8dbe634..f0f92a4 100644 --- a/internal/store/postgres_store.go +++ b/internal/store/postgres_store.go @@ -71,7 +71,7 @@ func (p *Postgres) CreateUser(ctx context.Context, u *User) error { Role: string(role), CreatedAt: u.CreatedAt, }); err != nil { - return err + return mapUniqueViolation(err) } if err := tx.Commit(); err != nil { return err @@ -89,8 +89,8 @@ func (p *Postgres) UserByUsername(ctx context.Context, username string) (*User, return UserByUsername(ctx, p.db, username) } -func (p *Postgres) ListUsers(ctx context.Context) ([]User, error) { - return ListUsers(ctx, p.db) +func (p *Postgres) ListUsers(ctx context.Context, q ListUsersQuery) ([]User, string, string, error) { + return ListUsers(ctx, p.db, q) } func (p *Postgres) CountAdmins(ctx context.Context) (int, error) { diff --git a/internal/store/sessions.go b/internal/store/sessions.go index b7fb062..a5d4a38 100644 --- a/internal/store/sessions.go +++ b/internal/store/sessions.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "errors" + "log" "sync" "time" @@ -103,10 +104,21 @@ func (s *SessionStore) cleanupLoop(interval time.Duration) { defer close(s.stopped) ticker := time.NewTicker(interval) defer ticker.Stop() + var lastErrLog time.Time for { select { case <-ticker.C: - _ = s.q.DeleteExpiredSessions(context.Background()) + n, err := s.q.DeleteExpiredSessions(context.Background()) + if err != nil { + if time.Since(lastErrLog) > time.Minute { + log.Printf("session cleanup: %v", err) + lastErrLog = time.Now() + } + continue + } + if n > 0 { + log.Printf("session cleanup: deleted %d expired row(s)", n) + } case <-s.stop: return } diff --git a/internal/store/sqlc/sessions.sql.go b/internal/store/sqlc/sessions.sql.go index 9562dea..7c9f9ec 100644 --- a/internal/store/sqlc/sessions.sql.go +++ b/internal/store/sqlc/sessions.sql.go @@ -10,14 +10,17 @@ import ( "time" ) -const deleteExpiredSessions = `-- name: DeleteExpiredSessions :exec +const deleteExpiredSessions = `-- name: DeleteExpiredSessions :execrows DELETE FROM sessions WHERE expiry <= now() ` -func (q *Queries) DeleteExpiredSessions(ctx context.Context) error { - _, err := q.db.ExecContext(ctx, deleteExpiredSessions) - return err +func (q *Queries) DeleteExpiredSessions(ctx context.Context) (int64, error) { + result, err := q.db.ExecContext(ctx, deleteExpiredSessions) + if err != nil { + return 0, err + } + return result.RowsAffected() } const deleteSession = `-- name: DeleteSession :exec diff --git a/internal/store/sqlc/users.sql.go b/internal/store/sqlc/users.sql.go index 9c764be..ffa9085 100644 --- a/internal/store/sqlc/users.sql.go +++ b/internal/store/sqlc/users.sql.go @@ -129,10 +129,27 @@ func (q *Queries) GetUserRole(ctx context.Context, id string) (string, error) { const listUsers = `-- name: ListUsers :many SELECT id, username, name, role, avatar_url, state, created_at FROM users -ORDER BY created_at ASC -LIMIT $1 +WHERE ( + $1 = '' + OR username ILIKE '%' || $1 || '%' + OR name ILIKE '%' || $1 || '%' +) +AND ( + $2 = '' + OR created_at < $2 + OR (created_at = $2 AND id < $3) +) +ORDER BY created_at DESC, id DESC +LIMIT $4 ` +type ListUsersParams struct { + Search interface{} + CursorCreated interface{} + CursorID string + RowLimit int32 +} + type ListUsersRow struct { ID string Username string @@ -143,8 +160,13 @@ type ListUsersRow struct { CreatedAt string } -func (q *Queries) ListUsers(ctx context.Context, rowLimit int32) ([]ListUsersRow, error) { - rows, err := q.db.QueryContext(ctx, listUsers, rowLimit) +func (q *Queries) ListUsers(ctx context.Context, arg ListUsersParams) ([]ListUsersRow, error) { + rows, err := q.db.QueryContext(ctx, listUsers, + arg.Search, + arg.CursorCreated, + arg.CursorID, + arg.RowLimit, + ) if err != nil { return nil, err } diff --git a/internal/store/sqlc/votes.sql.go b/internal/store/sqlc/votes.sql.go index da375d5..503901d 100644 --- a/internal/store/sqlc/votes.sql.go +++ b/internal/store/sqlc/votes.sql.go @@ -42,20 +42,41 @@ func (q *Queries) GetVote(ctx context.Context, arg GetVoteParams) (int32, error) return value, err } -const upsertVote = `-- name: UpsertVote :exec -INSERT INTO votes (user_id, question_id, value) -VALUES ($1, $2, $3) -ON CONFLICT (user_id, question_id) DO UPDATE -SET value = excluded.value +const questionIsVisible = `-- name: QuestionIsVisible :one +SELECT EXISTS( + SELECT 1 FROM questions WHERE id = $1 AND hidden = 0 +)::bool ` -type UpsertVoteParams struct { +func (q *Queries) QuestionIsVisible(ctx context.Context, id string) (bool, error) { + row := q.db.QueryRowContext(ctx, questionIsVisible, id) + var column_1 bool + err := row.Scan(&column_1) + return column_1, err +} + +const upsertVoteOnVisible = `-- name: UpsertVoteOnVisible :execrows +INSERT INTO votes (user_id, question_id, value) +SELECT $1, $2, $3 +FROM questions q +WHERE q.id = $2 AND q.hidden = 0 +ON CONFLICT (user_id, question_id) DO UPDATE +SET value = excluded.value +WHERE EXISTS ( + SELECT 1 FROM questions q2 WHERE q2.id = excluded.question_id AND q2.hidden = 0 +) +` + +type UpsertVoteOnVisibleParams struct { UserID string QuestionID string Value int32 } -func (q *Queries) UpsertVote(ctx context.Context, arg UpsertVoteParams) error { - _, err := q.db.ExecContext(ctx, upsertVote, arg.UserID, arg.QuestionID, arg.Value) - return err +func (q *Queries) UpsertVoteOnVisible(ctx context.Context, arg UpsertVoteOnVisibleParams) (int64, error) { + result, err := q.db.ExecContext(ctx, upsertVoteOnVisible, arg.UserID, arg.QuestionID, arg.Value) + if err != nil { + return 0, err + } + return result.RowsAffected() } diff --git a/internal/store/store.go b/internal/store/store.go index bd481bf..2faf5be 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -6,15 +6,23 @@ import "context" const ( HuntListLimit = 100 ProfileListLimit = 50 - AdminUsersLimit = 200 + AdminUsersLimit = 50 ) +// ListUsersQuery is a paginated admin user search. +type ListUsersQuery struct { + Search string + CursorCreated string + CursorID string + Limit int +} + // Store is the application persistence API used by the web layer. type Store interface { CreateUser(ctx context.Context, u *User) error UserByID(ctx context.Context, id string) (*User, error) UserByUsername(ctx context.Context, username string) (*User, error) - ListUsers(ctx context.Context) ([]User, error) + ListUsers(ctx context.Context, q ListUsersQuery) (users []User, nextCursorCreated, nextCursorID string, err error) CountAdmins(ctx context.Context) (int, error) SetUserRole(ctx context.Context, id string, role Role) error SaveUserProfile(ctx context.Context, u *User) error @@ -29,5 +37,6 @@ type Store interface { GetAnswer(ctx context.Context, questionID string) (*Answer, error) UpsertAnswer(ctx context.Context, a *Answer) error + // Vote sets the vote to 1, -1, or 0 (clear) on a visible question. Vote(ctx context.Context, userID, questionID string, value int) error } diff --git a/internal/store/user.go b/internal/store/user.go index ed28d57..299c616 100644 --- a/internal/store/user.go +++ b/internal/store/user.go @@ -82,14 +82,14 @@ func (u *User) Create(ctx context.Context) error { if u.CreatedAt == "" { u.CreatedAt = time.Now().UTC().Format(time.RFC3339) } - return sqlc.New(u.db).CreateUser(ctx, sqlc.CreateUserParams{ + return mapUniqueViolation(sqlc.New(u.db).CreateUser(ctx, sqlc.CreateUserParams{ ID: u.ID, Username: u.Username, Name: u.Name, PasswordHash: u.PasswordHash, Role: string(u.Role), CreatedAt: u.CreatedAt, - }) + })) } // adminRoleLockKey serializes SetRole so concurrent demotions cannot bypass the @@ -171,17 +171,32 @@ func CountAdmins(ctx context.Context, db *sql.DB) (int, error) { return int(n), err } -func ListUsers(ctx context.Context, db *sql.DB) ([]User, error) { - rows, err := sqlc.New(db).ListUsers(ctx, AdminUsersLimit) +func ListUsers(ctx context.Context, db *sql.DB, q ListUsersQuery) ([]User, string, string, error) { + limit := q.Limit + if limit <= 0 { + limit = AdminUsersLimit + } + rows, err := sqlc.New(db).ListUsers(ctx, sqlc.ListUsersParams{ + Search: q.Search, + CursorCreated: q.CursorCreated, + CursorID: q.CursorID, + RowLimit: int32(limit + 1), + }) if err != nil { - return nil, err + return nil, "", "", err } out := make([]User, 0, len(rows)) for _, r := range rows { u := toUser(db, r.ID, r.Username, r.Name, r.Role, r.AvatarUrl, r.State, r.CreatedAt, "") out = append(out, *u) } - return out, nil + var nextCreated, nextID string + if len(out) > limit { + last := out[limit-1] + nextCreated, nextID = last.CreatedAt, last.ID + out = out[:limit] + } + return out, nextCreated, nextID, nil } func UserByID(ctx context.Context, db *sql.DB, id string) (*User, error) { diff --git a/internal/store/vote.go b/internal/store/vote.go index c28efad..2d24a3c 100644 --- a/internal/store/vote.go +++ b/internal/store/vote.go @@ -3,38 +3,62 @@ package store import ( "context" "database/sql" + "errors" "fmt" + "github.com/jackc/pgx/v5/pgconn" + "plumber/internal/store/sqlc" ) -// Vote toggles or sets a user's vote on a question (value must be 1 or -1). -func Vote(ctx context.Context, db *sql.DB, userID, questionID string, value int) error { - if value != 1 && value != -1 { +// ErrDuplicateUsername is returned when inserting a username that already exists. +var ErrDuplicateUsername = errors.New("username taken") + +// ErrHiddenOrMissing is returned when voting on a hidden or unknown question. +var ErrHiddenOrMissing = errors.New("question not votable") + +// SetVote sets the user's vote to value (1, -1, or 0 to clear) on a visible question. +func SetVote(ctx context.Context, db *sql.DB, userID, questionID string, value int) error { + if value != 1 && value != -1 && value != 0 { return fmt.Errorf("invalid vote") } - tx, err := db.BeginTx(ctx, nil) - if err != nil { - return err - } - defer tx.Rollback() - - q := sqlc.New(tx) - current, err := q.GetVote(ctx, sqlc.GetVoteParams{UserID: userID, QuestionID: questionID}) - if err != nil && err != sql.ErrNoRows { - return err - } - if err == nil && int(current) == value { - err = q.DeleteVote(ctx, sqlc.DeleteVoteParams{UserID: userID, QuestionID: questionID}) - } else { - err = q.UpsertVote(ctx, sqlc.UpsertVoteParams{ + q := sqlc.New(db) + if value == 0 { + visible, err := q.QuestionIsVisible(ctx, questionID) + if err != nil { + return err + } + if !visible { + return ErrHiddenOrMissing + } + return q.DeleteVote(ctx, sqlc.DeleteVoteParams{ UserID: userID, QuestionID: questionID, - Value: int32(value), }) } + n, err := q.UpsertVoteOnVisible(ctx, sqlc.UpsertVoteOnVisibleParams{ + UserID: userID, + QuestionID: questionID, + Value: int32(value), + }) if err != nil { - return err + return mapUniqueViolation(err) } - return tx.Commit() + if n == 0 { + return ErrHiddenOrMissing + } + return nil +} + +// Vote is kept as an alias for SetVote for callers that still use the old name. +func Vote(ctx context.Context, db *sql.DB, userID, questionID string, value int) error { + return SetVote(ctx, db, userID, questionID, value) +} + +func mapUniqueViolation(err error) error { + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) && pgErr.Code == "23505" { + return ErrDuplicateUsername + } + return err } diff --git a/internal/web/admin.go b/internal/web/admin.go index 0ee32b6..fd90212 100644 --- a/internal/web/admin.go +++ b/internal/web/admin.go @@ -3,6 +3,8 @@ package web import ( "errors" "net/http" + "net/url" + "strings" "github.com/go-chi/chi/v5" @@ -11,8 +13,11 @@ import ( type adminUsersPage struct { page - Users []store.User - Error string + Users []store.User + Error string + Search string + NextCursor string + HasMore bool } func (s *Server) requireAdmin(w http.ResponseWriter, r *http.Request) *store.User { @@ -28,14 +33,35 @@ func (s *Server) handleAdminUsers(w http.ResponseWriter, r *http.Request) { if s.requireAdmin(w, r) == nil { return } - users, err := s.store.ListUsers(r.Context()) + search := strings.TrimSpace(r.URL.Query().Get("q")) + cursorCreated := r.URL.Query().Get("cursor_created") + cursorID := r.URL.Query().Get("cursor_id") + users, nextCreated, nextID, err := s.store.ListUsers(r.Context(), store.ListUsersQuery{ + Search: search, + CursorCreated: cursorCreated, + CursorID: cursorID, + Limit: store.AdminUsersLimit, + }) if err != nil { http.Error(w, "could not load users", http.StatusInternalServerError) return } + next := "" + if nextCreated != "" { + v := url.Values{} + if search != "" { + v.Set("q", search) + } + v.Set("cursor_created", nextCreated) + v.Set("cursor_id", nextID) + next = "/admin/users?" + v.Encode() + } s.exec(w, "admin-users", adminUsersPage{ - page: s.basePage(r, "Users"), - Users: users, + page: s.basePage(r, "Users"), + Users: users, + Search: search, + NextCursor: next, + HasMore: next != "", }) } @@ -50,7 +76,7 @@ func (s *Server) handleAdminSetRole(w http.ResponseWriter, r *http.Request) { role := store.Role(r.PostFormValue("role")) err := s.store.SetUserRole(r.Context(), id, role) if errors.Is(err, store.ErrLastAdmin) { - users, listErr := s.store.ListUsers(r.Context()) + users, _, _, listErr := s.store.ListUsers(r.Context(), store.ListUsersQuery{Limit: store.AdminUsersLimit}) if listErr != nil { http.Error(w, "could not demote last admin", http.StatusBadRequest) return diff --git a/internal/web/auth.go b/internal/web/auth.go index ac56f81..ed1d2c1 100644 --- a/internal/web/auth.go +++ b/internal/web/auth.go @@ -2,6 +2,9 @@ package web import ( "crypto/subtle" + "database/sql" + "errors" + "log" "net/http" "net/url" "regexp" @@ -79,8 +82,16 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { u, err := s.store.UserByUsername(r.Context(), username) hash := loginDummyHash - if err == nil { + switch { + case err == nil: hash = []byte(u.PasswordHash) + case errors.Is(err, sql.ErrNoRows): + // unknown user — still bcrypt against dummy hash + default: + log.Printf("login lookup: %v", err) + _ = bcrypt.CompareHashAndPassword(loginDummyHash, []byte(password)) + http.Error(w, "service temporarily unavailable", http.StatusServiceUnavailable) + return } if err != nil || bcrypt.CompareHashAndPassword(hash, []byte(password)) != nil { s.loginFail.record(loginFailKey(ip, userKey)) @@ -138,7 +149,7 @@ func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) { } role := store.RoleUser if setupSecretMatches(s.cfg.AdminSetupSecret, setupSecret) { - role = store.RoleAdmin // store downgrades if an admin already exists + role = store.RoleAdmin } u := &store.User{ Username: username, @@ -146,12 +157,19 @@ func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) { Role: role, } if err := s.store.CreateUser(r.Context(), u); err != nil { - p.Error = "That username is taken." - s.exec(w, "register", p) + if errors.Is(err, store.ErrDuplicateUsername) { + p.Error = "That username is taken." + s.exec(w, "register", p) + return + } + log.Printf("register create: %v", err) + http.Error(w, "could not create account", http.StatusInternalServerError) return } if err := s.sessions.RenewToken(r.Context()); err != nil { - http.Error(w, "could not start session", http.StatusInternalServerError) + log.Printf("register session: %v", err) + s.sessions.Put(r.Context(), "flash", "Account created — please sign in.") + http.Redirect(w, r, "/login", http.StatusSeeOther) return } s.sessions.Put(r.Context(), "user_id", u.ID) diff --git a/internal/web/profile.go b/internal/web/profile.go index 01ef47b..d76a2db 100644 --- a/internal/web/profile.go +++ b/internal/web/profile.go @@ -11,7 +11,6 @@ import ( "path" "strings" - "github.com/google/uuid" "golang.org/x/image/draw" _ "golang.org/x/image/webp" @@ -63,6 +62,7 @@ func (s *Server) handleProfile(w http.ResponseWriter, r *http.Request) { } avatarURL := "" + avatarKey := "" file, hdr, err := r.FormFile("avatar") if err == nil { defer file.Close() @@ -79,9 +79,10 @@ func (s *Server) handleProfile(w http.ResponseWriter, r *http.Request) { s.renderProfile(w, r, u, "Avatar must be a JPEG, PNG, or WebP image.", state) return } - key := path.Join("avatars", u.ID, uuid.NewString()+ext) + prevURL := u.AvatarURL + avatarKey = path.Join("avatars", u.ID, "avatar"+ext) url, upErr := s.cfg.Blob.Upload(r.Context(), blob.FileUpload{ - Key: key, + Key: avatarKey, Body: bytes.NewReader(body), ContentType: contentType, Size: int64(len(body)), @@ -91,15 +92,25 @@ func (s *Server) handleProfile(w http.ResponseWriter, r *http.Request) { return } avatarURL = url + u.State = state + u.AvatarURL = avatarURL + if err := s.store.SaveUserProfile(r.Context(), u); err != nil { + _ = s.cfg.Blob.Delete(r.Context(), avatarKey) + http.Error(w, "could not save profile", http.StatusInternalServerError) + return + } + if oldKey := avatarObjectKey(prevURL, u.ID); oldKey != "" && oldKey != avatarKey { + _ = s.cfg.Blob.Delete(r.Context(), oldKey) + } + s.sessions.Put(r.Context(), "flash", "Profile saved.") + http.Redirect(w, r, "/profile", http.StatusSeeOther) + return } else if err != http.ErrMissingFile { s.renderProfile(w, r, u, "Could not read avatar file.", state) return } u.State = state - if avatarURL != "" { - u.AvatarURL = avatarURL - } if err := s.store.SaveUserProfile(r.Context(), u); err != nil { http.Error(w, "could not save profile", http.StatusInternalServerError) return @@ -108,6 +119,19 @@ func (s *Server) handleProfile(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/profile", http.StatusSeeOther) } +func avatarObjectKey(publicURL, userID string) string { + marker := "/avatars/" + userID + "/" + i := strings.Index(publicURL, marker) + if i < 0 { + return "" + } + rest := publicURL[i+1:] // avatars/... + if q := strings.IndexAny(rest, "?#"); q >= 0 { + rest = rest[:q] + } + return rest +} + // prepareAvatar reads at most maxBytes, sniffs/decodes the image, resizes to a // small avatar, and re-encodes so only bounded valid image bytes are stored. func prepareAvatar(r io.Reader, maxBytes int64) (body []byte, ext, contentType string, err error) { diff --git a/internal/web/server.go b/internal/web/server.go index 5d84339..6d484bc 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -3,11 +3,14 @@ package web import ( "context" "crypto/rand" + "database/sql" "encoding/hex" + "errors" "fmt" "html/template" "io/fs" "log" + "net" "net/http" "net/url" "strings" @@ -28,9 +31,9 @@ type Config struct { // posts the matching setup_secret. It is ignored once any admin exists. AdminSetupSecret string SecureCookie bool - // TrustProxy enables X-Forwarded-For / RealIP only behind a known proxy. - TrustProxy bool - Blob blob.Uploader + // TrustedProxies are CIDRs allowed to set X-Forwarded-For (direct peer). + TrustedProxies []*net.IPNet + Blob blob.Uploader } type Server struct { @@ -145,7 +148,7 @@ func New(st store.Store, sessionStore scs.Store, templateFS fs.FS, staticFS fs.F func (s *Server) Handler() http.Handler { r := chi.NewRouter() r.Use(middleware.RequestID) - if s.cfg.TrustProxy { + if len(s.cfg.TrustedProxies) > 0 { r.Use(middleware.RealIP) } r.Use(middleware.Logger) @@ -356,7 +359,17 @@ func (s *Server) handleQuestion(w http.ResponseWriter, r *http.Request) { } var ans *store.Answer if q.Answered { - ans, _ = s.store.GetAnswer(r.Context(), q.ID) + ans, err = s.store.GetAnswer(r.Context(), q.ID) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + log.Printf("question %s marked answered but answer missing", q.ID) + http.Error(w, "answer unavailable", http.StatusInternalServerError) + return + } + log.Printf("get answer %s: %v", q.ID, err) + http.Error(w, "could not load answer", http.StatusInternalServerError) + return + } } s.exec(w, "question", questionPage{ page: s.basePage(r, q.Title), @@ -385,11 +398,17 @@ func (s *Server) handleVote(w http.ResponseWriter, r *http.Request) { value = 1 case "-1": value = -1 + case "0": + value = 0 default: http.Error(w, "invalid vote", http.StatusBadRequest) return } if err := s.store.Vote(r.Context(), u.ID, id, value); err != nil { + if errors.Is(err, store.ErrHiddenOrMissing) { + http.Error(w, "not found", http.StatusNotFound) + return + } http.Error(w, "could not vote", http.StatusInternalServerError) return } diff --git a/internal/web/server_test.go b/internal/web/server_test.go index 69fb926..34bb8a3 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -332,6 +332,8 @@ func (f *fakeBlob) Upload(_ context.Context, obj blob.FileUpload) (string, error return "https://cdn.example.com/" + obj.Key, nil } +func (f *fakeBlob) Delete(_ context.Context, _ string) error { return nil } + func TestProfilePageAndState(t *testing.T) { srv, mem := newTestServer(t, Config{}) h := srv.Handler() diff --git a/internal/web/throttle.go b/internal/web/throttle.go index 9956015..846e075 100644 --- a/internal/web/throttle.go +++ b/internal/web/throttle.go @@ -1,22 +1,33 @@ package web import ( + "container/list" + "log" "net" "net/http" "strings" "sync" + "sync/atomic" "time" ) const defaultThrottleMaxKeys = 10_000 -// throttle is a sliding-window rate limiter with expired-key eviction and a cap. +// throttle is a sliding-window rate limiter with LRU eviction at capacity. type throttle struct { mu sync.Mutex - hits map[string][]time.Time + hits map[string]*throttleEntry + lru *list.List // front = most recently used limit int window time.Duration maxKeys int + rejects atomic.Uint64 + lastLog time.Time +} + +type throttleEntry struct { + times []time.Time + el *list.Element } func newThrottle(limit int, window time.Duration, maxKeys int) *throttle { @@ -24,7 +35,8 @@ func newThrottle(limit int, window time.Duration, maxKeys int) *throttle { maxKeys = defaultThrottleMaxKeys } return &throttle{ - hits: map[string][]time.Time{}, + hits: map[string]*throttleEntry{}, + lru: list.New(), limit: limit, window: window, maxKeys: maxKeys, @@ -38,45 +50,68 @@ func (t *throttle) allow(key string) bool { t.mu.Lock() defer t.mu.Unlock() now := time.Now() - t.evictExpiredLocked(now) + cutoff := now.Add(-t.window) - xs := pruneTimes(t.hits[key], now.Add(-t.window)) - if len(xs) >= t.limit { - if len(xs) == 0 { - delete(t.hits, key) - } else { - t.hits[key] = xs + ent, ok := t.hits[key] + if ok { + ent.times = pruneTimes(ent.times, cutoff) + if len(ent.times) == 0 { + t.removeLocked(key, ent) + ok = false } - return false } - if _, exists := t.hits[key]; !exists && len(t.hits) >= t.maxKeys { - t.evictExpiredLocked(now) - if len(t.hits) >= t.maxKeys { + if ok { + if len(ent.times) >= t.limit { + t.touchLocked(key, ent) return false } + ent.times = append(ent.times, now) + t.touchLocked(key, ent) + return true } - t.hits[key] = append(xs, now) + + // New key: make room via LRU if needed. + for len(t.hits) >= t.maxKeys { + oldest := t.lru.Back() + if oldest == nil { + break + } + oldKey := oldest.Value.(string) + t.removeLocked(oldKey, t.hits[oldKey]) + n := t.rejects.Add(1) + if time.Since(t.lastLog) > time.Minute { + log.Printf("throttle: LRU evicted key at capacity=%d rejects=%d", t.maxKeys, n) + t.lastLog = now + } + } + ent = &throttleEntry{times: []time.Time{now}} + ent.el = t.lru.PushFront(key) + t.hits[key] = ent return true } +func (t *throttle) touchLocked(key string, ent *throttleEntry) { + if ent.el != nil { + t.lru.MoveToFront(ent.el) + } +} + +func (t *throttle) removeLocked(key string, ent *throttleEntry) { + if ent == nil { + return + } + if ent.el != nil { + t.lru.Remove(ent.el) + } + delete(t.hits, key) +} + func (t *throttle) lenKeys() int { t.mu.Lock() defer t.mu.Unlock() return len(t.hits) } -func (t *throttle) evictExpiredLocked(now time.Time) { - cutoff := now.Add(-t.window) - for k, xs := range t.hits { - xs = pruneTimes(xs, cutoff) - if len(xs) == 0 { - delete(t.hits, k) - } else { - t.hits[k] = xs - } - } -} - func pruneTimes(xs []time.Time, cutoff time.Time) []time.Time { n := 0 for _, ts := range xs { @@ -137,7 +172,16 @@ func (f *failureTracker) record(key string) { f.evictExpiredLocked(now) st := f.fails[key] if st.count == 0 && len(f.fails) >= f.maxKeys { - return + // Drop an arbitrary expired-or-oldest entry. + for k, v := range f.fails { + if now.Sub(v.last) > f.window/2 { + delete(f.fails, k) + break + } + } + if len(f.fails) >= f.maxKeys { + return + } } st.count++ st.last = now @@ -184,18 +228,58 @@ func progressiveDelay(failCount int) time.Duration { } func (s *Server) clientIP(r *http.Request) string { - if s.cfg.TrustProxy { - if xff := r.Header.Get("X-Forwarded-For"); xff != "" { - return strings.TrimSpace(strings.Split(xff, ",")[0]) - } - } host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { - return r.RemoteAddr + host = r.RemoteAddr + } + peer := net.ParseIP(host) + if peer == nil || !ipInNets(peer, s.cfg.TrustedProxies) { + return host + } + xff := r.Header.Get("X-Forwarded-For") + if xff == "" { + return host + } + parts := strings.Split(xff, ",") + // Walk right-to-left; skip trusted hops; first untrusted is the client. + for i := len(parts) - 1; i >= 0; i-- { + p := net.ParseIP(strings.TrimSpace(parts[i])) + if p == nil { + continue + } + if !ipInNets(p, s.cfg.TrustedProxies) { + return p.String() + } } return host } +func ipInNets(ip net.IP, nets []*net.IPNet) bool { + for _, n := range nets { + if n.Contains(ip) { + return true + } + } + return false +} + +func parseCIDRs(raw string) []*net.IPNet { + var out []*net.IPNet + for _, part := range strings.Split(raw, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + _, n, err := net.ParseCIDR(part) + if err != nil { + log.Printf("trusted proxy CIDR ignored %q: %v", part, err) + continue + } + out = append(out, n) + } + return out +} + func authTooMany(w http.ResponseWriter) { http.Error(w, "too many attempts; try again later", http.StatusTooManyRequests) } diff --git a/internal/web/throttle_test.go b/internal/web/throttle_test.go index b234980..156c0f3 100644 --- a/internal/web/throttle_test.go +++ b/internal/web/throttle_test.go @@ -1,6 +1,7 @@ package web import ( + "net" "net/http" "net/http/httptest" "sync" @@ -33,8 +34,8 @@ func TestThrottleMaxKeys(t *testing.T) { if !th.allow("one") || !th.allow("two") { t.Fatal("first keys should pass") } - if th.allow("three") { - t.Fatal("over maxKeys should reject new key") + if !th.allow("three") { + t.Fatal("over maxKeys should LRU-evict and accept new key") } if th.lenKeys() != 2 { t.Fatalf("keys=%d want 2", th.lenKeys()) @@ -90,7 +91,11 @@ func TestFailureTrackerEvictsExpired(t *testing.T) { } func TestClientIPTrustProxy(t *testing.T) { - srv := &Server{cfg: Config{TrustProxy: true}} + _, proxyNet, err := net.ParseCIDR("10.0.0.0/8") + if err != nil { + t.Fatal(err) + } + srv := &Server{cfg: Config{TrustedProxies: []*net.IPNet{proxyNet}}} req := httptest.NewRequest(http.MethodGet, "/", nil) req.RemoteAddr = "10.0.0.1:1234" req.Header.Set("X-Forwarded-For", "203.0.113.9, 10.0.0.1") @@ -98,9 +103,9 @@ func TestClientIPTrustProxy(t *testing.T) { t.Fatalf("trusted xff got %q", got) } - srv.cfg.TrustProxy = false - if got := srv.clientIP(req); got != "10.0.0.1" { - t.Fatalf("untrusted should use RemoteAddr host, got %q", got) + req.RemoteAddr = "203.0.113.50:9" + if got := srv.clientIP(req); got != "203.0.113.50" { + t.Fatalf("untrusted peer should ignore xff, got %q", got) } } diff --git a/templates/admin_users.html b/templates/admin_users.html index d15e846..8bdc197 100644 --- a/templates/admin_users.html +++ b/templates/admin_users.html @@ -4,6 +4,11 @@

Admin

Users

{{if .Error}}{{end}} +
+ + + +
@@ -40,6 +45,9 @@
+ {{if .HasMore}} +

Next page

+ {{end}} {{template "footer" .}} {{end}} diff --git a/templates/partials/_vote.html b/templates/partials/_vote.html index 7b40010..bdaf1ad 100644 --- a/templates/partials/_vote.html +++ b/templates/partials/_vote.html @@ -5,7 +5,7 @@ hx-post="/questions/{{.Question.ID}}/vote" {{if eq .View "list"}}hx-target="#leaderboard" hx-swap="outerHTML"{{else}}hx-target="#vote-{{.Question.ID}}" hx-swap="outerHTML"{{end}}> - + {{if eq .Question.UserVote 1}}{{else}}{{end}}