favoritter/internal/store/session.go
Ole-Morten Duesund fc1f7259c5 feat: implement Phase 1 (auth) and Phase 2 (faves CRUD) foundation
Go backend with server-rendered HTML/HTMX frontend, SQLite database,
and filesystem image storage. Self-hostable single-binary architecture.

Phase 1 — Authentication & project foundation:
- Argon2id password hashing with timing-attack prevention
- Session management with cookie-based auth and periodic cleanup
- Login, signup (open/requests/closed modes), logout, forced password reset
- CSRF double-submit cookie pattern with HTMX auto-inclusion
- Proxy-aware real IP extraction (WireGuard/Tailscale support)
- Configurable base path for subdomain and subpath deployment
- Rate limiting on auth endpoints with background cleanup
- Security headers (CSP, X-Frame-Options, Referrer-Policy)
- Structured logging with slog, graceful shutdown
- Pico CSS + HTMX vendored and embedded via go:embed

Phase 2 — Faves CRUD with tags and images:
- Full CRUD for favorites with ownership checks
- Image upload with EXIF stripping, resize to 1920px, UUID filenames
- Tag system with HTMX autocomplete (prefix search, popularity-sorted)
- Privacy controls (public/private per fave, user-configurable default)
- Tag browsing, pagination, batch tag loading (avoids N+1)
- OpenGraph meta tags on public fave detail pages

Includes code quality pass: extracted shared helpers, fixed signup
request persistence bug, plugged rate limiter memory leak, removed
dead code, and logged previously-swallowed errors.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 15:55:22 +02:00

119 lines
3 KiB
Go

// 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)
}
}
}
}