Initial commit
This commit is contained in:
commit
b6014c6ffc
47 files changed
+4329
No files matched your search
@@ -0,0 +1,81 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
const (
|
||||
SessionCookieName = "session"
|
||||
sessionTTL = 7 * 24 * time.Hour
|
||||
)
|
||||
|
||||
// SessionClaims is the app's own JWT payload minted after a successful OIDC
|
||||
// login. Subject is our internal user UUID, not the OIDC sub.
|
||||
type SessionClaims struct {
|
||||
Email string `json:"email"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// MintSessionJWT signs a new session token for the given internal user ID.
|
||||
func MintSessionJWT(secret, userID, email string) (string, error) {
|
||||
now := time.Now()
|
||||
claims := SessionClaims{
|
||||
Email: email,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Subject: userID,
|
||||
Issuer: "vlog-backend",
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
ExpiresAt: jwt.NewNumericDate(now.Add(sessionTTL)),
|
||||
},
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString([]byte(secret))
|
||||
}
|
||||
|
||||
// ParseSessionJWT verifies and decodes a session token, returning the claims.
|
||||
func ParseSessionJWT(secret, tokenString string) (*SessionClaims, error) {
|
||||
claims := &SessionClaims{}
|
||||
token, err := jwt.ParseWithClaims(tokenString, claims, func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
||||
}
|
||||
return []byte(secret), nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !token.Valid {
|
||||
return nil, fmt.Errorf("invalid token")
|
||||
}
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
// SetSessionCookie writes the signed session JWT as an httpOnly cookie.
|
||||
func SetSessionCookie(w http.ResponseWriter, token string, secure bool) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: SessionCookieName,
|
||||
Value: token,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: secure,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: int(sessionTTL.Seconds()),
|
||||
})
|
||||
}
|
||||
|
||||
// ClearSessionCookie logs the user out client-side.
|
||||
func ClearSessionCookie(w http.ResponseWriter, secure bool) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: SessionCookieName,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: secure,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: -1,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const userIDContextKey contextKey = "userID"
|
||||
|
||||
// RequireAuth reads the session cookie, verifies the JWT, and injects the
|
||||
// internal user ID into the request context. Responds 401 if missing/invalid.
|
||||
// This is the only route guard the app needs — every non-auth API route is
|
||||
// wrapped with it.
|
||||
func RequireAuth(jwtSecret string) 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 {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := ParseSessionJWT(jwtSecret, cookie.Value)
|
||||
if err != nil {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), userIDContextKey, claims.Subject)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// UserIDFromContext returns the authenticated user's internal UUID. Only
|
||||
// valid on requests that passed through RequireAuth.
|
||||
func UserIDFromContext(ctx context.Context) (string, bool) {
|
||||
id, ok := ctx.Value(userIDContextKey).(string)
|
||||
return id, ok
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
// Package auth implements the OIDC authorization-code login flow and the
|
||||
// app's own JWT session cookie that replaces the OIDC tokens after login.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
const (
|
||||
stateCookieName = "oidc_state"
|
||||
verifierCookieName = "oidc_verifier"
|
||||
oidcCookieTTL = 5 * time.Minute
|
||||
)
|
||||
|
||||
// OIDCClaims is the subset of ID token claims we care about.
|
||||
type OIDCClaims struct {
|
||||
Sub string `json:"sub"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// Authenticator wraps the discovered OIDC provider + oauth2 config for the
|
||||
// authorization-code flow.
|
||||
type Authenticator struct {
|
||||
provider *oidc.Provider
|
||||
verifier *oidc.IDTokenVerifier
|
||||
oauthConfig oauth2.Config
|
||||
// secureCookies controls the Secure flag on the short-lived login
|
||||
// cookies; false only makes sense for local http:// development.
|
||||
secureCookies bool
|
||||
}
|
||||
|
||||
func NewAuthenticator(ctx context.Context, issuerURL, clientID, clientSecret, redirectURL string, secureCookies bool) (*Authenticator, error) {
|
||||
provider, err := oidc.NewProvider(ctx, issuerURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("discover oidc provider: %w", err)
|
||||
}
|
||||
|
||||
return &Authenticator{
|
||||
provider: provider,
|
||||
verifier: provider.Verifier(&oidc.Config{ClientID: clientID}),
|
||||
oauthConfig: oauth2.Config{
|
||||
ClientID: clientID,
|
||||
ClientSecret: clientSecret,
|
||||
RedirectURL: redirectURL,
|
||||
Endpoint: provider.Endpoint(),
|
||||
Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
|
||||
},
|
||||
secureCookies: secureCookies,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// BeginLogin generates state + a PKCE verifier, stashes both in short-lived
|
||||
// cookies, and redirects the browser to the provider's authorize endpoint.
|
||||
func (a *Authenticator) BeginLogin(w http.ResponseWriter, r *http.Request) {
|
||||
state := randomToken()
|
||||
verifier := oauth2.GenerateVerifier()
|
||||
|
||||
setShortLivedCookie(w, stateCookieName, state, a.secureCookies)
|
||||
setShortLivedCookie(w, verifierCookieName, verifier, a.secureCookies)
|
||||
|
||||
authURL := a.oauthConfig.AuthCodeURL(state, oauth2.S256ChallengeOption(verifier))
|
||||
http.Redirect(w, r, authURL, http.StatusFound)
|
||||
}
|
||||
|
||||
// HandleCallback validates state, exchanges the code for tokens, and returns
|
||||
// the verified ID token claims. It also clears the short-lived cookies.
|
||||
func (a *Authenticator) HandleCallback(ctx context.Context, w http.ResponseWriter, r *http.Request) (*OIDCClaims, error) {
|
||||
defer clearCookie(w, stateCookieName)
|
||||
defer clearCookie(w, verifierCookieName)
|
||||
|
||||
stateCookie, err := r.Cookie(stateCookieName)
|
||||
if err != nil {
|
||||
return nil, errors.New("missing state cookie")
|
||||
}
|
||||
verifierCookie, err := r.Cookie(verifierCookieName)
|
||||
if err != nil {
|
||||
return nil, errors.New("missing verifier cookie")
|
||||
}
|
||||
|
||||
if r.URL.Query().Get("state") != stateCookie.Value {
|
||||
return nil, errors.New("state mismatch")
|
||||
}
|
||||
|
||||
code := r.URL.Query().Get("code")
|
||||
if code == "" {
|
||||
return nil, errors.New("missing code")
|
||||
}
|
||||
|
||||
token, err := a.oauthConfig.Exchange(ctx, code, oauth2.VerifierOption(verifierCookie.Value))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("exchange code: %w", err)
|
||||
}
|
||||
|
||||
rawIDToken, ok := token.Extra("id_token").(string)
|
||||
if !ok {
|
||||
return nil, errors.New("no id_token in token response")
|
||||
}
|
||||
|
||||
idToken, err := a.verifier.Verify(ctx, rawIDToken)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("verify id_token: %w", err)
|
||||
}
|
||||
|
||||
var claims OIDCClaims
|
||||
if err := idToken.Claims(&claims); err != nil {
|
||||
return nil, fmt.Errorf("parse id_token claims: %w", err)
|
||||
}
|
||||
if claims.Sub == "" {
|
||||
return nil, errors.New("id_token missing sub")
|
||||
}
|
||||
|
||||
return &claims, nil
|
||||
}
|
||||
|
||||
func randomToken() string {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(err) // crypto/rand failing is unrecoverable
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
func setShortLivedCookie(w http.ResponseWriter, name, value string, secure bool) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: name,
|
||||
Value: value,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: secure,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: int(oidcCookieTTL.Seconds()),
|
||||
})
|
||||
}
|
||||
|
||||
func clearCookie(w http.ResponseWriter, name string) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: name,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
MaxAge: -1,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// Package config loads and validates the app's configuration from environment
|
||||
// variables. Everything the app needs to run lives here — no config files,
|
||||
// no flags, just env vars (Docker Compose friendly).
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Port string
|
||||
|
||||
// DBDriver is "postgres" (default, production) or "sqlite" (local
|
||||
// dev/testing without a real Postgres instance). When sqlite,
|
||||
// DatabaseURL is a filesystem path to the DB file instead of a DSN.
|
||||
DBDriver string
|
||||
DatabaseURL string
|
||||
|
||||
OIDCIssuerURL string
|
||||
OIDCClientID string
|
||||
OIDCClientSecret string
|
||||
OIDCRedirectURL string
|
||||
|
||||
// PublicBaseURL is this app's own externally-visible URL, e.g.
|
||||
// https://garage.example.com. Used to build the OIDC redirect URL and to
|
||||
// decide whether to mark cookies Secure.
|
||||
PublicBaseURL string
|
||||
|
||||
JWTSigningSecret string
|
||||
|
||||
// StorageDriver is "s3" (default, production) or "local" (writes
|
||||
// uploads to disk — for testing without an S3 bucket). When local,
|
||||
// LocalStoragePath is where files are written.
|
||||
StorageDriver string
|
||||
LocalStoragePath string
|
||||
|
||||
AWSRegion string
|
||||
S3Bucket string
|
||||
// AWS credentials are picked up by the SDK's default credential chain
|
||||
// (env vars, instance role, etc.) — we don't read them ourselves.
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
cfg := &Config{
|
||||
Port: getEnv("PORT", "8080"),
|
||||
DBDriver: getEnv("DB_DRIVER", "postgres"),
|
||||
DatabaseURL: os.Getenv("DATABASE_URL"),
|
||||
OIDCIssuerURL: os.Getenv("OIDC_ISSUER_URL"),
|
||||
OIDCClientID: os.Getenv("OIDC_CLIENT_ID"),
|
||||
OIDCClientSecret: os.Getenv("OIDC_CLIENT_SECRET"),
|
||||
OIDCRedirectURL: os.Getenv("OIDC_REDIRECT_URL"),
|
||||
PublicBaseURL: os.Getenv("PUBLIC_BASE_URL"),
|
||||
JWTSigningSecret: os.Getenv("JWT_SIGNING_SECRET"),
|
||||
StorageDriver: getEnv("STORAGE_DRIVER", "s3"),
|
||||
LocalStoragePath: getEnv("LOCAL_STORAGE_PATH", "./data/uploads"),
|
||||
AWSRegion: os.Getenv("AWS_REGION"),
|
||||
S3Bucket: os.Getenv("S3_BUCKET_NAME"),
|
||||
}
|
||||
|
||||
if cfg.DBDriver != "postgres" && cfg.DBDriver != "sqlite" {
|
||||
return nil, fmt.Errorf("invalid DB_DRIVER %q (must be postgres or sqlite)", cfg.DBDriver)
|
||||
}
|
||||
if cfg.StorageDriver != "s3" && cfg.StorageDriver != "local" {
|
||||
return nil, fmt.Errorf("invalid STORAGE_DRIVER %q (must be s3 or local)", cfg.StorageDriver)
|
||||
}
|
||||
|
||||
required := map[string]string{
|
||||
"DATABASE_URL": cfg.DatabaseURL,
|
||||
"OIDC_ISSUER_URL": cfg.OIDCIssuerURL,
|
||||
"OIDC_CLIENT_ID": cfg.OIDCClientID,
|
||||
"OIDC_CLIENT_SECRET": cfg.OIDCClientSecret,
|
||||
"OIDC_REDIRECT_URL": cfg.OIDCRedirectURL,
|
||||
"PUBLIC_BASE_URL": cfg.PublicBaseURL,
|
||||
"JWT_SIGNING_SECRET": cfg.JWTSigningSecret,
|
||||
}
|
||||
// S3 credentials only matter when actually using S3.
|
||||
if cfg.StorageDriver == "s3" {
|
||||
required["AWS_REGION"] = cfg.AWSRegion
|
||||
required["S3_BUCKET_NAME"] = cfg.S3Bucket
|
||||
}
|
||||
for name, val := range required {
|
||||
if val == "" {
|
||||
return nil, fmt.Errorf("missing required env var %s", name)
|
||||
}
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func getEnv(key, fallback string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// Package db wraps the DB connection and applies the schema on startup so
|
||||
// there's no separate migrate step for the operator to remember. Supports
|
||||
// Postgres (production) and SQLite (local dev/testing without a real
|
||||
// Postgres instance) via DB_DRIVER.
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/golang-migrate/migrate/v4"
|
||||
"github.com/golang-migrate/migrate/v4/database/postgres"
|
||||
"github.com/golang-migrate/migrate/v4/source/iofs"
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
_ "github.com/lib/pq" // postgres driver
|
||||
_ "modernc.org/sqlite" // pure-Go sqlite driver, no CGO
|
||||
|
||||
"vlog/migrations"
|
||||
)
|
||||
|
||||
// Connect opens the DB connection for the given driver ("postgres" or
|
||||
// "sqlite") and applies the schema.
|
||||
func Connect(driver, databaseURL string) (*sqlx.DB, error) {
|
||||
switch driver {
|
||||
case "postgres":
|
||||
return connectPostgres(databaseURL)
|
||||
case "sqlite":
|
||||
return connectSQLite(databaseURL)
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid DB_DRIVER %q (must be postgres or sqlite)", driver)
|
||||
}
|
||||
}
|
||||
|
||||
func connectPostgres(databaseURL string) (*sqlx.DB, error) {
|
||||
conn, err := sqlx.Connect("postgres", databaseURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connect to postgres: %w", err)
|
||||
}
|
||||
|
||||
sourceDriver, err := iofs.New(migrations.PostgresFS, "postgres")
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("load embedded migrations: %w", err)
|
||||
}
|
||||
dbDriver, err := postgres.WithInstance(conn.DB, &postgres.Config{})
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("init postgres migrate driver: %w", err)
|
||||
}
|
||||
m, err := migrate.NewWithInstance("iofs", sourceDriver, "postgres", dbDriver)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("init migrate instance: %w", err)
|
||||
}
|
||||
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("run migrations: %w", err)
|
||||
}
|
||||
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// connectSQLite treats databaseURL as a filesystem path to the DB file
|
||||
// (e.g. "./data/vlog.db"). The schema is applied idempotently on every
|
||||
// startup rather than through golang-migrate — see migrations/sqlite/schema.sql.
|
||||
func connectSQLite(path string) (*sqlx.DB, error) {
|
||||
if dir := filepath.Dir(path); dir != "." && dir != "" {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return nil, fmt.Errorf("create sqlite db directory: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
conn, err := sqlx.Connect("sqlite", path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connect to sqlite: %w", err)
|
||||
}
|
||||
|
||||
// SQLite handles one writer at a time anyway; capping the pool at a
|
||||
// single connection sidesteps per-connection PRAGMA/locking headaches
|
||||
// entirely. Fine for the local dev/testing use case this is for.
|
||||
conn.SetMaxOpenConns(1)
|
||||
|
||||
if _, err := conn.Exec(`PRAGMA foreign_keys = ON`); err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("enable sqlite foreign keys: %w", err)
|
||||
}
|
||||
if _, err := conn.Exec(migrations.SQLiteSchemaSQL); err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("apply sqlite schema: %w", err)
|
||||
}
|
||||
if err := ensureSQLiteColumns(conn); err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("apply sqlite column additions: %w", err)
|
||||
}
|
||||
|
||||
return conn, nil
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
// TestSQLiteAddsMissingColumns simulates exactly the bug a user hit: an
|
||||
// existing local .db file created before share_token/service_interval_*/
|
||||
// is_service existed. Connect must add them in place, not require deleting
|
||||
// the file. The "old" schema is hand-built (not via schema.sql, which
|
||||
// already has the new columns) so CREATE TABLE IF NOT EXISTS in the real
|
||||
// connectSQLite is a genuine no-op against it, same as it would be against
|
||||
// a real pre-existing file.
|
||||
func TestSQLiteAddsMissingColumns(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "old.db")
|
||||
|
||||
oldConn, err := sqlx.Connect("sqlite", path)
|
||||
if err != nil {
|
||||
t.Fatalf("open old-style db: %v", err)
|
||||
}
|
||||
for _, stmt := range []string{
|
||||
`CREATE TABLE users (id TEXT PRIMARY KEY, oidc_sub TEXT NOT NULL UNIQUE, email TEXT NOT NULL, name TEXT, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)`,
|
||||
`CREATE TABLE cars (id TEXT PRIMARY KEY, user_id TEXT NOT NULL, rego TEXT NOT NULL, odometer INTEGER, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)`,
|
||||
`CREATE TABLE service_entries (id TEXT PRIMARY KEY, car_id TEXT NOT NULL, entry_date DATE NOT NULL, entry_type TEXT NOT NULL, odometer INTEGER, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)`,
|
||||
} {
|
||||
if _, err := oldConn.Exec(stmt); err != nil {
|
||||
t.Fatalf("build old-style schema (%s): %v", stmt, err)
|
||||
}
|
||||
}
|
||||
oldConn.Close()
|
||||
|
||||
// Reconnecting through the real path (as a fresh app start would) must
|
||||
// backfill the missing columns without erroring and without the
|
||||
// caller/operator doing anything special.
|
||||
conn, err := connectSQLite(path)
|
||||
if err != nil {
|
||||
t.Fatalf("connect against old-style schema: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
if _, err := conn.Exec(`INSERT INTO cars (id, user_id, rego, service_interval_km) VALUES ('c1', 'u1', 'ABC123', 10000)`); err != nil {
|
||||
t.Fatalf("insert using backfilled column: %v", err)
|
||||
}
|
||||
if _, err := conn.Exec(`UPDATE cars SET share_token = 'tok1' WHERE id = 'c1'`); err != nil {
|
||||
t.Fatalf("update using backfilled share_token column: %v", err)
|
||||
}
|
||||
var count int
|
||||
if err := conn.Get(&count, `SELECT COUNT(*) FROM cars WHERE share_token = 'tok1'`); err != nil || count != 1 {
|
||||
t.Fatalf("expected to find the row by its backfilled share_token, err=%v count=%d", err, count)
|
||||
}
|
||||
|
||||
// The share_token uniqueness constraint must actually be enforced, not
|
||||
// just present as an unconstrained column.
|
||||
if _, err := conn.Exec(`INSERT INTO cars (id, user_id, rego, share_token) VALUES ('c2', 'u1', 'XYZ789', 'tok1')`); err == nil {
|
||||
t.Fatal("expected duplicate share_token to be rejected")
|
||||
}
|
||||
|
||||
if _, err := conn.Exec(`INSERT INTO service_entries (id, car_id, entry_date, entry_type, is_service) VALUES ('e1', 'c1', '2026-01-01', 'Service', 1)`); err != nil {
|
||||
t.Fatalf("insert using backfilled is_service column: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
// sqliteColumnAdditions lists every column added to a pre-existing table
|
||||
// since schema.sql's original CREATE TABLE statements. CREATE TABLE IF NOT
|
||||
// EXISTS is a no-op against a table that already exists, so an existing
|
||||
// local .db file never picks up new columns just by editing schema.sql —
|
||||
// this applies them the same way a real migration would, without requiring
|
||||
// the developer to delete and recreate their local dev database every time
|
||||
// the schema grows during active development.
|
||||
var sqliteColumnAdditions = []struct {
|
||||
table string
|
||||
column string
|
||||
ddl string // type + constraints, everything after the column name
|
||||
}{
|
||||
{"cars", "share_token", "TEXT"},
|
||||
{"cars", "service_interval_km", "INTEGER"},
|
||||
{"cars", "service_interval_months", "INTEGER"},
|
||||
{"service_entries", "is_service", "BOOLEAN NOT NULL DEFAULT 0"},
|
||||
}
|
||||
|
||||
// ensureSQLiteColumns adds any missing columns from the list above, and
|
||||
// (re)creates the share_token uniqueness index — SQLite's ALTER TABLE ADD
|
||||
// COLUMN can't declare UNIQUE inline, so that's a separate CREATE UNIQUE
|
||||
// INDEX IF NOT EXISTS, safe to run every time regardless of whether the
|
||||
// column was just added or already existed.
|
||||
func ensureSQLiteColumns(conn *sqlx.DB) error {
|
||||
for _, c := range sqliteColumnAdditions {
|
||||
var existing []string
|
||||
// pragma_table_info as a table-valued function (not the bare PRAGMA
|
||||
// statement) so this is a normal SELECT we can project down to just
|
||||
// the column we need — the bare PRAGMA form always returns every
|
||||
// column (cid, name, type, ...), which sqlx's strict struct scan
|
||||
// rejects unless every one of them has a matching destination field.
|
||||
if err := conn.Select(&existing, `SELECT name FROM pragma_table_info(?)`, c.table); err != nil {
|
||||
return fmt.Errorf("inspect %s columns: %w", c.table, err)
|
||||
}
|
||||
found := false
|
||||
for _, name := range existing {
|
||||
if name == c.column {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
if _, err := conn.Exec(fmt.Sprintf(`ALTER TABLE %s ADD COLUMN %s %s`, c.table, c.column, c.ddl)); err != nil {
|
||||
return fmt.Errorf("add column %s.%s: %w", c.table, c.column, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := conn.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_cars_share_token ON cars(share_token)`); err != nil {
|
||||
return fmt.Errorf("create share_token index: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"vlog/internal/auth"
|
||||
)
|
||||
|
||||
// Login kicks off the OIDC authorization-code flow.
|
||||
func (h *Handlers) Login(w http.ResponseWriter, r *http.Request) {
|
||||
h.Authenticator.BeginLogin(w, r)
|
||||
}
|
||||
|
||||
// Callback completes the OIDC flow: verifies the ID token, JIT-provisions
|
||||
// the user row, mints our own session JWT, and redirects into the app.
|
||||
func (h *Handlers) Callback(w http.ResponseWriter, r *http.Request) {
|
||||
claims, err := h.Authenticator.HandleCallback(r.Context(), w, r)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnauthorized, "login failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
var name *string
|
||||
if claims.Name != "" {
|
||||
name = &claims.Name
|
||||
}
|
||||
|
||||
var userID string
|
||||
err = h.dbGet(r.Context(), &userID, `
|
||||
INSERT INTO users (id, oidc_sub, email, name)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT (oidc_sub) DO UPDATE SET email = excluded.email, name = excluded.name
|
||||
RETURNING id
|
||||
`, uuid.New().String(), claims.Sub, claims.Email, name)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to provision user")
|
||||
return
|
||||
}
|
||||
|
||||
token, err := auth.MintSessionJWT(h.JWTSecret, userID, claims.Email)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to mint session")
|
||||
return
|
||||
}
|
||||
|
||||
auth.SetSessionCookie(w, token, h.SecureCookies)
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
}
|
||||
|
||||
// Logout clears the session cookie.
|
||||
func (h *Handlers) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
auth.ClearSessionCookie(w, h.SecureCookies)
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
// Me returns the current authenticated user.
|
||||
func (h *Handlers) Me(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
|
||||
var user struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
Email string `db:"email" json:"email"`
|
||||
Name *string `db:"name" json:"name"`
|
||||
}
|
||||
err := h.dbGet(r.Context(), &user, `SELECT id, email, name FROM users WHERE id = ?`, userID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnauthorized, "user not found")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, user)
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"vlog/internal/auth"
|
||||
"vlog/internal/models"
|
||||
"vlog/internal/storage"
|
||||
)
|
||||
|
||||
// ListCars returns the current user's garage.
|
||||
func (h *Handlers) ListCars(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
|
||||
cars := []models.Car{} // not "var" — an empty result must encode as [], not null
|
||||
err := h.dbSelect(r.Context(), &cars, `
|
||||
SELECT * FROM cars WHERE user_id = ? ORDER BY created_at DESC
|
||||
`, userID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list cars")
|
||||
return
|
||||
}
|
||||
for i := range cars {
|
||||
cars[i].HasPhoto = cars[i].PhotoS3Key != nil
|
||||
}
|
||||
writeJSON(w, http.StatusOK, cars)
|
||||
}
|
||||
|
||||
// CreateCar creates a new car in the current user's garage.
|
||||
func (h *Handlers) CreateCar(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
|
||||
var in models.CarInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if in.Rego == "" {
|
||||
writeError(w, http.StatusBadRequest, "rego is required")
|
||||
return
|
||||
}
|
||||
|
||||
regoExpiry, err := parseOptionalDate(in.RegoExpiry)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid regoExpiry")
|
||||
return
|
||||
}
|
||||
wofExpiry, err := parseOptionalDate(in.WofExpiry)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid wofExpiry")
|
||||
return
|
||||
}
|
||||
|
||||
var car models.Car
|
||||
err = h.dbGet(r.Context(), &car, `
|
||||
INSERT INTO cars (id, user_id, rego, make, model, year, color, odometer, rego_expiry, wof_expiry, service_interval_km, service_interval_months)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
RETURNING *
|
||||
`, uuid.New().String(), userID, in.Rego, in.Make, in.Model, in.Year, in.Color, in.Odometer, regoExpiry, wofExpiry, in.ServiceIntervalKM, in.ServiceIntervalMonths)
|
||||
if err != nil {
|
||||
if isUniqueConstraintErr(err) {
|
||||
writeError(w, http.StatusConflict, "could not create car (rego may already exist in your garage)")
|
||||
} else {
|
||||
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to create car: %v", err))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, car)
|
||||
}
|
||||
|
||||
// GetCar returns a single car owned by the current user.
|
||||
func (h *Handlers) GetCar(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
car.HasPhoto = car.PhotoS3Key != nil
|
||||
writeJSON(w, http.StatusOK, car)
|
||||
}
|
||||
|
||||
// UpdateCar edits an existing car.
|
||||
func (h *Handlers) UpdateCar(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var in models.CarInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if in.Rego == "" {
|
||||
writeError(w, http.StatusBadRequest, "rego is required")
|
||||
return
|
||||
}
|
||||
|
||||
regoExpiry, err := parseOptionalDate(in.RegoExpiry)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid regoExpiry")
|
||||
return
|
||||
}
|
||||
wofExpiry, err := parseOptionalDate(in.WofExpiry)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid wofExpiry")
|
||||
return
|
||||
}
|
||||
|
||||
var updated models.Car
|
||||
err = h.dbGet(r.Context(), &updated, `
|
||||
UPDATE cars
|
||||
SET rego = ?, make = ?, model = ?, year = ?, color = ?,
|
||||
odometer = ?, rego_expiry = ?, wof_expiry = ?,
|
||||
service_interval_km = ?, service_interval_months = ?, updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
RETURNING *
|
||||
`, in.Rego, in.Make, in.Model, in.Year, in.Color, in.Odometer, regoExpiry, wofExpiry,
|
||||
in.ServiceIntervalKM, in.ServiceIntervalMonths, car.ID)
|
||||
if err != nil {
|
||||
if isUniqueConstraintErr(err) {
|
||||
writeError(w, http.StatusConflict, "could not update car (rego may already exist in your garage)")
|
||||
} else {
|
||||
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to update car: %v", err))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, updated)
|
||||
}
|
||||
|
||||
// DeleteCar removes a car (cascades to service entries, files, reminders in
|
||||
// the DB; best-effort cleans up its photo in storage).
|
||||
func (h *Handlers) DeleteCar(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := h.dbExec(r.Context(), `DELETE FROM cars WHERE id = ?`, car.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to delete car")
|
||||
return
|
||||
}
|
||||
|
||||
if car.PhotoS3Key != nil {
|
||||
_ = h.Storage.Delete(r.Context(), *car.PhotoS3Key)
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
// UploadCarPhoto accepts a multipart PNG/JPEG upload and replaces the car's photo.
|
||||
func (h *Handlers) UploadCarPhoto(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
file, contentType, ok := parseUploadedFile(w, r, 10<<20, storage.AllowedPhotoTypes)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
oldKey := car.PhotoS3Key
|
||||
key := fmt.Sprintf("users/%s/cars/%s/photo.%s", car.UserID, car.ID, extensionForContentType(contentType))
|
||||
|
||||
if err := h.Storage.Upload(r.Context(), key, contentType, file); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to upload photo")
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := h.dbExec(r.Context(), `
|
||||
UPDATE cars SET photo_s3_key = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?
|
||||
`, key, car.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to save photo reference")
|
||||
return
|
||||
}
|
||||
|
||||
if oldKey != nil && *oldKey != key {
|
||||
_ = h.Storage.Delete(r.Context(), *oldKey)
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
// GetCarPhoto streams the car's photo from storage.
|
||||
func (h *Handlers) GetCarPhoto(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if car.PhotoS3Key == nil {
|
||||
writeError(w, http.StatusNotFound, "no photo set")
|
||||
return
|
||||
}
|
||||
|
||||
body, err := h.Storage.Get(r.Context(), *car.PhotoS3Key)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "photo not found")
|
||||
return
|
||||
}
|
||||
defer body.Close()
|
||||
|
||||
w.Header().Set("Content-Type", contentTypeForExtension(*car.PhotoS3Key))
|
||||
w.Header().Set("Cache-Control", "private, max-age=60")
|
||||
io.Copy(w, body)
|
||||
}
|
||||
|
||||
// UpdateOdometer is a lightweight endpoint for just bumping the odometer
|
||||
// reading — quicker than resending the whole car record via UpdateCar.
|
||||
func (h *Handlers) UpdateOdometer(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Odometer int `json:"odometer"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if body.Odometer < 0 {
|
||||
writeError(w, http.StatusBadRequest, "odometer must be positive")
|
||||
return
|
||||
}
|
||||
|
||||
var updated models.Car
|
||||
err := h.dbGet(r.Context(), &updated, `
|
||||
UPDATE cars SET odometer = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? RETURNING *
|
||||
`, body.Odometer, car.ID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to update odometer")
|
||||
return
|
||||
}
|
||||
updated.HasPhoto = updated.PhotoS3Key != nil
|
||||
writeJSON(w, http.StatusOK, updated)
|
||||
}
|
||||
|
||||
// GenerateShareLink turns on (or regenerates, invalidating the previous
|
||||
// link/QR code) public read-only sharing for a car.
|
||||
func (h *Handlers) GenerateShareLink(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
token := randomID() + randomID() // 64 hex chars of entropy — not guessable
|
||||
var updated models.Car
|
||||
err := h.dbGet(r.Context(), &updated, `
|
||||
UPDATE cars SET share_token = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? RETURNING *
|
||||
`, token, car.ID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to generate share link")
|
||||
return
|
||||
}
|
||||
updated.HasPhoto = updated.PhotoS3Key != nil
|
||||
writeJSON(w, http.StatusOK, updated)
|
||||
}
|
||||
|
||||
// RevokeShareLink turns off public sharing for a car.
|
||||
func (h *Handlers) RevokeShareLink(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := h.dbExec(r.Context(), `
|
||||
UPDATE cars SET share_token = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?
|
||||
`, car.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to revoke share link")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (h *Handlers) loadOwnedCar(w http.ResponseWriter, r *http.Request) (*models.Car, bool) {
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
carID := r.PathValue("carId")
|
||||
|
||||
var car models.Car
|
||||
err := h.dbGet(r.Context(), &car, `
|
||||
SELECT * FROM cars WHERE id = ? AND user_id = ?
|
||||
`, carID, userID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "car not found")
|
||||
return nil, false
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to load car: %v", err))
|
||||
return nil, false
|
||||
}
|
||||
return &car, true
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"vlog/internal/auth"
|
||||
"vlog/internal/models"
|
||||
)
|
||||
|
||||
// Dashboard computes the "what's coming up" view for the current user:
|
||||
// open reminders due soon/overdue (real + synthesized rego/WoF/service-due),
|
||||
// across every car. It's computed at request time — no scheduler, no
|
||||
// email, matching the in-app-only reminder decision. Shares its synthesis
|
||||
// logic with the car-scoped ListReminders (see reminder_view.go) so the two
|
||||
// views never disagree about what's due.
|
||||
func (h *Handlers) Dashboard(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
todayDate := today()
|
||||
|
||||
var cars []models.Car
|
||||
if err := h.dbSelect(r.Context(), &cars, `SELECT * FROM cars WHERE user_id = ?`, userID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load dashboard")
|
||||
return
|
||||
}
|
||||
|
||||
carByID := make(map[string]models.Car, len(cars))
|
||||
carIDs := make([]string, len(cars))
|
||||
for i, c := range cars {
|
||||
carByID[c.ID] = c
|
||||
carIDs[i] = c.ID
|
||||
}
|
||||
|
||||
items := []models.ReminderView{} // not "var" — an empty result must encode as [], not null
|
||||
|
||||
if len(carIDs) > 0 {
|
||||
query, args, err := sqlx.In(`SELECT * FROM reminders WHERE car_id IN (?) AND completed_at IS NULL`, carIDs)
|
||||
if err == nil {
|
||||
var reminders []models.Reminder
|
||||
if err := h.dbSelect(r.Context(), &reminders, query, args...); err == nil {
|
||||
for _, rem := range reminders {
|
||||
car := carByID[rem.CarID]
|
||||
view := reminderToView(rem, car.Rego, car.Odometer, todayDate)
|
||||
if view.Status == "overdue" || view.Status == "upcoming" {
|
||||
items = append(items, view)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, c := range cars {
|
||||
car := c // local copy — synthesizedReminders takes a pointer
|
||||
for _, view := range synthesizedReminders(r.Context(), h, &car, todayDate) {
|
||||
if view.Status == "overdue" || view.Status == "upcoming" {
|
||||
items = append(items, view)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sortReminderViews(items)
|
||||
writeJSON(w, http.StatusOK, items)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package handlers
|
||||
|
||||
import "time"
|
||||
|
||||
const dateLayout = "2006-01-02"
|
||||
|
||||
// parseOptionalDate parses a "YYYY-MM-DD" string, treating nil/empty as no
|
||||
// value. Used for the optional date fields on car/reminder inputs.
|
||||
func parseOptionalDate(s *string) (*time.Time, error) {
|
||||
if s == nil || *s == "" {
|
||||
return nil, nil
|
||||
}
|
||||
t, err := time.Parse(dateLayout, *s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &t, nil
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"vlog/internal/auth"
|
||||
"vlog/internal/models"
|
||||
"vlog/internal/storage"
|
||||
)
|
||||
|
||||
// parseUploadedFile extracts the "file" multipart field, enforces maxBytes,
|
||||
// and sniffs+validates its real content type against allowed (never trusts
|
||||
// the client-declared type/extension). Returns the file handle reset to the
|
||||
// start, ready to stream to storage — caller must Close it.
|
||||
func parseUploadedFile(w http.ResponseWriter, r *http.Request, maxBytes int64, allowed map[string]bool) (multipart.File, string, bool) {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
|
||||
if err := r.ParseMultipartForm(maxBytes); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "file too large or invalid upload")
|
||||
return nil, "", false
|
||||
}
|
||||
|
||||
file, _, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "missing file")
|
||||
return nil, "", false
|
||||
}
|
||||
|
||||
contentType, err := storage.DetectAndValidate(file, allowed)
|
||||
if err != nil {
|
||||
file.Close()
|
||||
writeError(w, http.StatusUnsupportedMediaType, err.Error())
|
||||
return nil, "", false
|
||||
}
|
||||
|
||||
return file, contentType, true
|
||||
}
|
||||
|
||||
func extensionForContentType(ct string) string {
|
||||
switch ct {
|
||||
case "image/png":
|
||||
return "png"
|
||||
case "image/jpeg":
|
||||
return "jpg"
|
||||
case "application/pdf":
|
||||
return "pdf"
|
||||
default:
|
||||
return "bin"
|
||||
}
|
||||
}
|
||||
|
||||
func contentTypeForExtension(key string) string {
|
||||
switch {
|
||||
case strings.HasSuffix(key, ".png"):
|
||||
return "image/png"
|
||||
case strings.HasSuffix(key, ".jpg"), strings.HasSuffix(key, ".jpeg"):
|
||||
return "image/jpeg"
|
||||
case strings.HasSuffix(key, ".pdf"):
|
||||
return "application/pdf"
|
||||
default:
|
||||
return "application/octet-stream"
|
||||
}
|
||||
}
|
||||
|
||||
func randomID() string {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// sanitizeFileName strips any path components and whitespace so it's safe
|
||||
// to embed in a storage key and to send back in Content-Disposition.
|
||||
func sanitizeFileName(name string) string {
|
||||
name = filepath.Base(name)
|
||||
name = strings.ReplaceAll(name, " ", "_")
|
||||
if name == "" || name == "." || name == "/" {
|
||||
return "file"
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// GetFile streams a service-entry attachment after verifying the requesting
|
||||
// user owns the car the entry belongs to.
|
||||
func (h *Handlers) GetFile(w http.ResponseWriter, r *http.Request) {
|
||||
file, ok := h.loadOwnedFile(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
body, err := h.Storage.Get(r.Context(), file.S3Key)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "file not found in storage")
|
||||
return
|
||||
}
|
||||
defer body.Close()
|
||||
|
||||
w.Header().Set("Content-Type", file.ContentType)
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, file.FileName))
|
||||
io.Copy(w, body)
|
||||
}
|
||||
|
||||
// DeleteFile removes a single attachment.
|
||||
func (h *Handlers) DeleteFile(w http.ResponseWriter, r *http.Request) {
|
||||
file, ok := h.loadOwnedFile(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := h.dbExec(r.Context(), `DELETE FROM service_entry_files WHERE id = ?`, file.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to delete file")
|
||||
return
|
||||
}
|
||||
_ = h.Storage.Delete(r.Context(), file.S3Key)
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (h *Handlers) loadOwnedFile(w http.ResponseWriter, r *http.Request) (*models.ServiceEntryFile, bool) {
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
fileID := r.PathValue("fileId")
|
||||
|
||||
var file models.ServiceEntryFile
|
||||
err := h.dbGet(r.Context(), &file, `
|
||||
SELECT sef.*
|
||||
FROM service_entry_files sef
|
||||
JOIN service_entries se ON se.id = sef.service_entry_id
|
||||
JOIN cars c ON c.id = se.car_id
|
||||
WHERE sef.id = ? AND c.user_id = ?
|
||||
`, fileID, userID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "file not found")
|
||||
return nil, false
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load file")
|
||||
return nil, false
|
||||
}
|
||||
return &file, true
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"vlog/internal/auth"
|
||||
"vlog/internal/models"
|
||||
)
|
||||
|
||||
// ListFuelEntries returns one page of a car's fuel-up history, newest
|
||||
// first. Paginated for the same reason as service entries — no unbounded
|
||||
// fetch regardless of how long the car's been tracked.
|
||||
func (h *Handlers) ListFuelEntries(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, offset := parsePagination(r)
|
||||
|
||||
entries := []models.FuelEntry{} // not "var" — empty result must encode as [], not null
|
||||
err := h.dbSelect(r.Context(), &entries, `
|
||||
SELECT * FROM fuel_entries WHERE car_id = ?
|
||||
ORDER BY entry_date DESC, created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`, car.ID, limit+1, offset)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list fuel entries")
|
||||
return
|
||||
}
|
||||
|
||||
entries, hasMore := paginate(limit, entries)
|
||||
writeJSON(w, http.StatusOK, page[models.FuelEntry]{Items: entries, HasMore: hasMore})
|
||||
}
|
||||
|
||||
// CreateFuelEntry adds a fuel-up to a car.
|
||||
func (h *Handlers) CreateFuelEntry(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
in, entryDate, ok := decodeFuelEntryInput(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var entry models.FuelEntry
|
||||
err := h.dbGet(r.Context(), &entry, `
|
||||
INSERT INTO fuel_entries (id, car_id, entry_date, litres, cost, odometer, location, notes)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
RETURNING *
|
||||
`, uuid.New().String(), car.ID, entryDate, in.Litres, in.Cost, in.Odometer, in.Location, in.Notes)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to create fuel entry")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, entry)
|
||||
}
|
||||
|
||||
// UpdateFuelEntry edits a fuel entry's fields.
|
||||
func (h *Handlers) UpdateFuelEntry(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := h.loadOwnedFuelEntry(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
in, entryDate, ok := decodeFuelEntryInput(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var updated models.FuelEntry
|
||||
err := h.dbGet(r.Context(), &updated, `
|
||||
UPDATE fuel_entries
|
||||
SET entry_date = ?, litres = ?, cost = ?, odometer = ?, location = ?, notes = ?
|
||||
WHERE id = ?
|
||||
RETURNING *
|
||||
`, entryDate, in.Litres, in.Cost, in.Odometer, in.Location, in.Notes, entry.ID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to update fuel entry")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, updated)
|
||||
}
|
||||
|
||||
// DeleteFuelEntry removes a fuel entry.
|
||||
func (h *Handlers) DeleteFuelEntry(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := h.loadOwnedFuelEntry(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := h.dbExec(r.Context(), `DELETE FROM fuel_entries WHERE id = ?`, entry.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to delete fuel entry")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func decodeFuelEntryInput(w http.ResponseWriter, r *http.Request) (models.FuelEntryInput, time.Time, bool) {
|
||||
var in models.FuelEntryInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return in, time.Time{}, false
|
||||
}
|
||||
if in.Litres <= 0 {
|
||||
writeError(w, http.StatusBadRequest, "litres must be greater than 0")
|
||||
return in, time.Time{}, false
|
||||
}
|
||||
if in.Cost <= 0 {
|
||||
writeError(w, http.StatusBadRequest, "cost must be greater than 0")
|
||||
return in, time.Time{}, false
|
||||
}
|
||||
entryDate, err := time.Parse(dateLayout, in.EntryDate)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid entryDate")
|
||||
return in, time.Time{}, false
|
||||
}
|
||||
return in, entryDate, true
|
||||
}
|
||||
|
||||
func (h *Handlers) loadOwnedFuelEntry(w http.ResponseWriter, r *http.Request) (*models.FuelEntry, bool) {
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
entryID := r.PathValue("entryId")
|
||||
|
||||
var entry models.FuelEntry
|
||||
err := h.dbGet(r.Context(), &entry, `
|
||||
SELECT fe.*
|
||||
FROM fuel_entries fe
|
||||
JOIN cars c ON c.id = fe.car_id
|
||||
WHERE fe.id = ? AND c.user_id = ?
|
||||
`, entryID, userID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "fuel entry not found")
|
||||
return nil, false
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load fuel entry")
|
||||
return nil, false
|
||||
}
|
||||
return &entry, true
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// Package handlers implements the JSON API. All handlers hang off Handlers,
|
||||
// which carries the shared dependencies (DB, storage, auth) they need.
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"vlog/internal/auth"
|
||||
"vlog/internal/storage"
|
||||
)
|
||||
|
||||
type Handlers struct {
|
||||
DB *sqlx.DB
|
||||
Storage storage.Storage
|
||||
Authenticator *auth.Authenticator
|
||||
JWTSecret string
|
||||
SecureCookies bool
|
||||
}
|
||||
|
||||
func New(db *sqlx.DB, store storage.Storage, authenticator *auth.Authenticator, jwtSecret string, secureCookies bool) *Handlers {
|
||||
return &Handlers{
|
||||
DB: db,
|
||||
Storage: store,
|
||||
Authenticator: authenticator,
|
||||
JWTSecret: jwtSecret,
|
||||
SecureCookies: secureCookies,
|
||||
}
|
||||
}
|
||||
|
||||
// All queries in this package are written with "?" placeholders (SQLite's
|
||||
// native style) and go through these three helpers, which rebind to "$1,
|
||||
// $2, ..." automatically when running against Postgres. This is what lets
|
||||
// the same query strings work against both DB_DRIVER options.
|
||||
|
||||
func (h *Handlers) dbGet(ctx context.Context, dest interface{}, query string, args ...interface{}) error {
|
||||
return h.DB.GetContext(ctx, dest, h.DB.Rebind(query), args...)
|
||||
}
|
||||
|
||||
func (h *Handlers) dbSelect(ctx context.Context, dest interface{}, query string, args ...interface{}) error {
|
||||
return h.DB.SelectContext(ctx, dest, h.DB.Rebind(query), args...)
|
||||
}
|
||||
|
||||
func (h *Handlers) dbExec(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
|
||||
return h.DB.ExecContext(ctx, h.DB.Rebind(query), args...)
|
||||
}
|
||||
|
||||
// writeJSON marshals v as the response body, or 500s if it fails.
|
||||
func writeJSON(w http.ResponseWriter, status int, v interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
if err := json.NewEncoder(w).Encode(v); err != nil {
|
||||
// Response is already partially written at this point; just log.
|
||||
// (No logger wired up yet — keep it dead simple and let it be silent
|
||||
// in the rare case encoding itself fails.)
|
||||
_ = err
|
||||
}
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, message string) {
|
||||
writeJSON(w, status, map[string]string{"error": message})
|
||||
}
|
||||
|
||||
// isUniqueConstraintErr distinguishes an actual unique-constraint violation
|
||||
// (e.g. duplicate rego) from any other DB error, so a schema/column problem
|
||||
// during development doesn't get mislabeled as "already exists" and hide
|
||||
// the real cause. Postgres and SQLite word this differently, so it's a
|
||||
// substring match on the driver's own error text rather than a typed
|
||||
// sentinel — good enough since the only thing we do with it is pick the
|
||||
// response code/message, not branch on a specific constraint.
|
||||
func isUniqueConstraintErr(err error) bool {
|
||||
msg := strings.ToLower(err.Error())
|
||||
return strings.Contains(msg, "unique constraint") || strings.Contains(msg, "duplicate key")
|
||||
}
|
||||
|
||||
// page is the response shape for every paginated list endpoint — long lists
|
||||
// (service history, knowledgebase) load a page at a time instead of
|
||||
// dumping everything into one response/DOM.
|
||||
type page[T any] struct {
|
||||
Items []T `json:"items"`
|
||||
HasMore bool `json:"hasMore"`
|
||||
}
|
||||
|
||||
const (
|
||||
defaultPageSize = 20
|
||||
maxPageSize = 100
|
||||
)
|
||||
|
||||
// parsePagination reads ?limit=&offset= from the query string, applying
|
||||
// sane defaults/bounds so a bad or missing value can't blow up the page
|
||||
// size or request something nonsensical.
|
||||
func parsePagination(r *http.Request) (limit, offset int) {
|
||||
limit = defaultPageSize
|
||||
if v, err := strconv.Atoi(r.URL.Query().Get("limit")); err == nil && v > 0 {
|
||||
limit = v
|
||||
}
|
||||
if limit > maxPageSize {
|
||||
limit = maxPageSize
|
||||
}
|
||||
offset = 0
|
||||
if v, err := strconv.Atoi(r.URL.Query().Get("offset")); err == nil && v > 0 {
|
||||
offset = v
|
||||
}
|
||||
return limit, offset
|
||||
}
|
||||
|
||||
// paginate expects rows fetched with LIMIT limit+1, so it can tell whether
|
||||
// there's a next page without a separate COUNT(*) query — then trims back
|
||||
// down to limit.
|
||||
func paginate[T any](limit int, rows []T) (trimmed []T, hasMore bool) {
|
||||
hasMore = len(rows) > limit
|
||||
if hasMore {
|
||||
rows = rows[:limit]
|
||||
}
|
||||
return rows, hasMore
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"vlog/internal/auth"
|
||||
"vlog/internal/models"
|
||||
)
|
||||
|
||||
// ListKnowledge returns one page of a car's knowledgebase entries
|
||||
// (procedures, common problems, reference info like coolant type), most
|
||||
// recently updated first. Paginated (?limit=&offset=) for the same reason
|
||||
// as service entries — a big knowledgebase shouldn't mean one giant fetch.
|
||||
func (h *Handlers) ListKnowledge(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, offset := parsePagination(r)
|
||||
|
||||
entries := []models.KnowledgeEntry{} // not "var" — empty result must encode as [], not null
|
||||
err := h.dbSelect(r.Context(), &entries, `
|
||||
SELECT * FROM knowledge_entries WHERE car_id = ?
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`, car.ID, limit+1, offset)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list knowledge entries")
|
||||
return
|
||||
}
|
||||
|
||||
entries, hasMore := paginate(limit, entries)
|
||||
writeJSON(w, http.StatusOK, page[models.KnowledgeEntry]{Items: entries, HasMore: hasMore})
|
||||
}
|
||||
|
||||
// CreateKnowledge adds a new knowledgebase entry to a car.
|
||||
func (h *Handlers) CreateKnowledge(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
in, ok := decodeKnowledgeInput(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var entry models.KnowledgeEntry
|
||||
err := h.dbGet(r.Context(), &entry, `
|
||||
INSERT INTO knowledge_entries (id, car_id, title, body)
|
||||
VALUES (?, ?, ?, ?)
|
||||
RETURNING *
|
||||
`, uuid.New().String(), car.ID, in.Title, in.Body)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to create knowledge entry")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, entry)
|
||||
}
|
||||
|
||||
// UpdateKnowledge edits a knowledgebase entry's title/body.
|
||||
func (h *Handlers) UpdateKnowledge(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := h.loadOwnedKnowledge(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
in, ok := decodeKnowledgeInput(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var updated models.KnowledgeEntry
|
||||
err := h.dbGet(r.Context(), &updated, `
|
||||
UPDATE knowledge_entries
|
||||
SET title = ?, body = ?, updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
RETURNING *
|
||||
`, in.Title, in.Body, entry.ID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to update knowledge entry")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, updated)
|
||||
}
|
||||
|
||||
// DeleteKnowledge removes a knowledgebase entry.
|
||||
func (h *Handlers) DeleteKnowledge(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := h.loadOwnedKnowledge(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := h.dbExec(r.Context(), `DELETE FROM knowledge_entries WHERE id = ?`, entry.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to delete knowledge entry")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func decodeKnowledgeInput(w http.ResponseWriter, r *http.Request) (models.KnowledgeEntryInput, bool) {
|
||||
var in models.KnowledgeEntryInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return in, false
|
||||
}
|
||||
if in.Title == "" {
|
||||
writeError(w, http.StatusBadRequest, "title is required")
|
||||
return in, false
|
||||
}
|
||||
return in, true
|
||||
}
|
||||
|
||||
func (h *Handlers) loadOwnedKnowledge(w http.ResponseWriter, r *http.Request) (*models.KnowledgeEntry, bool) {
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
entryID := r.PathValue("knowledgeId")
|
||||
|
||||
var entry models.KnowledgeEntry
|
||||
err := h.dbGet(r.Context(), &entry, `
|
||||
SELECT k.*
|
||||
FROM knowledge_entries k
|
||||
JOIN cars c ON c.id = k.car_id
|
||||
WHERE k.id = ? AND c.user_id = ?
|
||||
`, entryID, userID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "knowledge entry not found")
|
||||
return nil, false
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load knowledge entry")
|
||||
return nil, false
|
||||
}
|
||||
return &entry, true
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sort"
|
||||
"time"
|
||||
)
|
||||
|
||||
type MileageResponse struct {
|
||||
CurrentOdometer *int `json:"currentOdometer"`
|
||||
KmPerYear *float64 `json:"kmPerYear"`
|
||||
// YearsPer100k/Next100kEta answer "how long does it take to put another
|
||||
// 100,000km on this car at my current rate" — a throughput figure, not
|
||||
// tied to the odometer's current position (68,420km → 100,000km is a
|
||||
// misleadingly small gap; this is always a full 100,000km from today).
|
||||
YearsPer100k *float64 `json:"yearsPer100k"`
|
||||
Next100kEta *string `json:"next100kEta"`
|
||||
}
|
||||
|
||||
// milestoneDistance is the block of driving the "how long" estimate is
|
||||
// measured over — a generic throughput unit, not a specific odometer target.
|
||||
const milestoneDistance = 100_000
|
||||
|
||||
// Mileage reports the car's usage rate: an estimated km/year (derived from
|
||||
// every known odometer+date pair across service and fuel entries, plus the
|
||||
// car's own current reading) and how long, at that rate, it takes to add
|
||||
// another 100,000km from today. Needs at least two data points to estimate
|
||||
// a rate — with fewer, it just reports the current reading.
|
||||
func (h *Handlers) Mileage(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
type odometerPoint struct {
|
||||
EntryDate time.Time `db:"entry_date"`
|
||||
Odometer int `db:"odometer"`
|
||||
}
|
||||
|
||||
var points []odometerPoint
|
||||
_ = h.dbSelect(r.Context(), &points, `
|
||||
SELECT entry_date, odometer FROM service_entries WHERE car_id = ? AND odometer IS NOT NULL
|
||||
UNION ALL
|
||||
SELECT entry_date, odometer FROM fuel_entries WHERE car_id = ? AND odometer IS NOT NULL
|
||||
`, car.ID, car.ID)
|
||||
// best-effort: a query error just means we fall back to "current reading
|
||||
// only" below, rather than failing the whole endpoint.
|
||||
|
||||
if car.Odometer != nil {
|
||||
points = append(points, odometerPoint{EntryDate: today(), Odometer: *car.Odometer})
|
||||
}
|
||||
sort.Slice(points, func(i, j int) bool { return points[i].EntryDate.Before(points[j].EntryDate) })
|
||||
|
||||
resp := MileageResponse{CurrentOdometer: car.Odometer}
|
||||
|
||||
if len(points) >= 2 {
|
||||
first, last := points[0], points[len(points)-1]
|
||||
days := last.EntryDate.Sub(first.EntryDate).Hours() / 24
|
||||
if days > 0 && last.Odometer > first.Odometer {
|
||||
kmPerYear := float64(last.Odometer-first.Odometer) / days * 365
|
||||
resp.KmPerYear = &kmPerYear
|
||||
|
||||
years := milestoneDistance / kmPerYear
|
||||
resp.YearsPer100k = &years
|
||||
|
||||
eta := today().AddDate(0, 0, int(years*365)).Format(dateLayout)
|
||||
resp.Next100kEta = &eta
|
||||
}
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// Public, unauthenticated read-only endpoints for a car whose owner has
|
||||
// turned on sharing (POST /api/cars/{id}/share) — e.g. a QR code stuck in
|
||||
// the glovebox a mechanic can scan, or a link sent to a buyer. Deliberately
|
||||
// a separate, narrow surface (not just "the normal endpoints minus auth")
|
||||
// so there's no risk of it ever exposing more than intended: car identity,
|
||||
// service history, and its attachments — no reminders, no knowledgebase, no
|
||||
// owner info.
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"vlog/internal/models"
|
||||
)
|
||||
|
||||
func (h *Handlers) loadCarByShareToken(w http.ResponseWriter, r *http.Request) (*models.Car, bool) {
|
||||
token := r.PathValue("shareToken")
|
||||
if token == "" {
|
||||
writeError(w, http.StatusNotFound, "not found")
|
||||
return nil, false
|
||||
}
|
||||
|
||||
var car models.Car
|
||||
err := h.dbGet(r.Context(), &car, `SELECT * FROM cars WHERE share_token = ?`, token)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "not found")
|
||||
return nil, false
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load car")
|
||||
return nil, false
|
||||
}
|
||||
return &car, true
|
||||
}
|
||||
|
||||
// PublicCar returns just enough to identify the car — no owner/user info.
|
||||
func (h *Handlers) PublicCar(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadCarByShareToken(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"rego": car.Rego,
|
||||
"make": car.Make,
|
||||
"model": car.Model,
|
||||
"year": car.Year,
|
||||
"color": car.Color,
|
||||
"hasPhoto": car.PhotoS3Key != nil,
|
||||
})
|
||||
}
|
||||
|
||||
// PublicCarPhoto streams the car's photo — helps confirm it's the right car.
|
||||
func (h *Handlers) PublicCarPhoto(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadCarByShareToken(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if car.PhotoS3Key == nil {
|
||||
writeError(w, http.StatusNotFound, "no photo set")
|
||||
return
|
||||
}
|
||||
body, err := h.Storage.Get(r.Context(), *car.PhotoS3Key)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "photo not found")
|
||||
return
|
||||
}
|
||||
defer body.Close()
|
||||
w.Header().Set("Content-Type", contentTypeForExtension(*car.PhotoS3Key))
|
||||
io.Copy(w, body)
|
||||
}
|
||||
|
||||
// PublicServiceEntries returns one page of service history, including
|
||||
// attachments — read-only, no edit/delete affordance on this surface.
|
||||
func (h *Handlers) PublicServiceEntries(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadCarByShareToken(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, offset := parsePagination(r)
|
||||
|
||||
var entries []models.ServiceEntry
|
||||
err := h.dbSelect(r.Context(), &entries, `
|
||||
SELECT * FROM service_entries WHERE car_id = ?
|
||||
ORDER BY entry_date DESC, created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`, car.ID, limit+1, offset)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list service entries")
|
||||
return
|
||||
}
|
||||
|
||||
entries, hasMore := paginate(limit, entries)
|
||||
writeJSON(w, http.StatusOK, page[ServiceEntryWithFiles]{
|
||||
Items: h.attachFiles(r, entries),
|
||||
HasMore: hasMore,
|
||||
})
|
||||
}
|
||||
|
||||
// PublicFile streams a service-entry attachment, verified to belong to a
|
||||
// car reachable via this exact share token (not just "any file the caller
|
||||
// asks for").
|
||||
func (h *Handlers) PublicFile(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadCarByShareToken(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
fileID := r.PathValue("fileId")
|
||||
|
||||
var file models.ServiceEntryFile
|
||||
err := h.dbGet(r.Context(), &file, `
|
||||
SELECT sef.*
|
||||
FROM service_entry_files sef
|
||||
JOIN service_entries se ON se.id = sef.service_entry_id
|
||||
WHERE sef.id = ? AND se.car_id = ?
|
||||
`, fileID, car.ID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "file not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load file")
|
||||
return
|
||||
}
|
||||
|
||||
body, err := h.Storage.Get(r.Context(), file.S3Key)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "file not found in storage")
|
||||
return
|
||||
}
|
||||
defer body.Close()
|
||||
w.Header().Set("Content-Type", file.ContentType)
|
||||
io.Copy(w, body)
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"vlog/internal/models"
|
||||
)
|
||||
|
||||
// reminderWindowDays is how far ahead items are surfaced as "upcoming"
|
||||
// (overdue items always show regardless of age).
|
||||
const reminderWindowDays = 30
|
||||
|
||||
func today() time.Time {
|
||||
now := time.Now().UTC()
|
||||
return time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
// statusFor computes overdue/upcoming/future for a due date and/or due
|
||||
// odometer against today and the car's current odometer reading. Either
|
||||
// dueDate or dueOdometer (or both) may be nil.
|
||||
func statusFor(dueDate *time.Time, dueOdometer, currentOdometer *int, today time.Time) string {
|
||||
overdue, upcoming := false, false
|
||||
if dueDate != nil {
|
||||
if dueDate.Before(today) {
|
||||
overdue = true
|
||||
} else if !dueDate.After(today.AddDate(0, 0, reminderWindowDays)) {
|
||||
upcoming = true
|
||||
}
|
||||
}
|
||||
if dueOdometer != nil && currentOdometer != nil {
|
||||
if *currentOdometer >= *dueOdometer {
|
||||
overdue = true
|
||||
} else if *dueOdometer-*currentOdometer <= 1000 {
|
||||
upcoming = true
|
||||
}
|
||||
}
|
||||
if overdue {
|
||||
return "overdue"
|
||||
}
|
||||
if upcoming {
|
||||
return "upcoming"
|
||||
}
|
||||
return "future"
|
||||
}
|
||||
|
||||
// reminderToView converts a stored Reminder row into the unified view shape.
|
||||
func reminderToView(r models.Reminder, carRego string, currentOdometer *int, todayDate time.Time) models.ReminderView {
|
||||
status := "done"
|
||||
if r.CompletedAt == nil {
|
||||
status = statusFor(r.DueDate, r.DueOdometer, currentOdometer, todayDate)
|
||||
}
|
||||
id := r.ID
|
||||
return models.ReminderView{
|
||||
ID: &id, CarID: r.CarID, CarRego: carRego, ReminderType: r.ReminderType,
|
||||
Label: r.Label, DueDate: r.DueDate, DueOdometer: r.DueOdometer,
|
||||
Notes: r.Notes, CompletedAt: r.CompletedAt, Status: status,
|
||||
}
|
||||
}
|
||||
|
||||
// synthesizedReminders returns the rego/WoF/next-service-due items derived
|
||||
// from a car's own fields — never stored, always computed fresh, so there's
|
||||
// nothing to keep in sync when the car (or its service history) changes.
|
||||
// ID is left nil, which is how the frontend knows these aren't editable
|
||||
// directly — change the car's rego/WoF/service-interval fields instead.
|
||||
func synthesizedReminders(ctx context.Context, h *Handlers, car *models.Car, todayDate time.Time) []models.ReminderView {
|
||||
var views []models.ReminderView
|
||||
|
||||
if car.RegoExpiry != nil {
|
||||
views = append(views, models.ReminderView{
|
||||
CarID: car.ID, CarRego: car.Rego, ReminderType: "rego",
|
||||
DueDate: car.RegoExpiry, Status: statusFor(car.RegoExpiry, nil, nil, todayDate),
|
||||
})
|
||||
}
|
||||
if car.WofExpiry != nil {
|
||||
views = append(views, models.ReminderView{
|
||||
CarID: car.ID, CarRego: car.Rego, ReminderType: "wof",
|
||||
DueDate: car.WofExpiry, Status: statusFor(car.WofExpiry, nil, nil, todayDate),
|
||||
})
|
||||
}
|
||||
|
||||
if car.ServiceIntervalKM != nil || car.ServiceIntervalMonths != nil {
|
||||
var last models.ServiceEntry
|
||||
err := h.dbGet(ctx, &last, `
|
||||
SELECT * FROM service_entries
|
||||
WHERE car_id = ? AND is_service = ?
|
||||
ORDER BY entry_date DESC, created_at DESC
|
||||
LIMIT 1
|
||||
`, car.ID, true)
|
||||
if err == nil {
|
||||
var dueDate *time.Time
|
||||
if car.ServiceIntervalMonths != nil {
|
||||
d := last.EntryDate.AddDate(0, *car.ServiceIntervalMonths, 0)
|
||||
dueDate = &d
|
||||
}
|
||||
var dueOdometer *int
|
||||
if car.ServiceIntervalKM != nil && last.Odometer != nil {
|
||||
o := *last.Odometer + *car.ServiceIntervalKM
|
||||
dueOdometer = &o
|
||||
}
|
||||
if dueDate != nil || dueOdometer != nil {
|
||||
views = append(views, models.ReminderView{
|
||||
CarID: car.ID, CarRego: car.Rego, ReminderType: "service",
|
||||
DueDate: dueDate, DueOdometer: dueOdometer,
|
||||
Status: statusFor(dueDate, dueOdometer, car.Odometer, todayDate),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return views
|
||||
}
|
||||
|
||||
// sortReminderViews orders overdue-first, then by due date (nulls last),
|
||||
// then by due odometer (nulls last), with completed items always last.
|
||||
func sortReminderViews(views []models.ReminderView) {
|
||||
rank := func(v models.ReminderView) int {
|
||||
switch v.Status {
|
||||
case "overdue":
|
||||
return 0
|
||||
case "upcoming":
|
||||
return 1
|
||||
case "future":
|
||||
return 2
|
||||
default: // "done"
|
||||
return 3
|
||||
}
|
||||
}
|
||||
sort.SliceStable(views, func(i, j int) bool {
|
||||
a, b := views[i], views[j]
|
||||
if ra, rb := rank(a), rank(b); ra != rb {
|
||||
return ra < rb
|
||||
}
|
||||
switch {
|
||||
case a.DueDate == nil && b.DueDate != nil:
|
||||
return false
|
||||
case a.DueDate != nil && b.DueDate == nil:
|
||||
return true
|
||||
case a.DueDate != nil && b.DueDate != nil && !a.DueDate.Equal(*b.DueDate):
|
||||
return a.DueDate.Before(*b.DueDate)
|
||||
}
|
||||
switch {
|
||||
case a.DueOdometer == nil && b.DueOdometer != nil:
|
||||
return false
|
||||
case a.DueOdometer != nil && b.DueOdometer == nil:
|
||||
return true
|
||||
case a.DueOdometer != nil && b.DueOdometer != nil:
|
||||
return *a.DueOdometer < *b.DueOdometer
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"vlog/internal/auth"
|
||||
"vlog/internal/models"
|
||||
)
|
||||
|
||||
var validReminderTypes = map[string]bool{
|
||||
"service": true,
|
||||
"wheel_rotation": true,
|
||||
"alignment": true,
|
||||
"custom": true,
|
||||
}
|
||||
|
||||
// ListReminders returns a car's reminders — real ones (service/custom/etc,
|
||||
// completed ones hidden unless ?completed=1) plus rego/WoF/next-service-due
|
||||
// synthesized from the car's own fields, all in one unified list.
|
||||
func (h *Handlers) ListReminders(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
includeCompleted := r.URL.Query().Get("completed") == "1"
|
||||
todayDate := today()
|
||||
|
||||
query := `SELECT * FROM reminders WHERE car_id = ?`
|
||||
if !includeCompleted {
|
||||
query += ` AND completed_at IS NULL`
|
||||
}
|
||||
var reminders []models.Reminder
|
||||
if err := h.dbSelect(r.Context(), &reminders, query, car.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list reminders")
|
||||
return
|
||||
}
|
||||
|
||||
views := make([]models.ReminderView, 0, len(reminders))
|
||||
for _, rem := range reminders {
|
||||
views = append(views, reminderToView(rem, car.Rego, car.Odometer, todayDate))
|
||||
}
|
||||
views = append(views, synthesizedReminders(r.Context(), h, car, todayDate)...)
|
||||
sortReminderViews(views)
|
||||
|
||||
writeJSON(w, http.StatusOK, views)
|
||||
}
|
||||
|
||||
// CreateReminder adds a reminder to a car — either a built-in type (service,
|
||||
// wheel_rotation, alignment) or a fully custom one with its own label.
|
||||
func (h *Handlers) CreateReminder(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
in, ok := h.decodeReminderInput(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
dueDate, err := parseOptionalDate(in.DueDate)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid dueDate")
|
||||
return
|
||||
}
|
||||
|
||||
var reminder models.Reminder
|
||||
err = h.dbGet(r.Context(), &reminder, `
|
||||
INSERT INTO reminders (id, car_id, reminder_type, label, due_date, due_odometer, notes)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
RETURNING *
|
||||
`, uuid.New().String(), car.ID, in.ReminderType, in.Label, dueDate, in.DueOdometer, in.Notes)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to create reminder")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, reminder)
|
||||
}
|
||||
|
||||
// UpdateReminder edits a reminder's fields, or marks/unmarks it complete
|
||||
// (send completed: true/false in the body).
|
||||
func (h *Handlers) UpdateReminder(w http.ResponseWriter, r *http.Request) {
|
||||
reminder, ok := h.loadOwnedReminder(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
models.ReminderInput
|
||||
Completed *bool `json:"completed"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
// Marking complete/incomplete is a lightweight partial update that
|
||||
// doesn't require the other fields to be present.
|
||||
if body.Completed != nil && body.ReminderType == "" {
|
||||
var updated models.Reminder
|
||||
var err error
|
||||
if *body.Completed {
|
||||
err = h.dbGet(r.Context(), &updated, `
|
||||
UPDATE reminders SET completed_at = CURRENT_TIMESTAMP WHERE id = ? RETURNING *
|
||||
`, reminder.ID)
|
||||
} else {
|
||||
err = h.dbGet(r.Context(), &updated, `
|
||||
UPDATE reminders SET completed_at = NULL WHERE id = ? RETURNING *
|
||||
`, reminder.ID)
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to update reminder")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, updated)
|
||||
return
|
||||
}
|
||||
|
||||
if !validateReminderFields(w, body.ReminderInput) {
|
||||
return
|
||||
}
|
||||
dueDate, err := parseOptionalDate(body.DueDate)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid dueDate")
|
||||
return
|
||||
}
|
||||
|
||||
var updated models.Reminder
|
||||
err = h.dbGet(r.Context(), &updated, `
|
||||
UPDATE reminders
|
||||
SET reminder_type = ?, label = ?, due_date = ?, due_odometer = ?, notes = ?
|
||||
WHERE id = ?
|
||||
RETURNING *
|
||||
`, body.ReminderType, body.Label, dueDate, body.DueOdometer, body.Notes, reminder.ID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to update reminder")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, updated)
|
||||
}
|
||||
|
||||
// DeleteReminder removes a reminder.
|
||||
func (h *Handlers) DeleteReminder(w http.ResponseWriter, r *http.Request) {
|
||||
reminder, ok := h.loadOwnedReminder(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := h.dbExec(r.Context(), `DELETE FROM reminders WHERE id = ?`, reminder.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to delete reminder")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (h *Handlers) decodeReminderInput(w http.ResponseWriter, r *http.Request) (models.ReminderInput, bool) {
|
||||
var in models.ReminderInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return in, false
|
||||
}
|
||||
if !validateReminderFields(w, in) {
|
||||
return in, false
|
||||
}
|
||||
return in, true
|
||||
}
|
||||
|
||||
func validateReminderFields(w http.ResponseWriter, in models.ReminderInput) bool {
|
||||
if !validReminderTypes[in.ReminderType] {
|
||||
writeError(w, http.StatusBadRequest, "reminderType must be one of service, wheel_rotation, alignment, custom")
|
||||
return false
|
||||
}
|
||||
if in.ReminderType == "custom" && (in.Label == nil || *in.Label == "") {
|
||||
writeError(w, http.StatusBadRequest, "label is required for custom reminders")
|
||||
return false
|
||||
}
|
||||
if (in.DueDate == nil || *in.DueDate == "") && in.DueOdometer == nil {
|
||||
writeError(w, http.StatusBadRequest, "either dueDate or dueOdometer is required")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *Handlers) loadOwnedReminder(w http.ResponseWriter, r *http.Request) (*models.Reminder, bool) {
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
reminderID := r.PathValue("reminderId")
|
||||
|
||||
var reminder models.Reminder
|
||||
err := h.dbGet(r.Context(), &reminder, `
|
||||
SELECT rm.*
|
||||
FROM reminders rm
|
||||
JOIN cars c ON c.id = rm.car_id
|
||||
WHERE rm.id = ? AND c.user_id = ?
|
||||
`, reminderID, userID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "reminder not found")
|
||||
return nil, false
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load reminder")
|
||||
return nil, false
|
||||
}
|
||||
return &reminder, true
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"vlog/internal/auth"
|
||||
"vlog/internal/models"
|
||||
"vlog/internal/storage"
|
||||
)
|
||||
|
||||
// ServiceEntryWithFiles is the shape returned to the frontend: an entry plus
|
||||
// its attachments, so the timeline can render everything in one fetch.
|
||||
type ServiceEntryWithFiles struct {
|
||||
models.ServiceEntry
|
||||
Files []models.ServiceEntryFile `json:"files"`
|
||||
}
|
||||
|
||||
// ListServiceEntries returns one page of a car's service history, newest
|
||||
// first — the "timeline" is just this list rendered chronologically,
|
||||
// nothing fancier. Paginated (?limit=&offset=) so a long history doesn't
|
||||
// mean dumping thousands of rows into a single response/DOM.
|
||||
func (h *Handlers) ListServiceEntries(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, offset := parsePagination(r)
|
||||
|
||||
var entries []models.ServiceEntry
|
||||
err := h.dbSelect(r.Context(), &entries, `
|
||||
SELECT * FROM service_entries WHERE car_id = ?
|
||||
ORDER BY entry_date DESC, created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`, car.ID, limit+1, offset)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list service entries")
|
||||
return
|
||||
}
|
||||
|
||||
entries, hasMore := paginate(limit, entries)
|
||||
writeJSON(w, http.StatusOK, page[ServiceEntryWithFiles]{
|
||||
Items: h.attachFiles(r, entries),
|
||||
HasMore: hasMore,
|
||||
})
|
||||
}
|
||||
|
||||
// attachFiles batches a single query for all files belonging to entries,
|
||||
// rather than one query per entry.
|
||||
func (h *Handlers) attachFiles(r *http.Request, entries []models.ServiceEntry) []ServiceEntryWithFiles {
|
||||
result := make([]ServiceEntryWithFiles, len(entries))
|
||||
ids := make([]string, len(entries))
|
||||
for i, e := range entries {
|
||||
result[i] = ServiceEntryWithFiles{ServiceEntry: e, Files: []models.ServiceEntryFile{}}
|
||||
ids[i] = e.ID
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return result
|
||||
}
|
||||
|
||||
// sqlx.In expands the slice into the right number of "?" placeholders;
|
||||
// Rebind then adapts those for whichever driver is actually connected.
|
||||
query, args, err := sqlx.In(`SELECT * FROM service_entry_files WHERE service_entry_id IN (?) ORDER BY created_at`, ids)
|
||||
if err != nil {
|
||||
return result // best-effort: entries without file metadata beats a 500
|
||||
}
|
||||
|
||||
var files []models.ServiceEntryFile
|
||||
if err := h.dbSelect(r.Context(), &files, query, args...); err != nil {
|
||||
return result
|
||||
}
|
||||
|
||||
byEntry := make(map[string][]models.ServiceEntryFile, len(ids))
|
||||
for _, f := range files {
|
||||
byEntry[f.ServiceEntryID] = append(byEntry[f.ServiceEntryID], f)
|
||||
}
|
||||
for i := range result {
|
||||
if fs, ok := byEntry[result[i].ID]; ok {
|
||||
result[i].Files = fs
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// CreateServiceEntry adds a new history entry to a car.
|
||||
func (h *Handlers) CreateServiceEntry(w http.ResponseWriter, r *http.Request) {
|
||||
car, ok := h.loadOwnedCar(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var in models.ServiceEntryInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if in.EntryType == "" {
|
||||
writeError(w, http.StatusBadRequest, "entryType is required")
|
||||
return
|
||||
}
|
||||
entryDate, err := time.Parse(dateLayout, in.EntryDate)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid entryDate")
|
||||
return
|
||||
}
|
||||
|
||||
var entry models.ServiceEntry
|
||||
err = h.dbGet(r.Context(), &entry, `
|
||||
INSERT INTO service_entries (id, car_id, entry_date, entry_type, description, performed_at, odometer, is_service)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
RETURNING *
|
||||
`, uuid.New().String(), car.ID, entryDate, in.EntryType, in.Description, in.PerformedAt, in.Odometer, in.IsService)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to create service entry")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, ServiceEntryWithFiles{ServiceEntry: entry, Files: []models.ServiceEntryFile{}})
|
||||
}
|
||||
|
||||
// GetServiceEntry returns one entry with its attachments.
|
||||
func (h *Handlers) GetServiceEntry(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := h.loadOwnedServiceEntry(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
result := h.attachFiles(r, []models.ServiceEntry{*entry})
|
||||
writeJSON(w, http.StatusOK, result[0])
|
||||
}
|
||||
|
||||
// UpdateServiceEntry edits an entry's fields.
|
||||
func (h *Handlers) UpdateServiceEntry(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := h.loadOwnedServiceEntry(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var in models.ServiceEntryInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if in.EntryType == "" {
|
||||
writeError(w, http.StatusBadRequest, "entryType is required")
|
||||
return
|
||||
}
|
||||
entryDate, err := time.Parse(dateLayout, in.EntryDate)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid entryDate")
|
||||
return
|
||||
}
|
||||
|
||||
var updated models.ServiceEntry
|
||||
err = h.dbGet(r.Context(), &updated, `
|
||||
UPDATE service_entries
|
||||
SET entry_date = ?, entry_type = ?, description = ?, performed_at = ?, odometer = ?, is_service = ?
|
||||
WHERE id = ?
|
||||
RETURNING *
|
||||
`, entryDate, in.EntryType, in.Description, in.PerformedAt, in.Odometer, in.IsService, entry.ID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to update service entry")
|
||||
return
|
||||
}
|
||||
|
||||
result := h.attachFiles(r, []models.ServiceEntry{updated})
|
||||
writeJSON(w, http.StatusOK, result[0])
|
||||
}
|
||||
|
||||
// DeleteServiceEntry removes an entry (DB cascades to its files; storage
|
||||
// cleanup of each attached file is best-effort).
|
||||
func (h *Handlers) DeleteServiceEntry(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := h.loadOwnedServiceEntry(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var files []models.ServiceEntryFile
|
||||
_ = h.dbSelect(r.Context(), &files, `SELECT * FROM service_entry_files WHERE service_entry_id = ?`, entry.ID)
|
||||
|
||||
if _, err := h.dbExec(r.Context(), `DELETE FROM service_entries WHERE id = ?`, entry.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to delete service entry")
|
||||
return
|
||||
}
|
||||
|
||||
for _, f := range files {
|
||||
_ = h.Storage.Delete(r.Context(), f.S3Key)
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
// UploadServiceEntryFile attaches one PNG/PDF file to an entry. Call once
|
||||
// per file for multi-file uploads.
|
||||
func (h *Handlers) UploadServiceEntryFile(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := h.loadOwnedServiceEntry(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
file, contentType, ok := parseUploadedFile(w, r, 15<<20, storage.AllowedAttachmentTypes)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
_, header, _ := r.FormFile("file")
|
||||
originalName := "attachment"
|
||||
if header != nil {
|
||||
originalName = sanitizeFileName(header.Filename)
|
||||
}
|
||||
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
key := fmt.Sprintf("users/%s/cars/%s/service/%s/%s-%s",
|
||||
userID, entry.CarID, entry.ID, randomID(), originalName)
|
||||
|
||||
var sizeBytes int64
|
||||
if header != nil {
|
||||
sizeBytes = header.Size
|
||||
}
|
||||
|
||||
if err := h.Storage.Upload(r.Context(), key, contentType, file); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to upload file")
|
||||
return
|
||||
}
|
||||
|
||||
var saved models.ServiceEntryFile
|
||||
err := h.dbGet(r.Context(), &saved, `
|
||||
INSERT INTO service_entry_files (id, service_entry_id, s3_key, file_name, content_type, size_bytes)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
RETURNING *
|
||||
`, uuid.New().String(), entry.ID, key, originalName, contentType, sizeBytes)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to save file reference")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, saved)
|
||||
}
|
||||
|
||||
func (h *Handlers) loadOwnedServiceEntry(w http.ResponseWriter, r *http.Request) (*models.ServiceEntry, bool) {
|
||||
userID, _ := auth.UserIDFromContext(r.Context())
|
||||
entryID := r.PathValue("entryId")
|
||||
|
||||
var entry models.ServiceEntry
|
||||
err := h.dbGet(r.Context(), &entry, `
|
||||
SELECT se.*
|
||||
FROM service_entries se
|
||||
JOIN cars c ON c.id = se.car_id
|
||||
WHERE se.id = ? AND c.user_id = ?
|
||||
`, entryID, userID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeError(w, http.StatusNotFound, "service entry not found")
|
||||
return nil, false
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load service entry")
|
||||
return nil, false
|
||||
}
|
||||
return &entry, true
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
// Package models holds the plain structs shared between the db layer and
|
||||
// the HTTP handlers. Field tags do double duty: `db` for sqlx scanning,
|
||||
// `json` for API responses.
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type User struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
OIDCSub string `db:"oidc_sub" json:"-"`
|
||||
Email string `db:"email" json:"email"`
|
||||
Name *string `db:"name" json:"name"`
|
||||
CreatedAt time.Time `db:"created_at" json:"createdAt"`
|
||||
}
|
||||
|
||||
type Car struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
UserID string `db:"user_id" json:"userId"`
|
||||
Rego string `db:"rego" json:"rego"`
|
||||
Make *string `db:"make" json:"make"`
|
||||
Model *string `db:"model" json:"model"`
|
||||
Year *int `db:"year" json:"year"`
|
||||
Color *string `db:"color" json:"color"`
|
||||
Odometer *int `db:"odometer" json:"odometer"`
|
||||
RegoExpiry *time.Time `db:"rego_expiry" json:"regoExpiry"`
|
||||
WofExpiry *time.Time `db:"wof_expiry" json:"wofExpiry"`
|
||||
PhotoS3Key *string `db:"photo_s3_key" json:"-"`
|
||||
HasPhoto bool `db:"-" json:"hasPhoto"`
|
||||
ShareToken *string `db:"share_token" json:"shareToken"`
|
||||
ServiceIntervalKM *int `db:"service_interval_km" json:"serviceIntervalKm"`
|
||||
ServiceIntervalMonths *int `db:"service_interval_months" json:"serviceIntervalMonths"`
|
||||
CreatedAt time.Time `db:"created_at" json:"createdAt"`
|
||||
UpdatedAt time.Time `db:"updated_at" json:"updatedAt"`
|
||||
}
|
||||
|
||||
// CarInput is the JSON body accepted for car create/update requests. Share
|
||||
// links are managed separately (POST/DELETE .../share) since they're not
|
||||
// really "car info" the way these fields are.
|
||||
type CarInput struct {
|
||||
Rego string `json:"rego"`
|
||||
Make *string `json:"make"`
|
||||
Model *string `json:"model"`
|
||||
Year *int `json:"year"`
|
||||
Color *string `json:"color"`
|
||||
Odometer *int `json:"odometer"`
|
||||
RegoExpiry *string `json:"regoExpiry"` // "YYYY-MM-DD" or null
|
||||
WofExpiry *string `json:"wofExpiry"`
|
||||
ServiceIntervalKM *int `json:"serviceIntervalKm"`
|
||||
ServiceIntervalMonths *int `json:"serviceIntervalMonths"`
|
||||
}
|
||||
|
||||
type ServiceEntry struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
CarID string `db:"car_id" json:"carId"`
|
||||
EntryDate time.Time `db:"entry_date" json:"entryDate"`
|
||||
EntryType string `db:"entry_type" json:"entryType"`
|
||||
Description *string `db:"description" json:"description"`
|
||||
PerformedAt *string `db:"performed_at" json:"performedAt"`
|
||||
Odometer *int `db:"odometer" json:"odometer"`
|
||||
// IsService marks this entry as "a full service" — the baseline the
|
||||
// synthesized next-service-due reminder counts forward from, using the
|
||||
// car's configured ServiceIntervalKM/ServiceIntervalMonths.
|
||||
IsService bool `db:"is_service" json:"isService"`
|
||||
CreatedAt time.Time `db:"created_at" json:"createdAt"`
|
||||
}
|
||||
|
||||
type ServiceEntryInput struct {
|
||||
EntryDate string `json:"entryDate"`
|
||||
EntryType string `json:"entryType"`
|
||||
Description *string `json:"description"`
|
||||
PerformedAt *string `json:"performedAt"`
|
||||
Odometer *int `json:"odometer"`
|
||||
IsService bool `json:"isService"`
|
||||
}
|
||||
|
||||
type ServiceEntryFile struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
ServiceEntryID string `db:"service_entry_id" json:"serviceEntryId"`
|
||||
S3Key string `db:"s3_key" json:"-"`
|
||||
FileName string `db:"file_name" json:"fileName"`
|
||||
ContentType string `db:"content_type" json:"contentType"`
|
||||
SizeBytes int64 `db:"size_bytes" json:"sizeBytes"`
|
||||
CreatedAt time.Time `db:"created_at" json:"createdAt"`
|
||||
}
|
||||
|
||||
type Reminder struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
CarID string `db:"car_id" json:"carId"`
|
||||
ReminderType string `db:"reminder_type" json:"reminderType"`
|
||||
Label *string `db:"label" json:"label"`
|
||||
DueDate *time.Time `db:"due_date" json:"dueDate"`
|
||||
DueOdometer *int `db:"due_odometer" json:"dueOdometer"`
|
||||
Notes *string `db:"notes" json:"notes"`
|
||||
CompletedAt *time.Time `db:"completed_at" json:"completedAt"`
|
||||
CreatedAt time.Time `db:"created_at" json:"createdAt"`
|
||||
}
|
||||
|
||||
type ReminderInput struct {
|
||||
ReminderType string `json:"reminderType"`
|
||||
Label *string `json:"label"`
|
||||
DueDate *string `json:"dueDate"`
|
||||
DueOdometer *int `json:"dueOdometer"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
type KnowledgeEntry struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
CarID string `db:"car_id" json:"carId"`
|
||||
Title string `db:"title" json:"title"`
|
||||
Body string `db:"body" json:"body"`
|
||||
CreatedAt time.Time `db:"created_at" json:"createdAt"`
|
||||
UpdatedAt time.Time `db:"updated_at" json:"updatedAt"`
|
||||
}
|
||||
|
||||
type KnowledgeEntryInput struct {
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
}
|
||||
|
||||
// ReminderView is the unified shape for every "reminder-like" row shown to
|
||||
// the user — real stored Reminder rows, plus rego/WoF expiry and next-
|
||||
// service-due items synthesized on the fly from the car's own fields (no
|
||||
// separate stored row to keep in sync). ID is nil for synthesized items,
|
||||
// which is how the frontend knows there's nothing to edit/delete/complete —
|
||||
// to change those, edit the car's rego/WoF/service-interval fields instead.
|
||||
// Used by both GET /api/dashboard (across all cars) and the car-scoped
|
||||
// GET /api/cars/{id}/reminders.
|
||||
type ReminderView struct {
|
||||
ID *string `db:"id" json:"id"`
|
||||
CarID string `db:"car_id" json:"carId"`
|
||||
CarRego string `db:"car_rego" json:"carRego"`
|
||||
ReminderType string `db:"reminder_type" json:"reminderType"` // 'service' | 'wheel_rotation' | 'alignment' | 'custom' | 'rego' | 'wof'
|
||||
Label *string `db:"label" json:"label"`
|
||||
DueDate *time.Time `db:"due_date" json:"dueDate"`
|
||||
DueOdometer *int `db:"due_odometer" json:"dueOdometer"`
|
||||
Notes *string `db:"notes" json:"notes"`
|
||||
CompletedAt *time.Time `db:"completed_at" json:"completedAt"`
|
||||
Status string `db:"status" json:"status"` // 'overdue' | 'upcoming' | 'future' | 'done'
|
||||
}
|
||||
|
||||
type FuelEntry struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
CarID string `db:"car_id" json:"carId"`
|
||||
EntryDate time.Time `db:"entry_date" json:"entryDate"`
|
||||
Litres float64 `db:"litres" json:"litres"`
|
||||
Cost float64 `db:"cost" json:"cost"`
|
||||
Odometer *int `db:"odometer" json:"odometer"`
|
||||
Location *string `db:"location" json:"location"`
|
||||
Notes *string `db:"notes" json:"notes"`
|
||||
CreatedAt time.Time `db:"created_at" json:"createdAt"`
|
||||
}
|
||||
|
||||
type FuelEntryInput struct {
|
||||
EntryDate string `json:"entryDate"`
|
||||
Litres float64 `json:"litres"`
|
||||
Cost float64 `json:"cost"`
|
||||
Odometer *int `json:"odometer"`
|
||||
Location *string `json:"location"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// LocalStorage writes uploads to a directory on disk instead of S3 — for
|
||||
// STORAGE_DRIVER=local, so the app can be tested without a real S3 bucket.
|
||||
// Keys are the same "users/{id}/cars/{id}/..." paths used for S3; they're
|
||||
// just joined onto basePath instead of being S3 object keys.
|
||||
type LocalStorage struct {
|
||||
basePath string
|
||||
}
|
||||
|
||||
func NewLocal(basePath string) (*LocalStorage, error) {
|
||||
if err := os.MkdirAll(basePath, 0o755); err != nil {
|
||||
return nil, fmt.Errorf("create local storage dir: %w", err)
|
||||
}
|
||||
return &LocalStorage{basePath: basePath}, nil
|
||||
}
|
||||
|
||||
func (l *LocalStorage) Upload(ctx context.Context, key, contentType string, r io.Reader) error {
|
||||
path, err := l.resolve(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return fmt.Errorf("create dir for %s: %w", key, err)
|
||||
}
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create %s: %w", key, err)
|
||||
}
|
||||
defer f.Close()
|
||||
if _, err := io.Copy(f, r); err != nil {
|
||||
return fmt.Errorf("write %s: %w", key, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *LocalStorage) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
path, err := l.resolve(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open %s: %w", key, err)
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func (l *LocalStorage) Delete(ctx context.Context, key string) error {
|
||||
path, err := l.resolve(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return fmt.Errorf("delete %s: %w", key, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// resolve joins key onto basePath, rejecting anything that would escape it.
|
||||
// Keys are always built internally from UUIDs + sanitized filenames, so
|
||||
// this is defense in depth rather than a load-bearing check.
|
||||
func (l *LocalStorage) resolve(key string) (string, error) {
|
||||
if strings.Contains(key, "..") {
|
||||
return "", fmt.Errorf("invalid storage key %q", key)
|
||||
}
|
||||
return filepath.Join(l.basePath, filepath.FromSlash(key)), nil
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// Package storage wraps S3 upload/download/delete plus the content-type
|
||||
// sniffing used to validate uploaded photos and PNG/PDF attachments. The
|
||||
// bucket is treated as fully private — everything is proxied through the Go
|
||||
// backend, so there are no presigned URLs or bucket CORS rules to manage.
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/config"
|
||||
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
)
|
||||
|
||||
// Storage is what handlers depend on — satisfied by S3Storage (production)
|
||||
// and LocalStorage (STORAGE_DRIVER=local, for testing without a real S3
|
||||
// bucket). Handlers never need to know which one they're talking to.
|
||||
type Storage interface {
|
||||
Upload(ctx context.Context, key, contentType string, r io.Reader) error
|
||||
Get(ctx context.Context, key string) (io.ReadCloser, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
}
|
||||
|
||||
type S3Storage struct {
|
||||
client *s3.Client
|
||||
bucket string
|
||||
}
|
||||
|
||||
func NewS3(ctx context.Context, region, bucket string) (*S3Storage, error) {
|
||||
cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(region))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load aws config: %w", err)
|
||||
}
|
||||
return &S3Storage{
|
||||
client: s3.NewFromConfig(cfg),
|
||||
bucket: bucket,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Upload streams r to S3 under key with the given content type. Uses the
|
||||
// managed uploader so large files aren't buffered fully in memory.
|
||||
func (s *S3Storage) Upload(ctx context.Context, key, contentType string, r io.Reader) error {
|
||||
uploader := manager.NewUploader(s.client)
|
||||
_, err := uploader.Upload(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
Body: r,
|
||||
ContentType: aws.String(contentType),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("upload %s: %w", key, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get returns a stream of the object's body. Caller must Close it.
|
||||
func (s *S3Storage) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
out, err := s.client.GetObject(ctx, &s3.GetObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get %s: %w", key, err)
|
||||
}
|
||||
return out.Body, nil
|
||||
}
|
||||
|
||||
// Delete removes the object. Callers should treat failures as non-fatal
|
||||
// (log and move on) since the DB row is the source of truth.
|
||||
func (s *S3Storage) Delete(ctx context.Context, key string) error {
|
||||
_, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete %s: %w", key, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DetectAndValidate sniffs the real content type of an uploaded file from
|
||||
// its first bytes (never trusts the client-declared type/extension) and
|
||||
// checks it against the allowed set. Returns the sniffed content type, or an
|
||||
// error if it's not in allowed. The file's read position is reset to the
|
||||
// start afterwards so it can still be uploaded.
|
||||
func DetectAndValidate(file multipart.File, allowed map[string]bool) (string, error) {
|
||||
buf := make([]byte, 512)
|
||||
n, err := file.Read(buf)
|
||||
if err != nil && err != io.EOF {
|
||||
return "", fmt.Errorf("read file header: %w", err)
|
||||
}
|
||||
contentType := http.DetectContentType(buf[:n])
|
||||
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return "", fmt.Errorf("reset file position: %w", err)
|
||||
}
|
||||
|
||||
if !allowed[contentType] {
|
||||
return "", fmt.Errorf("unsupported file type %q", contentType)
|
||||
}
|
||||
return contentType, nil
|
||||
}
|
||||
|
||||
var (
|
||||
AllowedPhotoTypes = map[string]bool{
|
||||
"image/png": true,
|
||||
"image/jpeg": true,
|
||||
}
|
||||
AllowedAttachmentTypes = map[string]bool{
|
||||
"image/png": true,
|
||||
"application/pdf": true,
|
||||
}
|
||||
)
|
||||
Reference in new issue
Block a user