feat: implement Phase 1 (auth) and Phase 2 (faves CRUD) foundation
Go backend with server-rendered HTML/HTMX frontend, SQLite database,
and filesystem image storage. Self-hostable single-binary architecture.
Phase 1 — Authentication & project foundation:
- Argon2id password hashing with timing-attack prevention
- Session management with cookie-based auth and periodic cleanup
- Login, signup (open/requests/closed modes), logout, forced password reset
- CSRF double-submit cookie pattern with HTMX auto-inclusion
- Proxy-aware real IP extraction (WireGuard/Tailscale support)
- Configurable base path for subdomain and subpath deployment
- Rate limiting on auth endpoints with background cleanup
- Security headers (CSP, X-Frame-Options, Referrer-Policy)
- Structured logging with slog, graceful shutdown
- Pico CSS + HTMX vendored and embedded via go:embed
Phase 2 — Faves CRUD with tags and images:
- Full CRUD for favorites with ownership checks
- Image upload with EXIF stripping, resize to 1920px, UUID filenames
- Tag system with HTMX autocomplete (prefix search, popularity-sorted)
- Privacy controls (public/private per fave, user-configurable default)
- Tag browsing, pagination, batch tag loading (avoids N+1)
- OpenGraph meta tags on public fave detail pages
Includes code quality pass: extracted shared helpers, fixed signup
request persistence bug, plugged rate limiter memory leak, removed
dead code, and logged previously-swallowed errors.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 15:55:22 +02:00
|
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
|
|
|
|
|
|
package store
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"database/sql"
|
|
|
|
|
"errors"
|
|
|
|
|
"fmt"
|
|
|
|
|
"strings"
|
2026-03-29 16:09:30 +02:00
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
"kode.naiv.no/olemd/favoritter/internal/model"
|
feat: implement Phase 1 (auth) and Phase 2 (faves CRUD) foundation
Go backend with server-rendered HTML/HTMX frontend, SQLite database,
and filesystem image storage. Self-hostable single-binary architecture.
Phase 1 — Authentication & project foundation:
- Argon2id password hashing with timing-attack prevention
- Session management with cookie-based auth and periodic cleanup
- Login, signup (open/requests/closed modes), logout, forced password reset
- CSRF double-submit cookie pattern with HTMX auto-inclusion
- Proxy-aware real IP extraction (WireGuard/Tailscale support)
- Configurable base path for subdomain and subpath deployment
- Rate limiting on auth endpoints with background cleanup
- Security headers (CSP, X-Frame-Options, Referrer-Policy)
- Structured logging with slog, graceful shutdown
- Pico CSS + HTMX vendored and embedded via go:embed
Phase 2 — Faves CRUD with tags and images:
- Full CRUD for favorites with ownership checks
- Image upload with EXIF stripping, resize to 1920px, UUID filenames
- Tag system with HTMX autocomplete (prefix search, popularity-sorted)
- Privacy controls (public/private per fave, user-configurable default)
- Tag browsing, pagination, batch tag loading (avoids N+1)
- OpenGraph meta tags on public fave detail pages
Includes code quality pass: extracted shared helpers, fixed signup
request persistence bug, plugged rate limiter memory leak, removed
dead code, and logged previously-swallowed errors.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 15:55:22 +02:00
|
|
|
)
|
|
|
|
|
|
2026-03-29 16:09:30 +02:00
|
|
|
var (
|
|
|
|
|
ErrSignupRequestExists = errors.New("signup request already exists")
|
|
|
|
|
ErrSignupRequestNotFound = errors.New("signup request not found")
|
|
|
|
|
)
|
feat: implement Phase 1 (auth) and Phase 2 (faves CRUD) foundation
Go backend with server-rendered HTML/HTMX frontend, SQLite database,
and filesystem image storage. Self-hostable single-binary architecture.
Phase 1 — Authentication & project foundation:
- Argon2id password hashing with timing-attack prevention
- Session management with cookie-based auth and periodic cleanup
- Login, signup (open/requests/closed modes), logout, forced password reset
- CSRF double-submit cookie pattern with HTMX auto-inclusion
- Proxy-aware real IP extraction (WireGuard/Tailscale support)
- Configurable base path for subdomain and subpath deployment
- Rate limiting on auth endpoints with background cleanup
- Security headers (CSP, X-Frame-Options, Referrer-Policy)
- Structured logging with slog, graceful shutdown
- Pico CSS + HTMX vendored and embedded via go:embed
Phase 2 — Faves CRUD with tags and images:
- Full CRUD for favorites with ownership checks
- Image upload with EXIF stripping, resize to 1920px, UUID filenames
- Tag system with HTMX autocomplete (prefix search, popularity-sorted)
- Privacy controls (public/private per fave, user-configurable default)
- Tag browsing, pagination, batch tag loading (avoids N+1)
- OpenGraph meta tags on public fave detail pages
Includes code quality pass: extracted shared helpers, fixed signup
request persistence bug, plugged rate limiter memory leak, removed
dead code, and logged previously-swallowed errors.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 15:55:22 +02:00
|
|
|
|
|
|
|
|
type SignupRequestStore struct {
|
|
|
|
|
db *sql.DB
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func NewSignupRequestStore(db *sql.DB) *SignupRequestStore {
|
|
|
|
|
return &SignupRequestStore{db: db}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Create stores a pending signup request with a hashed password.
|
|
|
|
|
func (s *SignupRequestStore) Create(username, password string) error {
|
|
|
|
|
hash, err := hashPassword(password)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return fmt.Errorf("hash password: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_, err = s.db.Exec(
|
|
|
|
|
`INSERT INTO signup_requests (username, password_hash) VALUES (?, ?)`,
|
|
|
|
|
username, hash,
|
|
|
|
|
)
|
|
|
|
|
if err != nil {
|
|
|
|
|
if strings.Contains(err.Error(), "UNIQUE constraint failed") {
|
|
|
|
|
return ErrSignupRequestExists
|
|
|
|
|
}
|
|
|
|
|
return fmt.Errorf("insert signup request: %w", err)
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-29 16:09:30 +02:00
|
|
|
// GetByID returns a signup request by ID.
|
|
|
|
|
func (s *SignupRequestStore) GetByID(id int64) (*model.SignupRequest, error) {
|
|
|
|
|
var sr model.SignupRequest
|
|
|
|
|
var createdAt string
|
|
|
|
|
var reviewedAt sql.NullString
|
|
|
|
|
var reviewedBy sql.NullInt64
|
|
|
|
|
err := s.db.QueryRow(
|
|
|
|
|
`SELECT id, username, password_hash, status, created_at, reviewed_at, reviewed_by
|
|
|
|
|
FROM signup_requests WHERE id = ?`, id,
|
|
|
|
|
).Scan(&sr.ID, &sr.Username, &sr.PasswordHash, &sr.Status, &createdAt, &reviewedAt, &reviewedBy)
|
|
|
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
|
|
|
return nil, ErrSignupRequestNotFound
|
|
|
|
|
}
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
sr.CreatedAt, _ = time.Parse(time.RFC3339, createdAt)
|
|
|
|
|
if reviewedAt.Valid {
|
|
|
|
|
t, _ := time.Parse(time.RFC3339, reviewedAt.String)
|
|
|
|
|
sr.ReviewedAt = &t
|
|
|
|
|
}
|
|
|
|
|
if reviewedBy.Valid {
|
|
|
|
|
sr.ReviewedBy = reviewedBy.Int64
|
|
|
|
|
}
|
|
|
|
|
return &sr, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ListPending returns all pending signup requests, newest first.
|
|
|
|
|
func (s *SignupRequestStore) ListPending() ([]*model.SignupRequest, error) {
|
|
|
|
|
rows, err := s.db.Query(
|
|
|
|
|
`SELECT id, username, password_hash, status, created_at, reviewed_at, reviewed_by
|
|
|
|
|
FROM signup_requests WHERE status = 'pending'
|
|
|
|
|
ORDER BY created_at DESC`,
|
|
|
|
|
)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
defer rows.Close()
|
|
|
|
|
|
|
|
|
|
var requests []*model.SignupRequest
|
|
|
|
|
for rows.Next() {
|
|
|
|
|
var sr model.SignupRequest
|
|
|
|
|
var createdAt string
|
|
|
|
|
var reviewedAt sql.NullString
|
|
|
|
|
var reviewedBy sql.NullInt64
|
|
|
|
|
if err := rows.Scan(&sr.ID, &sr.Username, &sr.PasswordHash, &sr.Status, &createdAt, &reviewedAt, &reviewedBy); err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
sr.CreatedAt, _ = time.Parse(time.RFC3339, createdAt)
|
|
|
|
|
requests = append(requests, &sr)
|
|
|
|
|
}
|
|
|
|
|
return requests, rows.Err()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Approve marks a request as approved and creates the user account.
|
|
|
|
|
// The new user will have must_reset_password=1.
|
|
|
|
|
func (s *SignupRequestStore) Approve(id int64, adminID int64) error {
|
|
|
|
|
sr, err := s.GetByID(id)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
if sr.Status != "pending" {
|
|
|
|
|
return fmt.Errorf("request is not pending (status: %s)", sr.Status)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Create the user with the already-hashed password.
|
|
|
|
|
_, err = s.db.Exec(
|
|
|
|
|
`INSERT INTO users (username, password_hash, must_reset_password) VALUES (?, ?, 1)`,
|
|
|
|
|
sr.Username, sr.PasswordHash,
|
|
|
|
|
)
|
|
|
|
|
if err != nil {
|
|
|
|
|
if strings.Contains(err.Error(), "UNIQUE constraint failed") {
|
|
|
|
|
return ErrUserExists
|
|
|
|
|
}
|
|
|
|
|
return fmt.Errorf("create user from request: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Mark the request as approved.
|
|
|
|
|
_, err = s.db.Exec(
|
|
|
|
|
`UPDATE signup_requests SET status = 'approved',
|
|
|
|
|
reviewed_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now'),
|
|
|
|
|
reviewed_by = ?
|
|
|
|
|
WHERE id = ?`,
|
|
|
|
|
adminID, id,
|
|
|
|
|
)
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Reject marks a request as rejected.
|
|
|
|
|
func (s *SignupRequestStore) Reject(id int64, adminID int64) error {
|
|
|
|
|
result, err := s.db.Exec(
|
|
|
|
|
`UPDATE signup_requests SET status = 'rejected',
|
|
|
|
|
reviewed_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now'),
|
|
|
|
|
reviewed_by = ?
|
|
|
|
|
WHERE id = ? AND status = 'pending'`,
|
|
|
|
|
adminID, id,
|
|
|
|
|
)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
n, _ := result.RowsAffected()
|
|
|
|
|
if n == 0 {
|
|
|
|
|
return ErrSignupRequestNotFound
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
feat: implement Phase 1 (auth) and Phase 2 (faves CRUD) foundation
Go backend with server-rendered HTML/HTMX frontend, SQLite database,
and filesystem image storage. Self-hostable single-binary architecture.
Phase 1 — Authentication & project foundation:
- Argon2id password hashing with timing-attack prevention
- Session management with cookie-based auth and periodic cleanup
- Login, signup (open/requests/closed modes), logout, forced password reset
- CSRF double-submit cookie pattern with HTMX auto-inclusion
- Proxy-aware real IP extraction (WireGuard/Tailscale support)
- Configurable base path for subdomain and subpath deployment
- Rate limiting on auth endpoints with background cleanup
- Security headers (CSP, X-Frame-Options, Referrer-Policy)
- Structured logging with slog, graceful shutdown
- Pico CSS + HTMX vendored and embedded via go:embed
Phase 2 — Faves CRUD with tags and images:
- Full CRUD for favorites with ownership checks
- Image upload with EXIF stripping, resize to 1920px, UUID filenames
- Tag system with HTMX autocomplete (prefix search, popularity-sorted)
- Privacy controls (public/private per fave, user-configurable default)
- Tag browsing, pagination, batch tag loading (avoids N+1)
- OpenGraph meta tags on public fave detail pages
Includes code quality pass: extracted shared helpers, fixed signup
request persistence bug, plugged rate limiter memory leak, removed
dead code, and logged previously-swallowed errors.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 15:55:22 +02:00
|
|
|
// PendingCount returns the number of pending signup requests.
|
|
|
|
|
func (s *SignupRequestStore) PendingCount() (int, error) {
|
|
|
|
|
var n int
|
|
|
|
|
err := s.db.QueryRow("SELECT COUNT(*) FROM signup_requests WHERE status = 'pending'").Scan(&n)
|
|
|
|
|
return n, err
|
|
|
|
|
}
|