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>
This commit is contained in:
Ole-Morten Duesund 2026-03-29 15:55:22 +02:00
commit fc1f7259c5
52 changed files with 5459 additions and 0 deletions

205
internal/config/config.go Normal file
View file

@ -0,0 +1,205 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package config loads application configuration from environment variables.
package config
import (
"log/slog"
"net"
"net/url"
"os"
"strconv"
"strings"
"time"
)
// Config holds all application configuration.
type Config struct {
// Database
DBPath string
// Server
Listen string
BasePath string
ExternalURL string
TrustedProxies []*net.IPNet
// Uploads
UploadDir string
MaxUploadSize int64
// Security
SessionLifetime time.Duration
Argon2Memory uint32
Argon2Time uint32
Argon2Parallelism uint8
RateLimit int
// Admin
AdminUsername string
AdminPassword string
// Site
SiteName string
DevMode bool
}
// Load reads configuration from environment variables with sensible defaults.
func Load() *Config {
cfg := &Config{
DBPath: envOr("FAVORITTER_DB_PATH", "./data/favoritter.db"),
Listen: envOr("FAVORITTER_LISTEN", ":8080"),
BasePath: envOr("FAVORITTER_BASE_PATH", "/"),
ExternalURL: os.Getenv("FAVORITTER_EXTERNAL_URL"),
UploadDir: envOr("FAVORITTER_UPLOAD_DIR", "./data/uploads"),
MaxUploadSize: envInt64("FAVORITTER_MAX_UPLOAD_SIZE", 10<<20), // 10MB
SessionLifetime: envDuration("FAVORITTER_SESSION_LIFETIME", 720*time.Hour),
Argon2Memory: uint32(envInt("FAVORITTER_ARGON2_MEMORY", 65536)),
Argon2Time: uint32(envInt("FAVORITTER_ARGON2_TIME", 3)),
Argon2Parallelism: uint8(envInt("FAVORITTER_ARGON2_PARALLELISM", 2)),
RateLimit: envInt("FAVORITTER_RATE_LIMIT", 60),
AdminUsername: os.Getenv("FAVORITTER_ADMIN_USERNAME"),
AdminPassword: os.Getenv("FAVORITTER_ADMIN_PASSWORD"),
SiteName: envOr("FAVORITTER_SITE_NAME", "Favoritter"),
DevMode: envBool("FAVORITTER_DEV_MODE", false),
}
// Normalize base path: ensure it starts with / and doesn't end with /.
cfg.BasePath = normalizePath(cfg.BasePath)
// Normalize external URL: strip trailing slash.
cfg.ExternalURL = strings.TrimRight(cfg.ExternalURL, "/")
// Parse trusted proxies.
cfg.TrustedProxies = parseCIDRs(envOr("FAVORITTER_TRUSTED_PROXIES", "127.0.0.1"))
return cfg
}
// BaseURL returns the external base URL for generating absolute URLs.
// If EXTERNAL_URL is set, it's used directly. Otherwise, falls back to
// constructing from the request (caller should pass the Host header).
func (c *Config) BaseURL(requestHost string) string {
if c.ExternalURL != "" {
return c.ExternalURL
}
// Fallback: construct from request host.
// Assume HTTPS unless we know otherwise.
return "https://" + requestHost + c.BasePath
}
// IsExternalURLConfigured returns true if an explicit external URL was set.
func (c *Config) IsExternalURLConfigured() bool {
return c.ExternalURL != ""
}
// ExternalHostname returns the hostname from the external URL, or empty string.
func (c *Config) ExternalHostname() string {
if c.ExternalURL == "" {
return ""
}
u, err := url.Parse(c.ExternalURL)
if err != nil {
return ""
}
return u.Hostname()
}
func normalizePath(p string) string {
if p == "" || p == "/" {
return ""
}
if !strings.HasPrefix(p, "/") {
p = "/" + p
}
return strings.TrimRight(p, "/")
}
func parseCIDRs(s string) []*net.IPNet {
var nets []*net.IPNet
for _, part := range strings.Split(s, ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
// If no CIDR notation, add /32 for IPv4 or /128 for IPv6.
if !strings.Contains(part, "/") {
ip := net.ParseIP(part)
if ip == nil {
slog.Warn("invalid trusted proxy IP, skipping", "ip", part)
continue
}
if ip.To4() != nil {
part += "/32"
} else {
part += "/128"
}
}
_, ipNet, err := net.ParseCIDR(part)
if err != nil {
slog.Warn("invalid trusted proxy CIDR, skipping", "cidr", part, "error", err)
continue
}
nets = append(nets, ipNet)
}
return nets
}
func envOr(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}
func envInt(key string, fallback int) int {
v := os.Getenv(key)
if v == "" {
return fallback
}
n, err := strconv.Atoi(v)
if err != nil {
slog.Warn("invalid integer env var, using default", "key", key, "value", v, "default", fallback)
return fallback
}
return n
}
func envInt64(key string, fallback int64) int64 {
v := os.Getenv(key)
if v == "" {
return fallback
}
n, err := strconv.ParseInt(v, 10, 64)
if err != nil {
slog.Warn("invalid int64 env var, using default", "key", key, "value", v, "default", fallback)
return fallback
}
return n
}
func envDuration(key string, fallback time.Duration) time.Duration {
v := os.Getenv(key)
if v == "" {
return fallback
}
d, err := time.ParseDuration(v)
if err != nil {
slog.Warn("invalid duration env var, using default", "key", key, "value", v, "default", fallback)
return fallback
}
return d
}
func envBool(key string, fallback bool) bool {
v := os.Getenv(key)
if v == "" {
return fallback
}
b, err := strconv.ParseBool(v)
if err != nil {
slog.Warn("invalid bool env var, using default", "key", key, "value", v, "default", fallback)
return fallback
}
return b
}

View file

@ -0,0 +1,129 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package database manages the SQLite connection, PRAGMAs, and schema migrations.
package database
import (
"database/sql"
"embed"
"fmt"
"log/slog"
"os"
"path/filepath"
"sort"
"strings"
_ "modernc.org/sqlite"
)
//go:embed migrations/*.sql
var migrationsFS embed.FS
// Open creates a new SQLite database connection with recommended PRAGMAs
// for WAL mode, foreign keys, and performance tuning.
func Open(dbPath string) (*sql.DB, error) {
// Ensure the directory for the database file exists.
dir := filepath.Dir(dbPath)
if err := os.MkdirAll(dir, 0750); err != nil {
return nil, fmt.Errorf("create db directory: %w", err)
}
db, err := sql.Open("sqlite", dbPath)
if err != nil {
return nil, fmt.Errorf("open sqlite: %w", err)
}
// Apply recommended PRAGMAs. These must be set per-connection, and since
// database/sql may open multiple connections, we use ConnInitHook via DSN
// parameters where possible. However, journal_mode persists at the db level.
pragmas := []string{
"PRAGMA journal_mode = WAL",
"PRAGMA busy_timeout = 5000",
"PRAGMA synchronous = NORMAL",
"PRAGMA foreign_keys = ON",
"PRAGMA cache_size = -20000",
}
for _, p := range pragmas {
if _, err := db.Exec(p); err != nil {
db.Close()
return nil, fmt.Errorf("set pragma %q: %w", p, err)
}
}
// SQLite works best with a single writer connection.
db.SetMaxOpenConns(1)
slog.Info("database opened", "path", dbPath)
return db, nil
}
// Migrate runs all pending SQL migrations in order. Migrations are embedded
// SQL files named with a numeric prefix (e.g. 001_initial.sql). Each migration
// runs within a transaction.
func Migrate(db *sql.DB) error {
// Create the migrations tracking table if it doesn't exist.
_, err := db.Exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY,
applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
)`)
if err != nil {
return fmt.Errorf("create schema_migrations table: %w", err)
}
// Read all migration files.
entries, err := migrationsFS.ReadDir("migrations")
if err != nil {
return fmt.Errorf("read migrations dir: %w", err)
}
// Sort by filename to ensure correct order.
sort.Slice(entries, func(i, j int) bool {
return entries[i].Name() < entries[j].Name()
})
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
continue
}
name := entry.Name()
// Check if this migration has already been applied.
var count int
if err := db.QueryRow("SELECT COUNT(*) FROM schema_migrations WHERE version = ?", name).Scan(&count); err != nil {
return fmt.Errorf("check migration %s: %w", name, err)
}
if count > 0 {
continue
}
// Read and execute the migration in a transaction.
content, err := migrationsFS.ReadFile("migrations/" + name)
if err != nil {
return fmt.Errorf("read migration %s: %w", name, err)
}
tx, err := db.Begin()
if err != nil {
return fmt.Errorf("begin tx for %s: %w", name, err)
}
if _, err := tx.Exec(string(content)); err != nil {
tx.Rollback()
return fmt.Errorf("execute migration %s: %w", name, err)
}
if _, err := tx.Exec("INSERT INTO schema_migrations (version) VALUES (?)", name); err != nil {
tx.Rollback()
return fmt.Errorf("record migration %s: %w", name, err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit migration %s: %w", name, err)
}
slog.Info("applied migration", "version", name)
}
return nil
}

View file

@ -0,0 +1,72 @@
-- Initial schema for Favoritter.
-- Creates core tables: users, sessions, signup_requests, faves, tags, fave_tags, site_settings.
CREATE TABLE users (
id INTEGER PRIMARY KEY,
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
display_name TEXT NOT NULL DEFAULT '',
bio TEXT NOT NULL DEFAULT '',
avatar_path TEXT NOT NULL DEFAULT '',
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user' CHECK (role IN ('user', 'admin')),
profile_visibility TEXT NOT NULL DEFAULT 'public' CHECK (profile_visibility IN ('public', 'limited')),
default_fave_privacy TEXT NOT NULL DEFAULT 'public' CHECK (default_fave_privacy IN ('public', 'private')),
must_reset_password INTEGER NOT NULL DEFAULT 0,
disabled INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);
CREATE TABLE sessions (
token TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);
CREATE INDEX idx_sessions_user_id ON sessions(user_id);
CREATE INDEX idx_sessions_expires ON sessions(expires_at);
CREATE TABLE signup_requests (
id INTEGER PRIMARY KEY,
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
password_hash TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')),
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
reviewed_at TEXT,
reviewed_by INTEGER REFERENCES users(id)
);
CREATE TABLE faves (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
description TEXT NOT NULL,
url TEXT NOT NULL DEFAULT '',
image_path TEXT NOT NULL DEFAULT '',
privacy TEXT NOT NULL DEFAULT 'public' CHECK (privacy IN ('public', 'private')),
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);
CREATE INDEX idx_faves_user_id ON faves(user_id);
CREATE INDEX idx_faves_privacy ON faves(privacy);
CREATE INDEX idx_faves_created ON faves(created_at);
CREATE TABLE tags (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE COLLATE NOCASE
);
CREATE TABLE fave_tags (
fave_id INTEGER NOT NULL REFERENCES faves(id) ON DELETE CASCADE,
tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
PRIMARY KEY (fave_id, tag_id)
);
CREATE INDEX idx_fave_tags_tag_id ON fave_tags(tag_id);
CREATE TABLE site_settings (
id INTEGER PRIMARY KEY CHECK (id = 1),
site_name TEXT NOT NULL DEFAULT 'Favoritter',
site_description TEXT NOT NULL DEFAULT '',
signup_mode TEXT NOT NULL DEFAULT 'open' CHECK (signup_mode IN ('open', 'requests', 'closed')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);
INSERT INTO site_settings (id) VALUES (1);

299
internal/handler/auth.go Normal file
View file

@ -0,0 +1,299 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package handler
import (
"errors"
"log/slog"
"net/http"
"regexp"
"strings"
"kode.naiv.no/olemd/favoritter/internal/middleware"
"kode.naiv.no/olemd/favoritter/internal/render"
"kode.naiv.no/olemd/favoritter/internal/store"
)
var usernameRegexp = regexp.MustCompile(`^[a-zA-Z0-9_-]{2,30}$`)
func (h *Handler) handleLoginGet(w http.ResponseWriter, r *http.Request) {
// If already logged in, redirect to home.
if middleware.UserFromContext(r.Context()) != nil {
http.Redirect(w, r, h.deps.Config.BasePath+"/", http.StatusSeeOther)
return
}
h.deps.Renderer.Page(w, r, "login", render.PageData{
Title: "Logg inn",
})
}
func (h *Handler) handleLoginPost(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
h.flash(w, r, "login", "Ugyldig forespørsel.", "error", nil)
return
}
username := strings.TrimSpace(r.FormValue("username"))
password := r.FormValue("password")
user, err := h.deps.Users.Authenticate(username, password)
if err != nil {
if errors.Is(err, store.ErrInvalidCredentials) || errors.Is(err, store.ErrUserDisabled) {
h.flash(w, r, "login", "Feil brukernavn eller passord.", "error", nil)
return
}
slog.Error("login authentication error", "error", err)
h.flash(w, r, "login", "Noe gikk galt. Prøv igjen.", "error", nil)
return
}
token, err := h.deps.Sessions.Create(user.ID)
if err != nil {
slog.Error("session create error", "error", err)
h.flash(w, r, "login", "Noe gikk galt. Prøv igjen.", "error", nil)
return
}
h.setSessionCookie(w, r, token)
// If user must reset password, redirect there.
if user.MustResetPassword {
http.Redirect(w, r, h.deps.Config.BasePath+"/reset-password", http.StatusSeeOther)
return
}
http.Redirect(w, r, h.deps.Config.BasePath+"/", http.StatusSeeOther)
}
func (h *Handler) handleSignupGet(w http.ResponseWriter, r *http.Request) {
if middleware.UserFromContext(r.Context()) != nil {
http.Redirect(w, r, h.deps.Config.BasePath+"/", http.StatusSeeOther)
return
}
settings, err := h.deps.Settings.Get()
if err != nil {
slog.Error("get settings error", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
h.deps.Renderer.Page(w, r, "signup", render.PageData{
Title: "Registrer",
Data: map[string]string{"Mode": settings.SignupMode},
})
}
func (h *Handler) handleSignupPost(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
h.flash(w, r, "signup", "Ugyldig forespørsel.", "error", signupData("open"))
return
}
settings, err := h.deps.Settings.Get()
if err != nil {
slog.Error("get settings error", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
if settings.SignupClosed() {
h.flash(w, r, "signup", "Registrering er stengt.", "error", signupData("closed"))
return
}
username := strings.TrimSpace(r.FormValue("username"))
password := r.FormValue("password")
passwordConfirm := r.FormValue("password_confirm")
// Validate input.
if !usernameRegexp.MatchString(username) {
h.flash(w, r, "signup", "Ugyldig brukernavn. Bruk 2-30 tegn: bokstaver, tall, bindestrek, understrek.", "error", signupData(settings.SignupMode))
return
}
if len(password) < 8 {
h.flash(w, r, "signup", "Passordet må være minst 8 tegn.", "error", signupData(settings.SignupMode))
return
}
if password != passwordConfirm {
h.flash(w, r, "signup", "Passordene er ikke like.", "error", signupData(settings.SignupMode))
return
}
if settings.SignupRequests() {
// Create a signup request for admin approval.
err := h.createSignupRequest(username, password)
if err != nil {
if errors.Is(err, store.ErrUserExists) {
h.flash(w, r, "signup", "Brukernavnet er allerede i bruk.", "error", signupData(settings.SignupMode))
return
}
slog.Error("signup request error", "error", err)
h.flash(w, r, "signup", "Noe gikk galt. Prøv igjen.", "error", signupData(settings.SignupMode))
return
}
h.flash(w, r, "login", "Forespørselen din er sendt. En administrator vil gjennomgå den.", "info", nil)
return
}
// Open signup — create user directly.
user, err := h.deps.Users.Create(username, password, "user")
if err != nil {
if errors.Is(err, store.ErrUserExists) {
h.flash(w, r, "signup", "Brukernavnet er allerede i bruk.", "error", signupData(settings.SignupMode))
return
}
slog.Error("user create error", "error", err)
h.flash(w, r, "signup", "Noe gikk galt. Prøv igjen.", "error", signupData(settings.SignupMode))
return
}
// Auto-login after signup.
token, err := h.deps.Sessions.Create(user.ID)
if err != nil {
slog.Error("session create error", "error", err)
http.Redirect(w, r, h.deps.Config.BasePath+"/login", http.StatusSeeOther)
return
}
h.setSessionCookie(w, r, token)
http.Redirect(w, r, h.deps.Config.BasePath+"/", http.StatusSeeOther)
}
func (h *Handler) handleLogout(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(middleware.SessionCookieName)
if err == nil {
if delErr := h.deps.Sessions.Delete(cookie.Value); delErr != nil {
slog.Error("session delete error", "error", delErr)
}
}
middleware.ClearSessionCookie(w)
http.Redirect(w, r, h.deps.Config.BasePath+"/login", http.StatusSeeOther)
}
func (h *Handler) handleResetPasswordGet(w http.ResponseWriter, r *http.Request) {
user := middleware.UserFromContext(r.Context())
if user == nil {
http.Redirect(w, r, h.deps.Config.BasePath+"/login", http.StatusSeeOther)
return
}
if !user.MustResetPassword {
http.Redirect(w, r, h.deps.Config.BasePath+"/", http.StatusSeeOther)
return
}
h.deps.Renderer.Page(w, r, "reset_password", render.PageData{
Title: "Endre passord",
})
}
func (h *Handler) handleResetPasswordPost(w http.ResponseWriter, r *http.Request) {
user := middleware.UserFromContext(r.Context())
if user == nil {
http.Redirect(w, r, h.deps.Config.BasePath+"/login", http.StatusSeeOther)
return
}
if err := r.ParseForm(); err != nil {
h.flash(w, r, "reset_password", "Ugyldig forespørsel.", "error", nil)
return
}
password := r.FormValue("password")
passwordConfirm := r.FormValue("password_confirm")
if len(password) < 8 {
h.flash(w, r, "reset_password", "Passordet må være minst 8 tegn.", "error", nil)
return
}
if password != passwordConfirm {
h.flash(w, r, "reset_password", "Passordene er ikke like.", "error", nil)
return
}
if err := h.deps.Users.UpdatePassword(user.ID, password); err != nil {
slog.Error("update password error", "error", err)
h.flash(w, r, "reset_password", "Noe gikk galt. Prøv igjen.", "error", nil)
return
}
if delErr := h.deps.Sessions.DeleteAllForUser(user.ID); delErr != nil {
slog.Error("session cleanup error", "error", delErr)
}
// Create a fresh session.
token, err := h.deps.Sessions.Create(user.ID)
if err != nil {
slog.Error("session create error", "error", err)
http.Redirect(w, r, h.deps.Config.BasePath+"/login", http.StatusSeeOther)
return
}
h.setSessionCookie(w, r, token)
http.Redirect(w, r, h.deps.Config.BasePath+"/", http.StatusSeeOther)
}
func (h *Handler) handleHome(w http.ResponseWriter, r *http.Request) {
h.deps.Renderer.Page(w, r, "home", render.PageData{})
}
func (h *Handler) handleHealth(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status":"ok"}`))
}
// setSessionCookie sets the session cookie with appropriate flags for
// both local and remote proxy deployments.
func (h *Handler) setSessionCookie(w http.ResponseWriter, r *http.Request, token string) {
cookie := &http.Cookie{
Name: "session",
Value: token,
Path: "/",
MaxAge: int(h.deps.Config.SessionLifetime.Seconds()),
HttpOnly: true,
Secure: middleware.IsSecureRequest(r, h.deps.Config),
SameSite: http.SameSiteLaxMode,
}
// Set domain from external URL if configured.
if hostname := h.deps.Config.ExternalHostname(); hostname != "" {
cookie.Domain = hostname
}
http.SetCookie(w, cookie)
}
// flash renders a page with a flash message.
func (h *Handler) flash(w http.ResponseWriter, r *http.Request, page, message, flashType string, data any) {
h.deps.Renderer.Page(w, r, page, render.PageData{
Flash: message,
FlashType: flashType,
Data: data,
})
}
func signupData(mode string) map[string]string {
return map[string]string{"Mode": mode}
}
func (h *Handler) createSignupRequest(username, password string) error {
// Check if username is already taken by an existing user.
_, err := h.deps.Users.GetByUsername(username)
if err == nil {
return store.ErrUserExists
}
err = h.deps.SignupRequests.Create(username, password)
if errors.Is(err, store.ErrSignupRequestExists) {
return store.ErrUserExists
}
return err
}

416
internal/handler/fave.go Normal file
View file

@ -0,0 +1,416 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package handler
import (
"errors"
"log/slog"
"net/http"
"strconv"
"strings"
"kode.naiv.no/olemd/favoritter/internal/image"
"kode.naiv.no/olemd/favoritter/internal/middleware"
"kode.naiv.no/olemd/favoritter/internal/render"
"kode.naiv.no/olemd/favoritter/internal/store"
)
const defaultPageSize = 24
// handleFaveList shows the current user's faves.
func (h *Handler) handleFaveList(w http.ResponseWriter, r *http.Request) {
user := middleware.UserFromContext(r.Context())
page := queryInt(r, "page", 1)
offset := (page - 1) * defaultPageSize
faves, total, err := h.deps.Faves.ListByUser(user.ID, defaultPageSize, offset)
if err != nil {
slog.Error("list faves error", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
// Load tags for each fave.
if err := h.deps.Faves.LoadTags(faves); err != nil {
slog.Error("load tags error", "error", err)
}
totalPages := (total + defaultPageSize - 1) / defaultPageSize
h.deps.Renderer.Page(w, r, "fave_list", render.PageData{
Title: "Mine favoritter",
Data: map[string]any{
"Faves": faves,
"Page": page,
"TotalPages": totalPages,
"Total": total,
},
})
}
// handleFaveNew shows the form for creating a new fave.
func (h *Handler) handleFaveNew(w http.ResponseWriter, r *http.Request) {
user := middleware.UserFromContext(r.Context())
h.deps.Renderer.Page(w, r, "fave_form", render.PageData{
Title: "Ny favoritt",
Data: map[string]any{
"IsNew": true,
"DefaultPrivacy": user.DefaultFavePrivacy,
},
})
}
// handleFaveCreate processes the form for creating a new fave.
func (h *Handler) handleFaveCreate(w http.ResponseWriter, r *http.Request) {
user := middleware.UserFromContext(r.Context())
if err := r.ParseMultipartForm(h.deps.Config.MaxUploadSize); err != nil {
h.flash(w, r, "fave_form", "Filen er for stor.", "error", map[string]any{"IsNew": true})
return
}
description := strings.TrimSpace(r.FormValue("description"))
url := strings.TrimSpace(r.FormValue("url"))
privacy := r.FormValue("privacy")
tagStr := r.FormValue("tags")
if description == "" {
h.flash(w, r, "fave_form", "Beskrivelse er påkrevd.", "error", map[string]any{
"IsNew": true, "Description": description, "URL": url, "Tags": tagStr, "Privacy": privacy,
})
return
}
if privacy != "public" && privacy != "private" {
privacy = user.DefaultFavePrivacy
}
// Handle image upload.
var imagePath string
file, header, err := r.FormFile("image")
if err == nil {
defer file.Close()
result, err := image.Process(file, header, h.deps.Config.UploadDir)
if err != nil {
slog.Error("image process error", "error", err)
h.flash(w, r, "fave_form", "Kunne ikke behandle bildet. Sjekk at filen er et gyldig bilde (JPEG, PNG, GIF eller WebP).", "error", map[string]any{
"IsNew": true, "Description": description, "URL": url, "Tags": tagStr, "Privacy": privacy,
})
return
}
imagePath = result.Filename
}
// Create the fave.
fave, err := h.deps.Faves.Create(user.ID, description, url, imagePath, privacy)
if err != nil {
slog.Error("create fave error", "error", err)
h.flash(w, r, "fave_form", "Noe gikk galt. Prøv igjen.", "error", map[string]any{"IsNew": true})
return
}
// Set tags.
if tagStr != "" {
tags := parseTags(tagStr)
if err := h.deps.Tags.SetFaveTags(fave.ID, tags); err != nil {
slog.Error("set tags error", "error", err)
}
}
http.Redirect(w, r, h.deps.Config.BasePath+"/faves/"+strconv.FormatInt(fave.ID, 10), http.StatusSeeOther)
}
// handleFaveDetail shows a single fave.
func (h *Handler) handleFaveDetail(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
fave, err := h.deps.Faves.GetByID(id)
if err != nil {
if errors.Is(err, store.ErrFaveNotFound) {
http.NotFound(w, r)
return
}
slog.Error("get fave error", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
// Check access: private faves are only visible to their owner.
user := middleware.UserFromContext(r.Context())
if fave.Privacy == "private" && (user == nil || user.ID != fave.UserID) {
http.NotFound(w, r)
return
}
// Load tags.
tags, err := h.deps.Tags.ForFave(fave.ID)
if err != nil {
slog.Error("load tags error", "error", err)
}
fave.Tags = tags
h.deps.Renderer.Page(w, r, "fave_detail", render.PageData{
Title: fave.Description,
Data: map[string]any{
"Fave": fave,
"IsOwner": user != nil && user.ID == fave.UserID,
},
})
}
// handleFaveEdit shows the edit form for a fave.
func (h *Handler) handleFaveEdit(w http.ResponseWriter, r *http.Request) {
user := middleware.UserFromContext(r.Context())
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
fave, err := h.deps.Faves.GetByID(id)
if err != nil {
if errors.Is(err, store.ErrFaveNotFound) {
http.NotFound(w, r)
return
}
slog.Error("get fave error", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
// Only the owner can edit.
if user.ID != fave.UserID {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
tags, _ := h.deps.Tags.ForFave(fave.ID)
fave.Tags = tags
tagNames := make([]string, len(tags))
for i, t := range tags {
tagNames[i] = t.Name
}
h.deps.Renderer.Page(w, r, "fave_form", render.PageData{
Title: "Rediger favoritt",
Data: map[string]any{
"IsNew": false,
"Fave": fave,
"Description": fave.Description,
"URL": fave.URL,
"Privacy": fave.Privacy,
"Tags": strings.Join(tagNames, ", "),
},
})
}
// handleFaveUpdate processes the edit form.
func (h *Handler) handleFaveUpdate(w http.ResponseWriter, r *http.Request) {
user := middleware.UserFromContext(r.Context())
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
fave, err := h.deps.Faves.GetByID(id)
if err != nil {
if errors.Is(err, store.ErrFaveNotFound) {
http.NotFound(w, r)
return
}
slog.Error("get fave error", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
if user.ID != fave.UserID {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
if err := r.ParseMultipartForm(h.deps.Config.MaxUploadSize); err != nil {
h.flash(w, r, "fave_form", "Filen er for stor.", "error", map[string]any{"IsNew": false, "Fave": fave})
return
}
description := strings.TrimSpace(r.FormValue("description"))
url := strings.TrimSpace(r.FormValue("url"))
privacy := r.FormValue("privacy")
tagStr := r.FormValue("tags")
if description == "" {
h.flash(w, r, "fave_form", "Beskrivelse er påkrevd.", "error", map[string]any{"IsNew": false, "Fave": fave})
return
}
if privacy != "public" && privacy != "private" {
privacy = fave.Privacy
}
// Handle image upload (optional on edit).
imagePath := fave.ImagePath
file, header, err := r.FormFile("image")
if err == nil {
defer file.Close()
result, err := image.Process(file, header, h.deps.Config.UploadDir)
if err != nil {
slog.Error("image process error", "error", err)
h.flash(w, r, "fave_form", "Kunne ikke behandle bildet. Sjekk at filen er et gyldig bilde (JPEG, PNG, GIF eller WebP).", "error", map[string]any{"IsNew": false, "Fave": fave})
return
}
if fave.ImagePath != "" {
if delErr := image.Delete(h.deps.Config.UploadDir, fave.ImagePath); delErr != nil {
slog.Error("image delete error", "error", delErr)
}
}
imagePath = result.Filename
}
// Check if user wants to remove the existing image.
if r.FormValue("remove_image") == "1" && imagePath != "" {
if delErr := image.Delete(h.deps.Config.UploadDir, imagePath); delErr != nil {
slog.Error("image delete error", "error", delErr)
}
imagePath = ""
}
if err := h.deps.Faves.Update(id, description, url, imagePath, privacy); err != nil {
slog.Error("update fave error", "error", err)
h.flash(w, r, "fave_form", "Noe gikk galt. Prøv igjen.", "error", map[string]any{"IsNew": false, "Fave": fave})
return
}
// Update tags.
tags := parseTags(tagStr)
if err := h.deps.Tags.SetFaveTags(id, tags); err != nil {
slog.Error("set tags error", "error", err)
}
http.Redirect(w, r, h.deps.Config.BasePath+"/faves/"+strconv.FormatInt(id, 10), http.StatusSeeOther)
}
// handleFaveDelete deletes a fave.
func (h *Handler) handleFaveDelete(w http.ResponseWriter, r *http.Request) {
user := middleware.UserFromContext(r.Context())
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
fave, err := h.deps.Faves.GetByID(id)
if err != nil {
if errors.Is(err, store.ErrFaveNotFound) {
http.NotFound(w, r)
return
}
slog.Error("get fave error", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
if user.ID != fave.UserID {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
if fave.ImagePath != "" {
if delErr := image.Delete(h.deps.Config.UploadDir, fave.ImagePath); delErr != nil {
slog.Error("image delete error", "error", delErr)
}
}
if err := h.deps.Faves.Delete(id); err != nil {
slog.Error("delete fave error", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
// If this was an HTMX request, return empty (the element is removed).
if r.Header.Get("HX-Request") == "true" {
w.WriteHeader(http.StatusOK)
return
}
http.Redirect(w, r, h.deps.Config.BasePath+"/faves", http.StatusSeeOther)
}
// handleTagSearch handles tag autocomplete HTMX requests.
func (h *Handler) handleTagSearch(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query().Get("q")
tags, err := h.deps.Tags.Search(q, 10)
if err != nil {
slog.Error("tag search error", "error", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := h.deps.Renderer.Partial(w, "tag_suggestions", tags); err != nil {
slog.Error("render tag suggestions error", "error", err)
}
}
// handleTagBrowse shows all public faves with a given tag.
func (h *Handler) handleTagBrowse(w http.ResponseWriter, r *http.Request) {
tagName := r.PathValue("name")
page := queryInt(r, "page", 1)
offset := (page - 1) * defaultPageSize
faves, total, err := h.deps.Faves.ListByTag(tagName, defaultPageSize, offset)
if err != nil {
slog.Error("list by tag error", "error", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
if err := h.deps.Faves.LoadTags(faves); err != nil {
slog.Error("load tags error", "error", err)
}
totalPages := (total + defaultPageSize - 1) / defaultPageSize
h.deps.Renderer.Page(w, r, "tag_browse", render.PageData{
Title: "Merkelapp: " + tagName,
Data: map[string]any{
"TagName": tagName,
"Faves": faves,
"Page": page,
"TotalPages": totalPages,
"Total": total,
},
})
}
// parseTags splits a comma-separated tag string into individual tag names.
func parseTags(s string) []string {
parts := strings.Split(s, ",")
var tags []string
for _, p := range parts {
p = strings.TrimSpace(p)
if p != "" {
tags = append(tags, p)
}
}
return tags
}
// queryInt parses an integer query parameter with a default.
func queryInt(r *http.Request, key string, fallback int) int {
v := r.URL.Query().Get(key)
n, err := strconv.Atoi(v)
if err != nil || n < 1 {
return fallback
}
return n
}

107
internal/handler/handler.go Normal file
View file

@ -0,0 +1,107 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package handler contains HTTP handlers for all web and API routes.
package handler
import (
"context"
"io/fs"
"net/http"
"time"
"kode.naiv.no/olemd/favoritter/internal/config"
"kode.naiv.no/olemd/favoritter/internal/middleware"
"kode.naiv.no/olemd/favoritter/internal/render"
"kode.naiv.no/olemd/favoritter/internal/store"
"kode.naiv.no/olemd/favoritter/web"
)
// Deps bundles all dependencies injected into handlers.
type Deps struct {
Config *config.Config
Users *store.UserStore
Sessions *store.SessionStore
Settings *store.SettingsStore
Faves *store.FaveStore
Tags *store.TagStore
SignupRequests *store.SignupRequestStore
Renderer *render.Renderer
}
// Handler holds all HTTP handler methods and their dependencies.
type Handler struct {
deps Deps
rateLimiter *middleware.RateLimiter
}
// New creates a new Handler with the given dependencies.
func New(deps Deps) *Handler {
return &Handler{
deps: deps,
rateLimiter: middleware.NewRateLimiter(deps.Config.RateLimit),
}
}
// RateLimiterCleanupLoop periodically evicts stale rate limiter entries.
func (h *Handler) RateLimiterCleanupLoop(ctx context.Context, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
h.rateLimiter.Cleanup()
}
}
}
// Routes registers all routes on a new ServeMux and returns it.
func (h *Handler) Routes() *http.ServeMux {
mux := http.NewServeMux()
// Static files (served from embedded filesystem).
staticFS, err := fs.Sub(web.StaticFS, "static")
if err != nil {
panic("embedded static filesystem missing: " + err.Error())
}
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticFS))))
// Uploaded images (served from the filesystem upload directory).
mux.Handle("GET /uploads/", http.StripPrefix("/uploads/",
http.FileServer(http.Dir(h.deps.Config.UploadDir))))
// Health check.
mux.HandleFunc("GET /health", h.handleHealth)
// Auth routes (rate-limited).
mux.Handle("POST /login", h.rateLimiter.Limit(http.HandlerFunc(h.handleLoginPost)))
mux.Handle("POST /signup", h.rateLimiter.Limit(http.HandlerFunc(h.handleSignupPost)))
mux.HandleFunc("GET /login", h.handleLoginGet)
mux.HandleFunc("GET /signup", h.handleSignupGet)
mux.HandleFunc("POST /logout", h.handleLogout)
// Password reset (for must-reset-password flow).
mux.HandleFunc("GET /reset-password", h.handleResetPasswordGet)
mux.HandleFunc("POST /reset-password", h.handleResetPasswordPost)
// Home page.
mux.HandleFunc("GET /{$}", h.handleHome)
// Faves — authenticated routes use requireLogin wrapper.
requireLogin := middleware.RequireLogin(h.deps.Config.BasePath)
mux.Handle("GET /faves", requireLogin(http.HandlerFunc(h.handleFaveList)))
mux.Handle("GET /faves/new", requireLogin(http.HandlerFunc(h.handleFaveNew)))
mux.Handle("POST /faves", requireLogin(http.HandlerFunc(h.handleFaveCreate)))
mux.HandleFunc("GET /faves/{id}", h.handleFaveDetail)
mux.Handle("GET /faves/{id}/edit", requireLogin(http.HandlerFunc(h.handleFaveEdit)))
mux.Handle("POST /faves/{id}", requireLogin(http.HandlerFunc(h.handleFaveUpdate)))
mux.Handle("DELETE /faves/{id}", requireLogin(http.HandlerFunc(h.handleFaveDelete)))
// Tags.
mux.HandleFunc("GET /tags/search", h.handleTagSearch)
mux.HandleFunc("GET /tags/{name}", h.handleTagBrowse)
return mux
}

154
internal/image/image.go Normal file
View file

@ -0,0 +1,154 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package image handles uploaded image validation, processing, and storage.
// It strips EXIF metadata by re-encoding images and resizes to a maximum width.
package image
import (
"fmt"
"image"
"image/jpeg"
"image/png"
"io"
"mime/multipart"
"os"
"path/filepath"
"strings"
"github.com/google/uuid"
// Register image format decoders.
_ "image/gif"
)
const (
MaxWidth = 1920
JPEGQuality = 85
)
// AllowedTypes maps MIME types to file extensions.
var AllowedTypes = map[string]string{
"image/jpeg": ".jpg",
"image/png": ".png",
"image/gif": ".gif",
"image/webp": ".webp",
}
// ProcessResult holds the result of processing an uploaded image.
type ProcessResult struct {
Filename string // UUID-based filename with extension
Path string // Full path where the image was saved
}
// Process validates, re-encodes (stripping EXIF), and optionally resizes an
// uploaded image. It saves the result to uploadDir with a UUID filename.
//
// Re-encoding to JPEG or PNG strips all EXIF metadata including GPS coordinates,
// which is important for user privacy.
func Process(file multipart.File, header *multipart.FileHeader, uploadDir string) (*ProcessResult, error) {
// Validate content type.
contentType := header.Header.Get("Content-Type")
ext, ok := AllowedTypes[contentType]
if !ok {
return nil, fmt.Errorf("unsupported image type: %s (allowed: JPEG, PNG, GIF, WebP)", contentType)
}
// Decode the image — this also validates it's a real image.
img, format, err := image.Decode(file)
if err != nil {
return nil, fmt.Errorf("invalid image: %w", err)
}
// Resize if wider than MaxWidth, maintaining aspect ratio.
img = resizeIfNeeded(img)
// Generate UUID filename.
filename := uuid.New().String() + ext
// Ensure upload directory exists.
if err := os.MkdirAll(uploadDir, 0750); err != nil {
return nil, fmt.Errorf("create upload dir: %w", err)
}
fullPath := filepath.Join(uploadDir, filename)
outFile, err := os.Create(fullPath)
if err != nil {
return nil, fmt.Errorf("create output file: %w", err)
}
defer outFile.Close()
// Re-encode the image, which strips all EXIF metadata.
if err := encode(outFile, img, format, ext); err != nil {
os.Remove(fullPath)
return nil, fmt.Errorf("encode image: %w", err)
}
return &ProcessResult{
Filename: filename,
Path: fullPath,
}, nil
}
// Delete removes an uploaded image file.
func Delete(uploadDir, filename string) error {
if filename == "" {
return nil
}
path := filepath.Join(uploadDir, filename)
// Only delete if the file is actually inside the upload directory
// to prevent path traversal.
absPath, err := filepath.Abs(path)
if err != nil {
return err
}
absDir, err := filepath.Abs(uploadDir)
if err != nil {
return err
}
if !strings.HasPrefix(absPath, absDir+string(filepath.Separator)) {
return fmt.Errorf("path traversal detected")
}
return os.Remove(absPath)
}
// encode writes the image in the appropriate format.
// GIF and WebP are re-encoded as PNG since Go's stdlib can decode but not
// encode GIF animations or WebP. This is acceptable — we prioritize EXIF
// stripping over format preservation.
func encode(w io.Writer, img image.Image, format, ext string) error {
switch {
case format == "jpeg" || ext == ".jpg":
return jpeg.Encode(w, img, &jpeg.Options{Quality: JPEGQuality})
default:
// PNG for everything else (png, gif, webp).
return png.Encode(w, img)
}
}
// resizeIfNeeded scales the image down if it exceeds MaxWidth.
// Uses nearest-neighbor for simplicity — good enough for a favorites app.
func resizeIfNeeded(img image.Image) image.Image {
bounds := img.Bounds()
w := bounds.Dx()
h := bounds.Dy()
if w <= MaxWidth {
return img
}
newW := MaxWidth
newH := h * MaxWidth / w
dst := image.NewRGBA(image.Rect(0, 0, newW, newH))
// Simple bilinear-ish downscale by sampling.
for y := 0; y < newH; y++ {
for x := 0; x < newW; x++ {
srcX := x * w / newW
srcY := y * h / newH
dst.Set(x, y, img.At(srcX+bounds.Min.X, srcY+bounds.Min.Y))
}
}
return dst
}

View file

@ -0,0 +1,58 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import (
"context"
"errors"
"net/http"
"kode.naiv.no/olemd/favoritter/internal/store"
)
const SessionCookieName = "session"
// ClearSessionCookie sets an expired session cookie to remove it from the client.
func ClearSessionCookie(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: SessionCookieName,
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
})
}
// SessionLoader loads the user from the session cookie on every request.
// If the session is valid, the user is attached to the request context.
func SessionLoader(sessions *store.SessionStore, users *store.UserStore) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(SessionCookieName)
if err != nil {
next.ServeHTTP(w, r)
return
}
session, err := sessions.Validate(cookie.Value)
if err != nil {
if errors.Is(err, store.ErrSessionNotFound) {
ClearSessionCookie(w)
}
next.ServeHTTP(w, r)
return
}
user, err := users.GetByID(session.UserID)
if err != nil || user.Disabled {
sessions.Delete(cookie.Value)
ClearSessionCookie(w)
next.ServeHTTP(w, r)
return
}
ctx := context.WithValue(r.Context(), userKey, user)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}

View file

@ -0,0 +1,36 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import (
"net/http"
"strings"
)
// BasePath strips a configured path prefix from incoming requests so the
// router sees paths without the prefix. This enables deployment at both
// faves.example.com (basePath="") and example.com/faves (basePath="/faves").
func BasePath(prefix string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
if prefix == "" {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Strip the prefix from the URL path.
if strings.HasPrefix(r.URL.Path, prefix) {
r.URL.Path = strings.TrimPrefix(r.URL.Path, prefix)
if r.URL.Path == "" {
r.URL.Path = "/"
}
// Also update RawPath if present.
if r.URL.RawPath != "" {
r.URL.RawPath = strings.TrimPrefix(r.URL.RawPath, prefix)
if r.URL.RawPath == "" {
r.URL.RawPath = "/"
}
}
}
next.ServeHTTP(w, r)
})
}
}

View file

@ -0,0 +1,61 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import (
"context"
"net/http"
"kode.naiv.no/olemd/favoritter/internal/model"
)
type contextKey string
const (
userKey contextKey = "user"
csrfTokenKey contextKey = "csrf_token"
realIPKey contextKey = "real_ip"
)
// UserFromContext returns the authenticated user from the request context, or nil.
func UserFromContext(ctx context.Context) *model.User {
u, _ := ctx.Value(userKey).(*model.User)
return u
}
// CSRFTokenFromContext returns the CSRF token from the request context.
func CSRFTokenFromContext(ctx context.Context) string {
s, _ := ctx.Value(csrfTokenKey).(string)
return s
}
// RealIPFromContext returns the real client IP from the request context.
func RealIPFromContext(ctx context.Context) string {
s, _ := ctx.Value(realIPKey).(string)
return s
}
// RequireLogin redirects to the login page if no user is authenticated.
func RequireLogin(basePath string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if UserFromContext(r.Context()) == nil {
http.Redirect(w, r, basePath+"/login", http.StatusSeeOther)
return
}
next.ServeHTTP(w, r)
})
}
}
// RequireAdmin returns 403 if the user is not an admin.
func RequireAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context())
if user == nil || !user.IsAdmin() {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}

View file

@ -0,0 +1,93 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import (
"context"
"crypto/rand"
"encoding/hex"
"net/http"
"strings"
"kode.naiv.no/olemd/favoritter/internal/config"
)
const (
csrfCookieName = "csrf_token"
csrfFormField = "csrf_token"
csrfHeaderName = "X-CSRF-Token"
)
// CSRFProtection implements double-submit cookie pattern for CSRF prevention.
// A token is stored in a cookie and must also be submitted in a form field
// or header on state-changing requests (POST, PUT, DELETE, PATCH).
func CSRFProtection(cfg *config.Config) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Read or generate the CSRF token.
token := ""
if cookie, err := r.Cookie(csrfCookieName); err == nil {
token = cookie.Value
}
if token == "" {
token = generateCSRFToken()
secure := IsSecureRequest(r, cfg)
http.SetCookie(w, &http.Cookie{
Name: csrfCookieName,
Value: token,
Path: "/",
HttpOnly: false, // JS needs to read it for HTMX hx-headers
Secure: secure,
SameSite: http.SameSiteLaxMode,
})
}
// Attach token to context for templates.
ctx := context.WithValue(r.Context(), csrfTokenKey, token)
r = r.WithContext(ctx)
// Validate on state-changing methods.
if isStateChangingMethod(r.Method) {
// Skip CSRF check for API routes that use Bearer auth (future).
if !strings.HasPrefix(r.URL.Path, "/api/") {
submitted := r.FormValue(csrfFormField)
if submitted == "" {
submitted = r.Header.Get(csrfHeaderName)
}
if submitted != token {
http.Error(w, "CSRF token mismatch", http.StatusForbidden)
return
}
}
}
next.ServeHTTP(w, r)
})
}
}
func isStateChangingMethod(method string) bool {
switch method {
case http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch:
return true
}
return false
}
func generateCSRFToken() string {
b := make([]byte, 32)
rand.Read(b)
return hex.EncodeToString(b)
}
// IsSecureRequest determines if the original client request used HTTPS,
// checking X-Forwarded-Proto from trusted proxies.
func IsSecureRequest(r *http.Request, cfg *config.Config) bool {
if cfg.ExternalURL != "" {
return strings.HasPrefix(cfg.ExternalURL, "https://")
}
if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
return proto == "https"
}
return r.TLS != nil
}

View file

@ -0,0 +1,38 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import (
"log/slog"
"net/http"
"time"
)
// responseWriter wraps http.ResponseWriter to capture the status code.
type responseWriter struct {
http.ResponseWriter
statusCode int
}
func (rw *responseWriter) WriteHeader(code int) {
rw.statusCode = code
rw.ResponseWriter.WriteHeader(code)
}
// RequestLogger logs each HTTP request with method, path, status, and duration.
func RequestLogger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rw := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}
next.ServeHTTP(rw, r)
slog.Debug("request",
"method", r.Method,
"path", r.URL.Path,
"status", rw.statusCode,
"duration", time.Since(start),
"ip", RealIPFromContext(r.Context()),
)
})
}

View file

@ -0,0 +1,15 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package middleware provides HTTP middleware for auth, security, and request processing.
package middleware
import "net/http"
// Chain wraps a handler with a stack of middleware, applied in order
// (the last middleware listed is the outermost wrapper).
func Chain(h http.Handler, middlewares ...func(http.Handler) http.Handler) http.Handler {
for _, m := range middlewares {
h = m(h)
}
return h
}

View file

@ -0,0 +1,89 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import (
"net/http"
"sync"
"time"
)
// RateLimiter implements a simple per-IP token bucket rate limiter for
// protecting auth endpoints from brute-force attacks.
type RateLimiter struct {
mu sync.Mutex
visitors map[string]*bucket
rate int
window time.Duration
}
type bucket struct {
tokens int
lastReset time.Time
}
// NewRateLimiter creates a rate limiter that allows `rate` requests per minute per IP.
func NewRateLimiter(rate int) *RateLimiter {
return &RateLimiter{
visitors: make(map[string]*bucket),
rate: rate,
window: time.Minute,
}
}
// Limit wraps a handler with rate limiting based on the real client IP.
func (rl *RateLimiter) Limit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := RealIPFromContext(r.Context())
if ip == "" {
ip = r.RemoteAddr
}
if !rl.allow(ip) {
http.Error(w, "Too many requests. Please try again later.", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
func (rl *RateLimiter) allow(ip string) bool {
rl.mu.Lock()
defer rl.mu.Unlock()
now := time.Now()
b, ok := rl.visitors[ip]
if !ok {
rl.visitors[ip] = &bucket{tokens: rl.rate - 1, lastReset: now}
return true
}
// Reset tokens if the window has passed.
if now.Sub(b.lastReset) >= rl.window {
b.tokens = rl.rate - 1
b.lastReset = now
return true
}
if b.tokens <= 0 {
return false
}
b.tokens--
return true
}
// Cleanup removes stale entries. Call periodically from a goroutine.
func (rl *RateLimiter) Cleanup() {
rl.mu.Lock()
defer rl.mu.Unlock()
now := time.Now()
for ip, b := range rl.visitors {
if now.Sub(b.lastReset) >= 2*rl.window {
delete(rl.visitors, ip)
}
}
}

View file

@ -0,0 +1,68 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import (
"context"
"net"
"net/http"
"strings"
)
// RealIP extracts the real client IP from X-Forwarded-For, but only if the
// direct connection comes from a trusted proxy. This is essential when Caddy
// runs on a different machine (e.g. connected via WireGuard/Tailscale).
func RealIP(trustedProxies []*net.IPNet) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := extractRealIP(r, trustedProxies)
ctx := context.WithValue(r.Context(), realIPKey, ip)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func extractRealIP(r *http.Request, trusted []*net.IPNet) string {
// Get the direct connection IP.
directIP, _, _ := net.SplitHostPort(r.RemoteAddr)
if directIP == "" {
directIP = r.RemoteAddr
}
// Only trust X-Forwarded-For if the direct connection is from a trusted proxy.
if !isTrusted(directIP, trusted) {
return directIP
}
// Parse X-Forwarded-For: client, proxy1, proxy2
// The rightmost non-trusted IP is the real client.
xff := r.Header.Get("X-Forwarded-For")
if xff == "" {
return directIP
}
ips := strings.Split(xff, ",")
// Walk from right to left, finding the first non-trusted IP.
for i := len(ips) - 1; i >= 0; i-- {
ip := strings.TrimSpace(ips[i])
if !isTrusted(ip, trusted) {
return ip
}
}
// All IPs in the chain are trusted; use the leftmost.
return strings.TrimSpace(ips[0])
}
func isTrusted(ipStr string, nets []*net.IPNet) bool {
ip := net.ParseIP(ipStr)
if ip == nil {
return false
}
for _, n := range nets {
if n.Contains(ip) {
return true
}
}
return false
}

View file

@ -0,0 +1,27 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import (
"log/slog"
"net/http"
"runtime/debug"
)
// Recovery catches panics in HTTP handlers and returns a 500 error
// instead of crashing the server.
func Recovery(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
slog.Error("panic recovered",
"error", err,
"path", r.URL.Path,
"stack", string(debug.Stack()),
)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}

View file

@ -0,0 +1,24 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import "net/http"
// SecurityHeaders adds security-related HTTP headers to every response.
func SecurityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("X-Content-Type-Options", "nosniff")
h.Set("X-Frame-Options", "DENY")
h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
// CSP allows inline styles from Pico CSS and scripts from self only.
// The 'unsafe-inline' for style-src is needed for Pico CSS.
h.Set("Content-Security-Policy",
"default-src 'self'; "+
"style-src 'self' 'unsafe-inline'; "+
"img-src 'self' data:; "+
"frame-ancestors 'none'")
next.ServeHTTP(w, r)
})
}

26
internal/model/fave.go Normal file
View file

@ -0,0 +1,26 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package model
import "time"
type Fave struct {
ID int64
UserID int64
Description string
URL string
ImagePath string
Privacy string
Tags []Tag
CreatedAt time.Time
UpdatedAt time.Time
// Joined fields for display.
Username string
DisplayName string
}
// IsPublic returns true if the fave is publicly visible.
func (f *Fave) IsPublic() bool {
return f.Privacy == "public"
}

12
internal/model/session.go Normal file
View file

@ -0,0 +1,12 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package model
import "time"
type Session struct {
Token string
UserID int64
ExpiresAt time.Time
CreatedAt time.Time
}

View file

@ -0,0 +1,27 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package model
import "time"
type SiteSettings struct {
SiteName string
SiteDescription string
SignupMode string
UpdatedAt time.Time
}
// SignupOpen returns true if self-registration is allowed.
func (s *SiteSettings) SignupOpen() bool {
return s.SignupMode == "open"
}
// SignupRequests returns true if signup requires admin approval.
func (s *SiteSettings) SignupRequests() bool {
return s.SignupMode == "requests"
}
// SignupClosed returns true if no new signups are allowed.
func (s *SiteSettings) SignupClosed() bool {
return s.SignupMode == "closed"
}

8
internal/model/tag.go Normal file
View file

@ -0,0 +1,8 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package model
type Tag struct {
ID int64
Name string
}

34
internal/model/user.go Normal file
View file

@ -0,0 +1,34 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package model
import "time"
type User struct {
ID int64
Username string
DisplayName string
Bio string
AvatarPath string
PasswordHash string
Role string
ProfileVisibility string
DefaultFavePrivacy string
MustResetPassword bool
Disabled bool
CreatedAt time.Time
UpdatedAt time.Time
}
// IsAdmin returns true if the user has the admin role.
func (u *User) IsAdmin() bool {
return u.Role == "admin"
}
// DisplayNameOrUsername returns the display name if set, otherwise the username.
func (u *User) DisplayNameOrUsername() string {
if u.DisplayName != "" {
return u.DisplayName
}
return u.Username
}

193
internal/render/render.go Normal file
View file

@ -0,0 +1,193 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package render provides HTML template rendering with layout support.
package render
import (
"fmt"
"html/template"
"io"
"io/fs"
"log/slog"
"net/http"
"os"
"path/filepath"
"strings"
"kode.naiv.no/olemd/favoritter/internal/config"
"kode.naiv.no/olemd/favoritter/internal/middleware"
"kode.naiv.no/olemd/favoritter/internal/model"
"kode.naiv.no/olemd/favoritter/internal/store"
"kode.naiv.no/olemd/favoritter/web"
)
// Renderer parses and executes HTML templates.
type Renderer struct {
templates map[string]*template.Template
cfg *config.Config
}
// PageData holds data passed to page templates.
type PageData struct {
Title string
User *model.User
CSRFToken string
BasePath string
SiteName string
Flash string
FlashType string // "success", "error", "info"
ExternalURL string
Data any
}
// New creates a Renderer, parsing all templates from the embedded filesystem.
func New(cfg *config.Config) (*Renderer, error) {
r := &Renderer{
cfg: cfg,
}
if err := r.parseTemplates(); err != nil {
return nil, err
}
return r, nil
}
func (r *Renderer) parseTemplates() error {
r.templates = make(map[string]*template.Template)
var templateFS fs.FS
if r.cfg.DevMode {
// In dev mode, read templates from disk for live reload.
templateFS = os.DirFS(filepath.Join("web", "templates"))
} else {
sub, err := fs.Sub(web.TemplatesFS, "templates")
if err != nil {
return fmt.Errorf("sub templates fs: %w", err)
}
templateFS = sub
}
funcMap := r.templateFuncs()
// Parse the base layout.
baseLayout, err := template.New("base.html").Funcs(funcMap).ParseFS(templateFS, "layouts/base.html")
if err != nil {
return fmt.Errorf("parse base layout: %w", err)
}
// Parse each page template with the base layout.
pages, err := fs.Glob(templateFS, "pages/*.html")
if err != nil {
return fmt.Errorf("glob pages: %w", err)
}
for _, page := range pages {
name := strings.TrimPrefix(page, "pages/")
name = strings.TrimSuffix(name, ".html")
t, err := baseLayout.Clone()
if err != nil {
return fmt.Errorf("clone base for %s: %w", name, err)
}
_, err = t.ParseFS(templateFS, page)
if err != nil {
return fmt.Errorf("parse page %s: %w", name, err)
}
r.templates[name] = t
}
// Parse partial templates (for HTMX responses).
partials, err := fs.Glob(templateFS, "partials/*.html")
if err != nil {
return fmt.Errorf("glob partials: %w", err)
}
for _, partial := range partials {
name := "partial:" + strings.TrimPrefix(partial, "partials/")
name = strings.TrimSuffix(name, ".html")
t, err := template.New(filepath.Base(partial)).Funcs(funcMap).ParseFS(templateFS, partial)
if err != nil {
return fmt.Errorf("parse partial %s: %w", name, err)
}
r.templates[name] = t
}
slog.Info("templates loaded", "pages", len(pages), "partials", len(partials))
return nil
}
// Page renders a full page with the base layout.
func (r *Renderer) Page(w http.ResponseWriter, req *http.Request, name string, data PageData) {
if r.cfg.DevMode {
// Reparse templates on every request in dev mode.
if err := r.parseTemplates(); err != nil {
slog.Error("template reparse failed", "error", err)
http.Error(w, "Template error", http.StatusInternalServerError)
return
}
}
// Populate common data from context.
data.User = middleware.UserFromContext(req.Context())
data.CSRFToken = middleware.CSRFTokenFromContext(req.Context())
data.BasePath = r.cfg.BasePath
data.SiteName = r.cfg.SiteName
data.ExternalURL = r.cfg.ExternalURL
t, ok := r.templates[name]
if !ok {
slog.Error("template not found", "name", name)
http.Error(w, "Template not found", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := t.ExecuteTemplate(w, "base.html", data); err != nil {
slog.Error("template execute failed", "name", name, "error", err)
}
}
// Partial renders a partial template (for HTMX responses).
func (r *Renderer) Partial(w io.Writer, name string, data any) error {
key := "partial:" + name
t, ok := r.templates[key]
if !ok {
return fmt.Errorf("partial template %q not found", name)
}
return t.Execute(w, data)
}
func (r *Renderer) templateFuncs() template.FuncMap {
return template.FuncMap{
// basePath returns the configured base path for URL construction.
"basePath": func() string {
return r.cfg.BasePath
},
// externalURL returns the configured external URL.
"externalURL": func() string {
return r.cfg.ExternalURL
},
// truncate truncates a string to n characters.
"truncate": func(n int, s string) string {
if len(s) <= n {
return s
}
return s[:n] + "..."
},
// join joins strings with a separator.
"join": strings.Join,
// contains checks if a string contains a substring.
"contains": strings.Contains,
// add returns a + b.
"add": func(a, b int) int { return a + b },
// subtract returns a - b.
"subtract": func(a, b int) int { return a - b },
// maxTags returns the maximum number of tags per fave.
"maxTags": func() int { return store.MaxTagsPerFave },
}
}

276
internal/store/fave.go Normal file
View file

@ -0,0 +1,276 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package store
import (
"database/sql"
"errors"
"fmt"
"strings"
"time"
"kode.naiv.no/olemd/favoritter/internal/model"
)
var ErrFaveNotFound = errors.New("fave not found")
type FaveStore struct {
db *sql.DB
}
func NewFaveStore(db *sql.DB) *FaveStore {
return &FaveStore{db: db}
}
// Create inserts a new fave and returns it with its ID populated.
func (s *FaveStore) Create(userID int64, description, url, imagePath, privacy string) (*model.Fave, error) {
result, err := s.db.Exec(
`INSERT INTO faves (user_id, description, url, image_path, privacy)
VALUES (?, ?, ?, ?, ?)`,
userID, description, url, imagePath, privacy,
)
if err != nil {
return nil, fmt.Errorf("insert fave: %w", err)
}
id, _ := result.LastInsertId()
return s.GetByID(id)
}
// GetByID returns a fave by its ID, including joined user info.
func (s *FaveStore) GetByID(id int64) (*model.Fave, error) {
f := &model.Fave{}
var createdAt, updatedAt string
err := s.db.QueryRow(
`SELECT f.id, f.user_id, f.description, f.url, f.image_path, f.privacy,
f.created_at, f.updated_at, u.username, u.display_name
FROM faves f
JOIN users u ON u.id = f.user_id
WHERE f.id = ?`, id,
).Scan(
&f.ID, &f.UserID, &f.Description, &f.URL, &f.ImagePath, &f.Privacy,
&createdAt, &updatedAt, &f.Username, &f.DisplayName,
)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrFaveNotFound
}
if err != nil {
return nil, fmt.Errorf("query fave: %w", err)
}
f.CreatedAt, _ = time.Parse(time.RFC3339, createdAt)
f.UpdatedAt, _ = time.Parse(time.RFC3339, updatedAt)
return f, nil
}
// Update modifies an existing fave's fields.
func (s *FaveStore) Update(id int64, description, url, imagePath, privacy string) error {
_, err := s.db.Exec(
`UPDATE faves SET description = ?, url = ?, image_path = ?, privacy = ?,
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
WHERE id = ?`,
description, url, imagePath, privacy, id,
)
return err
}
// Delete removes a fave by its ID. The cascade will clean up fave_tags.
func (s *FaveStore) Delete(id int64) error {
result, err := s.db.Exec("DELETE FROM faves WHERE id = ?", id)
if err != nil {
return err
}
n, _ := result.RowsAffected()
if n == 0 {
return ErrFaveNotFound
}
return nil
}
// ListByUser returns all faves for a user (both public and private),
// ordered by newest first, with pagination.
func (s *FaveStore) ListByUser(userID int64, limit, offset int) ([]*model.Fave, int, error) {
var total int
err := s.db.QueryRow("SELECT COUNT(*) FROM faves WHERE user_id = ?", userID).Scan(&total)
if err != nil {
return nil, 0, err
}
rows, err := s.db.Query(
`SELECT f.id, f.user_id, f.description, f.url, f.image_path, f.privacy,
f.created_at, f.updated_at, u.username, u.display_name
FROM faves f
JOIN users u ON u.id = f.user_id
WHERE f.user_id = ?
ORDER BY f.created_at DESC
LIMIT ? OFFSET ?`,
userID, limit, offset,
)
if err != nil {
return nil, 0, err
}
defer rows.Close()
faves, err := s.scanFaves(rows)
return faves, total, err
}
// ListPublicByUser returns only public faves for a user, with pagination.
func (s *FaveStore) ListPublicByUser(userID int64, limit, offset int) ([]*model.Fave, int, error) {
var total int
err := s.db.QueryRow(
"SELECT COUNT(*) FROM faves WHERE user_id = ? AND privacy = 'public'", userID,
).Scan(&total)
if err != nil {
return nil, 0, err
}
rows, err := s.db.Query(
`SELECT f.id, f.user_id, f.description, f.url, f.image_path, f.privacy,
f.created_at, f.updated_at, u.username, u.display_name
FROM faves f
JOIN users u ON u.id = f.user_id
WHERE f.user_id = ? AND f.privacy = 'public'
ORDER BY f.created_at DESC
LIMIT ? OFFSET ?`,
userID, limit, offset,
)
if err != nil {
return nil, 0, err
}
defer rows.Close()
faves, err := s.scanFaves(rows)
return faves, total, err
}
// ListPublic returns all public faves across all users, with pagination.
func (s *FaveStore) ListPublic(limit, offset int) ([]*model.Fave, int, error) {
var total int
err := s.db.QueryRow("SELECT COUNT(*) FROM faves WHERE privacy = 'public'").Scan(&total)
if err != nil {
return nil, 0, err
}
rows, err := s.db.Query(
`SELECT f.id, f.user_id, f.description, f.url, f.image_path, f.privacy,
f.created_at, f.updated_at, u.username, u.display_name
FROM faves f
JOIN users u ON u.id = f.user_id
WHERE f.privacy = 'public'
ORDER BY f.created_at DESC
LIMIT ? OFFSET ?`,
limit, offset,
)
if err != nil {
return nil, 0, err
}
defer rows.Close()
faves, err := s.scanFaves(rows)
return faves, total, err
}
// ListByTag returns all public faves with a given tag, with pagination.
func (s *FaveStore) ListByTag(tagName string, limit, offset int) ([]*model.Fave, int, error) {
var total int
err := s.db.QueryRow(
`SELECT COUNT(*) FROM faves f
JOIN fave_tags ft ON ft.fave_id = f.id
JOIN tags t ON t.id = ft.tag_id
WHERE t.name = ? AND f.privacy = 'public'`, tagName,
).Scan(&total)
if err != nil {
return nil, 0, err
}
rows, err := s.db.Query(
`SELECT f.id, f.user_id, f.description, f.url, f.image_path, f.privacy,
f.created_at, f.updated_at, u.username, u.display_name
FROM faves f
JOIN users u ON u.id = f.user_id
JOIN fave_tags ft ON ft.fave_id = f.id
JOIN tags t ON t.id = ft.tag_id
WHERE t.name = ? AND f.privacy = 'public'
ORDER BY f.created_at DESC
LIMIT ? OFFSET ?`,
tagName, limit, offset,
)
if err != nil {
return nil, 0, err
}
defer rows.Close()
faves, err := s.scanFaves(rows)
return faves, total, err
}
// Count returns the total number of faves.
func (s *FaveStore) Count() (int, error) {
var n int
err := s.db.QueryRow("SELECT COUNT(*) FROM faves").Scan(&n)
return n, err
}
// LoadTags populates the Tags field on each fave.
func (s *FaveStore) LoadTags(faves []*model.Fave) error {
if len(faves) == 0 {
return nil
}
// Build a map for fast lookup.
faveMap := make(map[int64]*model.Fave, len(faves))
ids := make([]any, len(faves))
placeholders := make([]string, len(faves))
for i, f := range faves {
faveMap[f.ID] = f
ids[i] = f.ID
placeholders[i] = "?"
}
query := fmt.Sprintf(
`SELECT ft.fave_id, t.id, t.name
FROM fave_tags ft
JOIN tags t ON t.id = ft.tag_id
WHERE ft.fave_id IN (%s)
ORDER BY t.name COLLATE NOCASE`,
strings.Join(placeholders, ","),
)
rows, err := s.db.Query(query, ids...)
if err != nil {
return fmt.Errorf("load tags: %w", err)
}
defer rows.Close()
for rows.Next() {
var faveID int64
var tag model.Tag
if err := rows.Scan(&faveID, &tag.ID, &tag.Name); err != nil {
return fmt.Errorf("scan tag: %w", err)
}
if f, ok := faveMap[faveID]; ok {
f.Tags = append(f.Tags, tag)
}
}
return rows.Err()
}
func (s *FaveStore) scanFaves(rows *sql.Rows) ([]*model.Fave, error) {
var faves []*model.Fave
for rows.Next() {
f := &model.Fave{}
var createdAt, updatedAt string
err := rows.Scan(
&f.ID, &f.UserID, &f.Description, &f.URL, &f.ImagePath, &f.Privacy,
&createdAt, &updatedAt, &f.Username, &f.DisplayName,
)
if err != nil {
return nil, fmt.Errorf("scan fave: %w", err)
}
f.CreatedAt, _ = time.Parse(time.RFC3339, createdAt)
f.UpdatedAt, _ = time.Parse(time.RFC3339, updatedAt)
faves = append(faves, f)
}
return faves, rows.Err()
}

180
internal/store/fave_test.go Normal file
View file

@ -0,0 +1,180 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package store
import (
"testing"
)
func TestFaveCRUD(t *testing.T) {
db := testDB(t)
users := NewUserStore(db)
faves := NewFaveStore(db)
tags := NewTagStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() { Argon2Memory = 65536; Argon2Time = 3 }()
// Create a user first.
user, err := users.Create("testuser", "password123", "user")
if err != nil {
t.Fatalf("create user: %v", err)
}
// Create a fave.
fave, err := faves.Create(user.ID, "Blade Runner 2049", "https://example.com", "", "public")
if err != nil {
t.Fatalf("create fave: %v", err)
}
if fave.Description != "Blade Runner 2049" {
t.Errorf("description = %q, want %q", fave.Description, "Blade Runner 2049")
}
if fave.Username != "testuser" {
t.Errorf("username = %q, want %q", fave.Username, "testuser")
}
// Get by ID.
got, err := faves.GetByID(fave.ID)
if err != nil {
t.Fatalf("get fave: %v", err)
}
if got.Description != fave.Description {
t.Errorf("got description = %q, want %q", got.Description, fave.Description)
}
// Update.
err = faves.Update(fave.ID, "Blade Runner 2049 (Final Cut)", "https://example.com/br2049", "", "private")
if err != nil {
t.Fatalf("update fave: %v", err)
}
updated, _ := faves.GetByID(fave.ID)
if updated.Description != "Blade Runner 2049 (Final Cut)" {
t.Errorf("updated description = %q", updated.Description)
}
if updated.Privacy != "private" {
t.Errorf("updated privacy = %q, want private", updated.Privacy)
}
// Set tags.
err = tags.SetFaveTags(fave.ID, []string{"film", "sci-fi", "favoritt"})
if err != nil {
t.Fatalf("set tags: %v", err)
}
faveTags, err := tags.ForFave(fave.ID)
if err != nil {
t.Fatalf("for fave: %v", err)
}
if len(faveTags) != 3 {
t.Errorf("tag count = %d, want 3", len(faveTags))
}
// List by user.
list, total, err := faves.ListByUser(user.ID, 10, 0)
if err != nil {
t.Fatalf("list by user: %v", err)
}
if total != 1 || len(list) != 1 {
t.Errorf("list by user: total=%d, len=%d", total, len(list))
}
// Load tags for list.
err = faves.LoadTags(list)
if err != nil {
t.Fatalf("load tags: %v", err)
}
if len(list[0].Tags) != 3 {
t.Errorf("loaded tags = %d, want 3", len(list[0].Tags))
}
// Public list should be empty (fave is now private).
pubList, pubTotal, err := faves.ListPublicByUser(user.ID, 10, 0)
if err != nil {
t.Fatalf("list public: %v", err)
}
if pubTotal != 0 || len(pubList) != 0 {
t.Errorf("public list should be empty: total=%d, len=%d", pubTotal, len(pubList))
}
// Delete.
err = faves.Delete(fave.ID)
if err != nil {
t.Fatalf("delete fave: %v", err)
}
_, err = faves.GetByID(fave.ID)
if err != ErrFaveNotFound {
t.Errorf("deleted fave error = %v, want ErrFaveNotFound", err)
}
}
func TestListByTag(t *testing.T) {
db := testDB(t)
users := NewUserStore(db)
faves := NewFaveStore(db)
tags := NewTagStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() { Argon2Memory = 65536; Argon2Time = 3 }()
user, _ := users.Create("testuser", "password123", "user")
// Create two public faves with overlapping tags.
f1, _ := faves.Create(user.ID, "Fave 1", "", "", "public")
f2, _ := faves.Create(user.ID, "Fave 2", "", "", "public")
f3, _ := faves.Create(user.ID, "Private Fave", "", "", "private")
tags.SetFaveTags(f1.ID, []string{"music", "jazz"})
tags.SetFaveTags(f2.ID, []string{"music", "rock"})
tags.SetFaveTags(f3.ID, []string{"music", "secret"})
// ListByTag only returns public faves.
list, total, err := faves.ListByTag("music", 10, 0)
if err != nil {
t.Fatalf("list by tag: %v", err)
}
if total != 2 {
t.Errorf("total = %d, want 2 (private fave should be excluded)", total)
}
if len(list) != 2 {
t.Errorf("len = %d, want 2", len(list))
}
}
func TestFavePagination(t *testing.T) {
db := testDB(t)
users := NewUserStore(db)
faves := NewFaveStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() { Argon2Memory = 65536; Argon2Time = 3 }()
user, _ := users.Create("testuser", "password123", "user")
// Create 5 faves.
for i := 0; i < 5; i++ {
faves.Create(user.ID, "Fave "+string(rune('A'+i)), "", "", "public")
}
// Page 1 with limit 2.
page1, total, err := faves.ListByUser(user.ID, 2, 0)
if err != nil {
t.Fatalf("page 1: %v", err)
}
if total != 5 {
t.Errorf("total = %d, want 5", total)
}
if len(page1) != 2 {
t.Errorf("page 1 len = %d, want 2", len(page1))
}
// Page 3 with limit 2 should have 1 item.
page3, _, err := faves.ListByUser(user.ID, 2, 4)
if err != nil {
t.Fatalf("page 3: %v", err)
}
if len(page3) != 1 {
t.Errorf("page 3 len = %d, want 1", len(page3))
}
}

119
internal/store/session.go Normal file
View file

@ -0,0 +1,119 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package store
import (
"context"
"crypto/rand"
"database/sql"
"encoding/hex"
"errors"
"fmt"
"log/slog"
"time"
"kode.naiv.no/olemd/favoritter/internal/model"
)
var ErrSessionNotFound = errors.New("session not found")
type SessionStore struct {
db *sql.DB
lifetime time.Duration
}
func NewSessionStore(db *sql.DB) *SessionStore {
return &SessionStore{db: db, lifetime: 720 * time.Hour} // default 30 days
}
// SetLifetime configures the session lifetime.
func (s *SessionStore) SetLifetime(d time.Duration) {
s.lifetime = d
}
// Create generates a new session token for the given user.
func (s *SessionStore) Create(userID int64) (string, error) {
tokenBytes := make([]byte, 32)
if _, err := rand.Read(tokenBytes); err != nil {
return "", fmt.Errorf("generate session token: %w", err)
}
token := hex.EncodeToString(tokenBytes)
expiresAt := time.Now().UTC().Add(s.lifetime)
_, err := s.db.Exec(
`INSERT INTO sessions (token, user_id, expires_at) VALUES (?, ?, ?)`,
token, userID, expiresAt.Format(time.RFC3339),
)
if err != nil {
return "", fmt.Errorf("insert session: %w", err)
}
return token, nil
}
// Validate checks if a session token is valid and not expired.
// Returns the session if valid.
func (s *SessionStore) Validate(token string) (*model.Session, error) {
var session model.Session
var expiresAt, createdAt string
err := s.db.QueryRow(
`SELECT token, user_id, expires_at, created_at
FROM sessions WHERE token = ?`, token,
).Scan(&session.Token, &session.UserID, &expiresAt, &createdAt)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrSessionNotFound
}
if err != nil {
return nil, fmt.Errorf("query session: %w", err)
}
session.ExpiresAt, _ = time.Parse(time.RFC3339, expiresAt)
session.CreatedAt, _ = time.Parse(time.RFC3339, createdAt)
if time.Now().UTC().After(session.ExpiresAt) {
// Session has expired — delete it.
s.Delete(token)
return nil, ErrSessionNotFound
}
return &session, nil
}
// Delete removes a session by its token.
func (s *SessionStore) Delete(token string) error {
_, err := s.db.Exec("DELETE FROM sessions WHERE token = ?", token)
return err
}
// DeleteAllForUser removes all sessions for a given user (e.g., on password change).
func (s *SessionStore) DeleteAllForUser(userID int64) error {
_, err := s.db.Exec("DELETE FROM sessions WHERE user_id = ?", userID)
return err
}
// CleanupLoop periodically removes expired sessions. It runs until the
// context is canceled.
func (s *SessionStore) CleanupLoop(ctx context.Context, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
result, err := s.db.Exec(
`DELETE FROM sessions WHERE expires_at < strftime('%Y-%m-%dT%H:%M:%SZ', 'now')`,
)
if err != nil {
slog.Error("session cleanup failed", "error", err)
continue
}
n, _ := result.RowsAffected()
if n > 0 {
slog.Info("cleaned up expired sessions", "count", n)
}
}
}
}

View file

@ -0,0 +1,46 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package store
import (
"database/sql"
"fmt"
"time"
"kode.naiv.no/olemd/favoritter/internal/model"
)
type SettingsStore struct {
db *sql.DB
}
func NewSettingsStore(db *sql.DB) *SettingsStore {
return &SettingsStore{db: db}
}
// Get returns the current site settings.
func (s *SettingsStore) Get() (*model.SiteSettings, error) {
var settings model.SiteSettings
var updatedAt string
err := s.db.QueryRow(
`SELECT site_name, site_description, signup_mode, updated_at
FROM site_settings WHERE id = 1`,
).Scan(&settings.SiteName, &settings.SiteDescription, &settings.SignupMode, &updatedAt)
if err != nil {
return nil, fmt.Errorf("query site settings: %w", err)
}
settings.UpdatedAt, _ = time.Parse(time.RFC3339, updatedAt)
return &settings, nil
}
// Update updates the site settings.
func (s *SettingsStore) Update(siteName, siteDescription, signupMode string) error {
_, err := s.db.Exec(
`UPDATE site_settings SET site_name = ?, site_description = ?, signup_mode = ?,
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
WHERE id = 1`,
siteName, siteDescription, signupMode,
)
return err
}

View file

@ -0,0 +1,47 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package store
import (
"database/sql"
"errors"
"fmt"
"strings"
)
var ErrSignupRequestExists = errors.New("signup request already exists")
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
}
// 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
}

240
internal/store/tag.go Normal file
View file

@ -0,0 +1,240 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package store
import (
"database/sql"
"errors"
"fmt"
"strings"
"kode.naiv.no/olemd/favoritter/internal/model"
)
const (
MaxTagsPerFave = 20
MaxTagLength = 50
)
var ErrTagNotFound = errors.New("tag not found")
type TagStore struct {
db *sql.DB
}
func NewTagStore(db *sql.DB) *TagStore {
return &TagStore{db: db}
}
// Search returns tags matching a prefix query, for autocomplete.
// Results are ordered by how many faves use each tag (most popular first).
func (s *TagStore) Search(query string, limit int) ([]model.Tag, error) {
query = strings.TrimSpace(strings.ToLower(query))
if query == "" {
return nil, nil
}
rows, err := s.db.Query(
`SELECT t.id, t.name
FROM tags t
LEFT JOIN fave_tags ft ON ft.tag_id = t.id
WHERE t.name LIKE ? || '%'
GROUP BY t.id
ORDER BY COUNT(ft.fave_id) DESC, t.name COLLATE NOCASE
LIMIT ?`,
query, limit,
)
if err != nil {
return nil, fmt.Errorf("search tags: %w", err)
}
defer rows.Close()
return scanTags(rows)
}
func scanTags(rows *sql.Rows) ([]model.Tag, error) {
var tags []model.Tag
for rows.Next() {
var t model.Tag
if err := rows.Scan(&t.ID, &t.Name); err != nil {
return nil, err
}
tags = append(tags, t)
}
return tags, rows.Err()
}
// GetOrCreate returns an existing tag by name, or creates it if it doesn't exist.
// Tag names are normalized to lowercase and trimmed.
func (s *TagStore) GetOrCreate(name string) (*model.Tag, error) {
name = NormalizeTagName(name)
if name == "" {
return nil, fmt.Errorf("empty tag name")
}
if len(name) > MaxTagLength {
return nil, fmt.Errorf("tag name too long (max %d characters)", MaxTagLength)
}
// Try to find existing tag first (COLLATE NOCASE handles case).
var tag model.Tag
err := s.db.QueryRow("SELECT id, name FROM tags WHERE name = ?", name).Scan(&tag.ID, &tag.Name)
if err == nil {
return &tag, nil
}
if !errors.Is(err, sql.ErrNoRows) {
return nil, err
}
// Create new tag.
result, err := s.db.Exec("INSERT INTO tags (name) VALUES (?)", name)
if err != nil {
// Race condition: another request may have created it.
if strings.Contains(err.Error(), "UNIQUE constraint failed") {
err2 := s.db.QueryRow("SELECT id, name FROM tags WHERE name = ?", name).Scan(&tag.ID, &tag.Name)
if err2 != nil {
return nil, err2
}
return &tag, nil
}
return nil, err
}
tag.ID, _ = result.LastInsertId()
tag.Name = name
return &tag, nil
}
// GetByID returns a tag by ID.
func (s *TagStore) GetByID(id int64) (*model.Tag, error) {
var tag model.Tag
err := s.db.QueryRow("SELECT id, name FROM tags WHERE id = ?", id).Scan(&tag.ID, &tag.Name)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrTagNotFound
}
return &tag, err
}
// GetByName returns a tag by its name (case-insensitive).
func (s *TagStore) GetByName(name string) (*model.Tag, error) {
var tag model.Tag
err := s.db.QueryRow("SELECT id, name FROM tags WHERE name = ?", name).Scan(&tag.ID, &tag.Name)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrTagNotFound
}
return &tag, err
}
// AttachToFave links a tag to a fave. No-op if already attached.
func (s *TagStore) AttachToFave(faveID, tagID int64) error {
_, err := s.db.Exec(
"INSERT OR IGNORE INTO fave_tags (fave_id, tag_id) VALUES (?, ?)",
faveID, tagID,
)
return err
}
// DetachFromFave removes a tag from a fave.
func (s *TagStore) DetachFromFave(faveID, tagID int64) error {
_, err := s.db.Exec(
"DELETE FROM fave_tags WHERE fave_id = ? AND tag_id = ?",
faveID, tagID,
)
return err
}
// SetFaveTags replaces all tags on a fave with the given tag names.
// Creates new tags as needed. Enforces MaxTagsPerFave.
func (s *TagStore) SetFaveTags(faveID int64, tagNames []string) error {
if len(tagNames) > MaxTagsPerFave {
tagNames = tagNames[:MaxTagsPerFave]
}
// Remove all existing tags for this fave.
if _, err := s.db.Exec("DELETE FROM fave_tags WHERE fave_id = ?", faveID); err != nil {
return err
}
// Attach new tags.
for _, name := range tagNames {
name = NormalizeTagName(name)
if name == "" {
continue
}
tag, err := s.GetOrCreate(name)
if err != nil {
return fmt.Errorf("get or create tag %q: %w", name, err)
}
if err := s.AttachToFave(faveID, tag.ID); err != nil {
return fmt.Errorf("attach tag %q: %w", name, err)
}
}
return nil
}
// ForFave returns all tags attached to a fave.
func (s *TagStore) ForFave(faveID int64) ([]model.Tag, error) {
rows, err := s.db.Query(
`SELECT t.id, t.name FROM tags t
JOIN fave_tags ft ON ft.tag_id = t.id
WHERE ft.fave_id = ?
ORDER BY t.name COLLATE NOCASE`,
faveID,
)
if err != nil {
return nil, err
}
defer rows.Close()
return scanTags(rows)
}
// ListAll returns all tags ordered by name.
func (s *TagStore) ListAll() ([]model.Tag, error) {
rows, err := s.db.Query("SELECT id, name FROM tags ORDER BY name COLLATE NOCASE")
if err != nil {
return nil, err
}
defer rows.Close()
return scanTags(rows)
}
// Rename changes a tag's name. Returns error if the new name already exists.
func (s *TagStore) Rename(id int64, newName string) error {
newName = NormalizeTagName(newName)
if newName == "" {
return fmt.Errorf("empty tag name")
}
_, err := s.db.Exec("UPDATE tags SET name = ? WHERE id = ?", newName, id)
return err
}
// Delete removes a tag and all its fave associations (via cascade).
func (s *TagStore) Delete(id int64) error {
// fave_tags rows are cleaned up by ON DELETE CASCADE.
result, err := s.db.Exec("DELETE FROM tags WHERE id = ?", id)
if err != nil {
return err
}
n, _ := result.RowsAffected()
if n == 0 {
return ErrTagNotFound
}
return nil
}
// CleanupOrphans removes tags that are not attached to any faves.
func (s *TagStore) CleanupOrphans() (int64, error) {
result, err := s.db.Exec(
`DELETE FROM tags WHERE id NOT IN (SELECT DISTINCT tag_id FROM fave_tags)`,
)
if err != nil {
return 0, err
}
return result.RowsAffected()
}
// NormalizeTagName lowercases and trims a tag name.
func NormalizeTagName(name string) string {
return strings.TrimSpace(strings.ToLower(name))
}

173
internal/store/tag_test.go Normal file
View file

@ -0,0 +1,173 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package store
import (
"testing"
)
func TestTagGetOrCreate(t *testing.T) {
db := testDB(t)
tags := NewTagStore(db)
// Create a new tag.
tag1, err := tags.GetOrCreate("Film")
if err != nil {
t.Fatalf("get or create: %v", err)
}
if tag1.Name != "film" {
t.Errorf("name = %q, want %q (should be normalized to lowercase)", tag1.Name, "film")
}
// Get the same tag again (case-insensitive).
tag2, err := tags.GetOrCreate("FILM")
if err != nil {
t.Fatalf("get or create duplicate: %v", err)
}
if tag2.ID != tag1.ID {
t.Errorf("duplicate tag got different ID: %d vs %d", tag2.ID, tag1.ID)
}
}
func TestTagSearch(t *testing.T) {
db := testDB(t)
tags := NewTagStore(db)
users := NewUserStore(db)
faves := NewFaveStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() { Argon2Memory = 65536; Argon2Time = 3 }()
user, _ := users.Create("testuser", "password123", "user")
// Create some tags via faves to give them usage counts.
f1, _ := faves.Create(user.ID, "F1", "", "", "public")
f2, _ := faves.Create(user.ID, "F2", "", "", "public")
tags.SetFaveTags(f1.ID, []string{"music", "movies", "misc"})
tags.SetFaveTags(f2.ID, []string{"music", "manga"})
// Search for "mu" should return "music" first (2 faves) then nothing else.
results, err := tags.Search("mu", 10)
if err != nil {
t.Fatalf("search: %v", err)
}
if len(results) != 1 {
t.Fatalf("search results = %d, want 1", len(results))
}
if results[0].Name != "music" {
t.Errorf("first result = %q, want %q", results[0].Name, "music")
}
// Search for "m" should return music (2), manga (1), misc (1), movies (1).
results, err = tags.Search("m", 10)
if err != nil {
t.Fatalf("search: %v", err)
}
if len(results) != 4 {
t.Errorf("search results = %d, want 4", len(results))
}
// Music should be first due to highest usage count.
if results[0].Name != "music" {
t.Errorf("first result = %q, want %q (most used)", results[0].Name, "music")
}
// Empty search returns nothing.
results, err = tags.Search("", 10)
if err != nil {
t.Fatalf("empty search: %v", err)
}
if len(results) != 0 {
t.Errorf("empty search results = %d, want 0", len(results))
}
}
func TestTagSetFaveTagsLimit(t *testing.T) {
db := testDB(t)
tags := NewTagStore(db)
users := NewUserStore(db)
faves := NewFaveStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() { Argon2Memory = 65536; Argon2Time = 3 }()
user, _ := users.Create("testuser", "password123", "user")
fave, _ := faves.Create(user.ID, "Test", "", "", "public")
// Try to set more than MaxTagsPerFave tags.
manyTags := make([]string, 30)
for i := range manyTags {
manyTags[i] = "tag" + string(rune('a'+i%26))
}
err := tags.SetFaveTags(fave.ID, manyTags)
if err != nil {
t.Fatalf("set many tags: %v", err)
}
attached, _ := tags.ForFave(fave.ID)
if len(attached) > MaxTagsPerFave {
t.Errorf("attached %d tags, max should be %d", len(attached), MaxTagsPerFave)
}
}
func TestTagCleanupOrphans(t *testing.T) {
db := testDB(t)
tags := NewTagStore(db)
users := NewUserStore(db)
faves := NewFaveStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() { Argon2Memory = 65536; Argon2Time = 3 }()
user, _ := users.Create("testuser", "password123", "user")
fave, _ := faves.Create(user.ID, "Test", "", "", "public")
tags.SetFaveTags(fave.ID, []string{"keep", "orphan"})
// Remove the fave — "keep" and "orphan" are now orphaned.
faves.Delete(fave.ID)
removed, err := tags.CleanupOrphans()
if err != nil {
t.Fatalf("cleanup: %v", err)
}
if removed != 2 {
t.Errorf("removed = %d, want 2", removed)
}
all, _ := tags.ListAll()
if len(all) != 0 {
t.Errorf("remaining tags = %d, want 0", len(all))
}
}
func TestTagRenameAndDelete(t *testing.T) {
db := testDB(t)
tags := NewTagStore(db)
tag, _ := tags.GetOrCreate("oldname")
err := tags.Rename(tag.ID, "NewName")
if err != nil {
t.Fatalf("rename: %v", err)
}
renamed, _ := tags.GetByID(tag.ID)
if renamed.Name != "newname" {
t.Errorf("renamed = %q, want %q", renamed.Name, "newname")
}
err = tags.Delete(tag.ID)
if err != nil {
t.Fatalf("delete: %v", err)
}
_, err = tags.GetByID(tag.ID)
if err != ErrTagNotFound {
t.Errorf("deleted tag error = %v, want ErrTagNotFound", err)
}
}

326
internal/store/user.go Normal file
View file

@ -0,0 +1,326 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package store
import (
"crypto/rand"
"crypto/subtle"
"database/sql"
"encoding/base64"
"errors"
"fmt"
"log/slog"
"strings"
"time"
"golang.org/x/crypto/argon2"
"kode.naiv.no/olemd/favoritter/internal/model"
)
// Argon2id parameters. Defaults match OWASP recommendations.
var (
Argon2Memory uint32 = 65536 // 64 MB
Argon2Time uint32 = 3
Argon2Parallelism uint8 = 2
Argon2KeyLength uint32 = 32
Argon2SaltLength = 16
)
var (
ErrUserNotFound = errors.New("user not found")
ErrUserExists = errors.New("username already taken")
ErrUserDisabled = errors.New("user account is disabled")
ErrInvalidCredentials = errors.New("invalid username or password")
)
type UserStore struct {
db *sql.DB
}
func NewUserStore(db *sql.DB) *UserStore {
return &UserStore{db: db}
}
// Create creates a new user with the given username and plaintext password.
func (s *UserStore) Create(username, password, role string) (*model.User, error) {
hash, err := hashPassword(password)
if err != nil {
return nil, fmt.Errorf("hash password: %w", err)
}
result, err := s.db.Exec(
`INSERT INTO users (username, password_hash, role) VALUES (?, ?, ?)`,
username, hash, role,
)
if err != nil {
if strings.Contains(err.Error(), "UNIQUE constraint failed") {
return nil, ErrUserExists
}
return nil, fmt.Errorf("insert user: %w", err)
}
id, _ := result.LastInsertId()
return s.GetByID(id)
}
// CreateWithReset creates a new user that must reset their password on first login.
func (s *UserStore) CreateWithReset(username, tempPassword, role string) (*model.User, error) {
hash, err := hashPassword(tempPassword)
if err != nil {
return nil, fmt.Errorf("hash password: %w", err)
}
result, err := s.db.Exec(
`INSERT INTO users (username, password_hash, role, must_reset_password) VALUES (?, ?, ?, 1)`,
username, hash, role,
)
if err != nil {
if strings.Contains(err.Error(), "UNIQUE constraint failed") {
return nil, ErrUserExists
}
return nil, fmt.Errorf("insert user: %w", err)
}
id, _ := result.LastInsertId()
return s.GetByID(id)
}
// Authenticate verifies credentials and returns the user if valid.
func (s *UserStore) Authenticate(username, password string) (*model.User, error) {
user, err := s.GetByUsername(username)
if err != nil {
if errors.Is(err, ErrUserNotFound) {
// Still do a dummy hash comparison to prevent timing attacks.
dummyHash(password)
return nil, ErrInvalidCredentials
}
return nil, err
}
if user.Disabled {
return nil, ErrUserDisabled
}
if !verifyPassword(password, user.PasswordHash) {
return nil, ErrInvalidCredentials
}
return user, nil
}
// GetByID retrieves a user by their ID.
func (s *UserStore) GetByID(id int64) (*model.User, error) {
return scanUserFrom(s.db.QueryRow(
`SELECT id, username, display_name, bio, avatar_path, password_hash,
role, profile_visibility, default_fave_privacy,
must_reset_password, disabled, created_at, updated_at
FROM users WHERE id = ?`, id,
))
}
// GetByUsername retrieves a user by their username (case-insensitive).
func (s *UserStore) GetByUsername(username string) (*model.User, error) {
return scanUserFrom(s.db.QueryRow(
`SELECT id, username, display_name, bio, avatar_path, password_hash,
role, profile_visibility, default_fave_privacy,
must_reset_password, disabled, created_at, updated_at
FROM users WHERE username = ?`, username,
))
}
// UpdatePassword changes a user's password and clears the must_reset_password flag.
func (s *UserStore) UpdatePassword(userID int64, newPassword string) error {
hash, err := hashPassword(newPassword)
if err != nil {
return fmt.Errorf("hash password: %w", err)
}
_, err = s.db.Exec(
`UPDATE users SET password_hash = ?, must_reset_password = 0,
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
WHERE id = ?`,
hash, userID,
)
return err
}
// UpdateProfile updates a user's profile fields.
func (s *UserStore) UpdateProfile(userID int64, displayName, bio, profileVisibility, defaultFavePrivacy string) error {
_, err := s.db.Exec(
`UPDATE users SET display_name = ?, bio = ?, profile_visibility = ?,
default_fave_privacy = ?,
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
WHERE id = ?`,
displayName, bio, profileVisibility, defaultFavePrivacy, userID,
)
return err
}
// UpdateAvatar updates a user's avatar path.
func (s *UserStore) UpdateAvatar(userID int64, avatarPath string) error {
_, err := s.db.Exec(
`UPDATE users SET avatar_path = ?,
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
WHERE id = ?`,
avatarPath, userID,
)
return err
}
// SetDisabled enables or disables a user account.
func (s *UserStore) SetDisabled(userID int64, disabled bool) error {
val := 0
if disabled {
val = 1
}
_, err := s.db.Exec(
`UPDATE users SET disabled = ?,
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
WHERE id = ?`,
val, userID,
)
return err
}
// ListAll returns all users, ordered by username.
func (s *UserStore) ListAll() ([]*model.User, error) {
rows, err := s.db.Query(
`SELECT id, username, display_name, bio, avatar_path, password_hash,
role, profile_visibility, default_fave_privacy,
must_reset_password, disabled, created_at, updated_at
FROM users ORDER BY username COLLATE NOCASE`,
)
if err != nil {
return nil, err
}
defer rows.Close()
var users []*model.User
for rows.Next() {
u, err := scanUserFrom(rows)
if err != nil {
return nil, err
}
users = append(users, u)
}
return users, rows.Err()
}
// Count returns the total number of users.
func (s *UserStore) Count() (int, error) {
var n int
err := s.db.QueryRow("SELECT COUNT(*) FROM users").Scan(&n)
return n, err
}
// EnsureAdmin creates the initial admin user if no users exist yet.
// This is called on startup with the configured admin credentials.
func (s *UserStore) EnsureAdmin(username, password string) error {
if username == "" || password == "" {
// No admin credentials configured — only skip if users already exist.
count, err := s.Count()
if err != nil {
return err
}
if count == 0 {
slog.Warn("no admin credentials configured and no users exist — set FAVORITTER_ADMIN_USERNAME and FAVORITTER_ADMIN_PASSWORD")
}
return nil
}
// Check if this admin already exists.
_, err := s.GetByUsername(username)
if err == nil {
return nil // Already exists.
}
if !errors.Is(err, ErrUserNotFound) {
return err
}
_, err = s.Create(username, password, "admin")
if err != nil {
return fmt.Errorf("create admin user: %w", err)
}
slog.Info("created initial admin user", "username", username)
return nil
}
// scanner is implemented by both *sql.Row and *sql.Rows.
type scanner interface {
Scan(dest ...any) error
}
func scanUserFrom(s scanner) (*model.User, error) {
u := &model.User{}
var createdAt, updatedAt string
err := s.Scan(
&u.ID, &u.Username, &u.DisplayName, &u.Bio, &u.AvatarPath,
&u.PasswordHash, &u.Role, &u.ProfileVisibility, &u.DefaultFavePrivacy,
&u.MustResetPassword, &u.Disabled, &createdAt, &updatedAt,
)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrUserNotFound
}
if err != nil {
return nil, fmt.Errorf("scan user: %w", err)
}
u.CreatedAt, _ = time.Parse(time.RFC3339, createdAt)
u.UpdatedAt, _ = time.Parse(time.RFC3339, updatedAt)
return u, nil
}
// Password hashing with Argon2id.
// Format: $argon2id$v=19$m=65536,t=3,p=2$<salt>$<hash>
func hashPassword(password string) (string, error) {
salt := make([]byte, Argon2SaltLength)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("generate salt: %w", err)
}
hash := argon2.IDKey([]byte(password), salt, Argon2Time, Argon2Memory, Argon2Parallelism, Argon2KeyLength)
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version,
Argon2Memory, Argon2Time, Argon2Parallelism,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(hash),
), nil
}
func verifyPassword(password, encodedHash string) bool {
parts := strings.Split(encodedHash, "$")
if len(parts) != 6 || parts[1] != "argon2id" {
return false
}
var memory uint32
var iterations uint32
var parallelism uint8
_, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, &parallelism)
if err != nil {
return false
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil {
return false
}
expectedHash, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil {
return false
}
hash := argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, uint32(len(expectedHash)))
return subtle.ConstantTimeCompare(hash, expectedHash) == 1
}
// dummyHash performs a hash operation to prevent timing-based username enumeration.
func dummyHash(password string) {
salt := make([]byte, Argon2SaltLength)
argon2.IDKey([]byte(password), salt, Argon2Time, Argon2Memory, Argon2Parallelism, Argon2KeyLength)
}

205
internal/store/user_test.go Normal file
View file

@ -0,0 +1,205 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package store
import (
"database/sql"
"testing"
_ "modernc.org/sqlite"
"kode.naiv.no/olemd/favoritter/internal/database"
)
func testDB(t *testing.T) *sql.DB {
t.Helper()
db, err := database.Open(":memory:")
if err != nil {
t.Fatalf("open test db: %v", err)
}
if err := database.Migrate(db); err != nil {
t.Fatalf("migrate test db: %v", err)
}
t.Cleanup(func() { db.Close() })
return db
}
func TestCreateAndAuthenticate(t *testing.T) {
db := testDB(t)
users := NewUserStore(db)
// Use fast Argon2 parameters for tests.
Argon2Memory = 1024
Argon2Time = 1
defer func() {
Argon2Memory = 65536
Argon2Time = 3
}()
// Create a user.
user, err := users.Create("testuser", "password123", "user")
if err != nil {
t.Fatalf("create user: %v", err)
}
if user.Username != "testuser" {
t.Errorf("username = %q, want %q", user.Username, "testuser")
}
if user.Role != "user" {
t.Errorf("role = %q, want %q", user.Role, "user")
}
// Authenticate with correct password.
authed, err := users.Authenticate("testuser", "password123")
if err != nil {
t.Fatalf("authenticate: %v", err)
}
if authed.ID != user.ID {
t.Errorf("authenticated user ID = %d, want %d", authed.ID, user.ID)
}
// Authenticate with wrong password.
_, err = users.Authenticate("testuser", "wrongpassword")
if err != ErrInvalidCredentials {
t.Errorf("wrong password error = %v, want ErrInvalidCredentials", err)
}
// Authenticate with non-existent user.
_, err = users.Authenticate("nouser", "password123")
if err != ErrInvalidCredentials {
t.Errorf("non-existent user error = %v, want ErrInvalidCredentials", err)
}
}
func TestCreateDuplicate(t *testing.T) {
db := testDB(t)
users := NewUserStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() {
Argon2Memory = 65536
Argon2Time = 3
}()
_, err := users.Create("testuser", "password123", "user")
if err != nil {
t.Fatalf("create user: %v", err)
}
_, err = users.Create("testuser", "password456", "user")
if err != ErrUserExists {
t.Errorf("duplicate error = %v, want ErrUserExists", err)
}
// Case-insensitive duplicate.
_, err = users.Create("TestUser", "password456", "user")
if err != ErrUserExists {
t.Errorf("case-insensitive duplicate error = %v, want ErrUserExists", err)
}
}
func TestUpdatePassword(t *testing.T) {
db := testDB(t)
users := NewUserStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() {
Argon2Memory = 65536
Argon2Time = 3
}()
user, err := users.CreateWithReset("admin", "temppass", "admin")
if err != nil {
t.Fatalf("create user: %v", err)
}
if !user.MustResetPassword {
t.Error("expected must_reset_password to be true")
}
err = users.UpdatePassword(user.ID, "newpassword123")
if err != nil {
t.Fatalf("update password: %v", err)
}
// Verify old password no longer works.
_, err = users.Authenticate("admin", "temppass")
if err != ErrInvalidCredentials {
t.Error("old password should not work after reset")
}
// Verify new password works and reset flag is cleared.
updated, err := users.Authenticate("admin", "newpassword123")
if err != nil {
t.Fatalf("authenticate with new password: %v", err)
}
if updated.MustResetPassword {
t.Error("must_reset_password should be false after update")
}
}
func TestEnsureAdmin(t *testing.T) {
db := testDB(t)
users := NewUserStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() {
Argon2Memory = 65536
Argon2Time = 3
}()
// First call creates the admin.
err := users.EnsureAdmin("admin", "adminpass")
if err != nil {
t.Fatalf("ensure admin: %v", err)
}
admin, err := users.GetByUsername("admin")
if err != nil {
t.Fatalf("get admin: %v", err)
}
if !admin.IsAdmin() {
t.Error("expected admin role")
}
// Second call is a no-op.
err = users.EnsureAdmin("admin", "adminpass")
if err != nil {
t.Fatalf("ensure admin (second call): %v", err)
}
count, _ := users.Count()
if count != 1 {
t.Errorf("user count = %d, want 1", count)
}
}
func TestDisabledUser(t *testing.T) {
db := testDB(t)
users := NewUserStore(db)
Argon2Memory = 1024
Argon2Time = 1
defer func() {
Argon2Memory = 65536
Argon2Time = 3
}()
user, err := users.Create("testuser", "password123", "user")
if err != nil {
t.Fatalf("create user: %v", err)
}
// Disable the user.
err = users.SetDisabled(user.ID, true)
if err != nil {
t.Fatalf("disable user: %v", err)
}
// Authentication should fail.
_, err = users.Authenticate("testuser", "password123")
if err != ErrUserDisabled {
t.Errorf("disabled user error = %v, want ErrUserDisabled", err)
}
}