Initial commit
This commit is contained in:
commit
b6014c6ffc
47 files changed
+4329
No files matched your search
@@ -0,0 +1,27 @@
|
|||||||
|
# Ships as one image: the Go binary embeds the built Svelte SPA, so this is
|
||||||
|
# the only container the app itself needs (Postgres and the OIDC provider
|
||||||
|
# already run elsewhere).
|
||||||
|
|
||||||
|
# --- Stage 1: build the frontend ---
|
||||||
|
FROM node:20-alpine AS frontend-build
|
||||||
|
WORKDIR /frontend
|
||||||
|
COPY frontend/package.json frontend/package-lock.json* ./
|
||||||
|
RUN npm install
|
||||||
|
COPY frontend/ ./
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# --- Stage 2: build the Go binary, embedding the frontend build ---
|
||||||
|
FROM golang:1.25-alpine AS backend-build
|
||||||
|
WORKDIR /backend
|
||||||
|
COPY backend/go.mod backend/go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
COPY backend/ ./
|
||||||
|
COPY --from=frontend-build /frontend/dist/. ./cmd/server/web/
|
||||||
|
RUN CGO_ENABLED=0 go build -o /vlog ./cmd/server
|
||||||
|
|
||||||
|
# --- Stage 3: minimal runtime image ---
|
||||||
|
FROM alpine:3.20
|
||||||
|
RUN apk add --no-cache ca-certificates
|
||||||
|
COPY --from=backend-build /vlog /vlog
|
||||||
|
EXPOSE 8080
|
||||||
|
ENTRYPOINT ["/vlog"]
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "embed"
|
||||||
|
|
||||||
|
//go:embed all:web
|
||||||
|
var frontendFS embed.FS
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
// Throwaway local preview server — NOT part of the real app, never
|
||||||
|
// committed. Bypasses OIDC entirely (no live provider needed for a visual
|
||||||
|
// check) by minting a session JWT directly and seeding just a user (no car
|
||||||
|
// — this drives the FULL real UI flow end-to-end, same as a real user
|
||||||
|
// would, to catch anything a direct-API test wouldn't).
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"vlog/internal/auth"
|
||||||
|
"vlog/internal/db"
|
||||||
|
"vlog/internal/handlers"
|
||||||
|
"vlog/internal/storage"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
dbPath := "/tmp/vlog-preview/preview.db"
|
||||||
|
os.MkdirAll("/tmp/vlog-preview/uploads", 0o755)
|
||||||
|
os.Remove(dbPath)
|
||||||
|
|
||||||
|
database, err := db.Connect("sqlite", dbPath)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("db: %v", err)
|
||||||
|
}
|
||||||
|
defer database.Close()
|
||||||
|
|
||||||
|
store, err := storage.NewLocal("/tmp/vlog-preview/uploads")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("storage: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
h := handlers.New(database, store, nil, "preview-secret", false)
|
||||||
|
|
||||||
|
userID := uuid.New().String()
|
||||||
|
database.Exec(`INSERT INTO users (id, oidc_sub, email, name) VALUES (?, ?, ?, ?)`,
|
||||||
|
userID, "preview-sub", "[email protected]", "Demo User")
|
||||||
|
|
||||||
|
token, err := auth.MintSessionJWT("preview-secret", userID, "[email protected]")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("mint jwt: %v", err)
|
||||||
|
}
|
||||||
|
fmt.Println("SESSION_TOKEN=" + token)
|
||||||
|
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
protected := http.NewServeMux()
|
||||||
|
protected.HandleFunc("GET /api/me", h.Me)
|
||||||
|
|
||||||
|
protected.HandleFunc("GET /api/cars", h.ListCars)
|
||||||
|
protected.HandleFunc("POST /api/cars", h.CreateCar)
|
||||||
|
protected.HandleFunc("GET /api/cars/{carId}", h.GetCar)
|
||||||
|
protected.HandleFunc("PUT /api/cars/{carId}", h.UpdateCar)
|
||||||
|
protected.HandleFunc("DELETE /api/cars/{carId}", h.DeleteCar)
|
||||||
|
protected.HandleFunc("POST /api/cars/{carId}/photo", h.UploadCarPhoto)
|
||||||
|
protected.HandleFunc("GET /api/cars/{carId}/photo", h.GetCarPhoto)
|
||||||
|
protected.HandleFunc("PATCH /api/cars/{carId}/odometer", h.UpdateOdometer)
|
||||||
|
protected.HandleFunc("POST /api/cars/{carId}/share", h.GenerateShareLink)
|
||||||
|
protected.HandleFunc("DELETE /api/cars/{carId}/share", h.RevokeShareLink)
|
||||||
|
protected.HandleFunc("GET /api/cars/{carId}/mileage", h.Mileage)
|
||||||
|
|
||||||
|
protected.HandleFunc("GET /api/cars/{carId}/service-entries", h.ListServiceEntries)
|
||||||
|
protected.HandleFunc("POST /api/cars/{carId}/service-entries", h.CreateServiceEntry)
|
||||||
|
protected.HandleFunc("GET /api/service-entries/{entryId}", h.GetServiceEntry)
|
||||||
|
protected.HandleFunc("PUT /api/service-entries/{entryId}", h.UpdateServiceEntry)
|
||||||
|
protected.HandleFunc("DELETE /api/service-entries/{entryId}", h.DeleteServiceEntry)
|
||||||
|
protected.HandleFunc("POST /api/service-entries/{entryId}/files", h.UploadServiceEntryFile)
|
||||||
|
protected.HandleFunc("GET /api/files/{fileId}", h.GetFile)
|
||||||
|
protected.HandleFunc("DELETE /api/files/{fileId}", h.DeleteFile)
|
||||||
|
|
||||||
|
protected.HandleFunc("GET /api/cars/{carId}/reminders", h.ListReminders)
|
||||||
|
protected.HandleFunc("POST /api/cars/{carId}/reminders", h.CreateReminder)
|
||||||
|
protected.HandleFunc("PUT /api/reminders/{reminderId}", h.UpdateReminder)
|
||||||
|
protected.HandleFunc("DELETE /api/reminders/{reminderId}", h.DeleteReminder)
|
||||||
|
|
||||||
|
protected.HandleFunc("GET /api/cars/{carId}/knowledge", h.ListKnowledge)
|
||||||
|
protected.HandleFunc("POST /api/cars/{carId}/knowledge", h.CreateKnowledge)
|
||||||
|
protected.HandleFunc("PUT /api/knowledge/{knowledgeId}", h.UpdateKnowledge)
|
||||||
|
protected.HandleFunc("DELETE /api/knowledge/{knowledgeId}", h.DeleteKnowledge)
|
||||||
|
|
||||||
|
protected.HandleFunc("GET /api/cars/{carId}/fuel-entries", h.ListFuelEntries)
|
||||||
|
protected.HandleFunc("POST /api/cars/{carId}/fuel-entries", h.CreateFuelEntry)
|
||||||
|
protected.HandleFunc("PUT /api/fuel-entries/{entryId}", h.UpdateFuelEntry)
|
||||||
|
protected.HandleFunc("DELETE /api/fuel-entries/{entryId}", h.DeleteFuelEntry)
|
||||||
|
|
||||||
|
protected.HandleFunc("GET /api/dashboard", h.Dashboard)
|
||||||
|
mux.Handle("/api/", auth.RequireAuth(h.JWTSecret)(protected))
|
||||||
|
|
||||||
|
staticFS, _ := fs.Sub(frontendFS, "web")
|
||||||
|
mux.Handle("/", http.FileServer(http.FS(staticFS)))
|
||||||
|
|
||||||
|
log.Println("preview server on :8099")
|
||||||
|
log.Fatal(http.ListenAndServe(":8099", mux))
|
||||||
|
}
|
||||||
Whitespace-only changes.
@@ -0,0 +1,11 @@
|
|||||||
|
var ks=Object.defineProperty;var da=e=>{throw TypeError(e)};var Ss=(e,t,r)=>t in e?ks(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ne=(e,t,r)=>Ss(e,typeof t!="symbol"?t+"":t,r),$n=(e,t,r)=>t.has(e)||da("Cannot "+r);var E=(e,t,r)=>($n(e,t,"read from private field"),r?r.call(e):t.get(e)),re=(e,t,r)=>t.has(e)?da("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),ae=(e,t,r,n)=>($n(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r),ge=(e,t,r)=>($n(e,t,"access private method"),r);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const o of a.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function r(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function n(i){if(i.ep)return;i.ep=!0;const a=r(i);fetch(i.href,a)}})();const go=!1;var Wi=Array.isArray,Cs=Array.prototype.indexOf,Un=Array.prototype.includes,Qn=Array.from,po=Object.defineProperty,Xt=Object.getOwnPropertyDescriptor,mo=Object.getOwnPropertyDescriptors,As=Object.prototype,Ts=Array.prototype,Qi=Object.getPrototypeOf,va=Object.isExtensible;function rn(e){return typeof e=="function"}const $t=()=>{};function Is(e){return e()}function Mi(e){for(var t=0;t<e.length;t++)e[t]()}function _o(){var e,t,r=new Promise((n,i)=>{e=n,t=i});return{promise:r,resolve:e,reject:t}}const qe=2,Ur=4,Cn=8,bo=1<<24,mt=16,ft=32,jt=64,Pi=128,ct=512,Fe=1024,Le=2048,bt=4096,Ye=8192,nt=16384,Wr=32768,ha=1<<25,tr=65536,Hn=1<<17,Ms=1<<18,Qr=1<<19,yo=1<<20,kt=1<<25,pr=65536,zn=1<<21,Nr=1<<22,er=1<<23,Ft=Symbol("$state"),wo=Symbol("legacy props"),Ps=Symbol(""),Dn=Symbol("attributes"),Ri=Symbol("class"),Rs=Symbol("style"),on=Symbol("text"),Bn=Symbol("form reset"),An=new class extends Error{constructor(){super(...arguments);Ne(this,"name","StaleReactionError");Ne(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}};var fo;const Ns=!!((fo=globalThis.document)!=null&&fo.contentType)&&globalThis.document.contentType.includes("xml");function Ls(e){throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function Ds(){throw new Error("https://svelte.dev/e/async_derived_orphan")}function Bs(e,t,r){throw new Error("https://svelte.dev/e/each_key_duplicate")}function Fs(e){throw new Error("https://svelte.dev/e/effect_in_teardown")}function Os(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function qs(e){throw new Error("https://svelte.dev/e/effect_orphan")}function js(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function Us(e){throw new Error("https://svelte.dev/e/props_invalid_value")}function Hs(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function zs(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function Vs(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function Ks(){throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}const Ys=1,Gs=2,xo=4,Js=8,Ws=16,Qs=1,Zs=2,Xs=4,$s=8,el=16,tl=1,rl=2,De=Symbol("uninitialized"),nl="http://www.w3.org/1999/xhtml";function il(){console.warn("https://svelte.dev/e/derived_inert")}function al(){console.warn("https://svelte.dev/e/select_multiple_invalid_value")}function ol(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}function Eo(e){return e===this.v}function ko(e,t){return e!=e?t==t:e!==t||e!==null&&typeof e=="object"||typeof e=="function"}function So(e){return!ko(e,this.v)}let Zr=!1,sl=!1;function ll(){Zr=!0}let Te=null;function Hr(e){Te=e}function Se(e,t=!1,r){Te={p:Te,i:!1,c:null,e:null,s:e,x:null,r:ve,l:Zr&&!t?{s:null,u:null,$:[]}:null}}function Ce(e){var t=Te,r=t.e;if(r!==null){t.e=null;for(var n of r)Go(n)}return t.i=!0,Te=t.p,{}}function Tn(){return!Zr||Te!==null&&Te.l===null}let ar=[];function Co(){var e=ar;ar=[],Mi(e)}function St(e){if(ar.length===0&&!dn){var t=ar;queueMicrotask(()=>{t===ar&&Co()})}ar.push(e)}function ul(){for(;ar.length>0;)Co()}function Ao(e){var t=ve;if(t===null)return de.f|=er,e;if((t.f&Wr)===0&&(t.f&Ur)===0)throw e;Qt(e,t)}function Qt(e,t){if(!(t!==null&&(t.f&nt)!==0)){for(;t!==null;){if((t.f&Pi)!==0){if((t.f&Wr)===0)throw e;try{t.b.error(e);return}catch(r){e=r}}t=t.parent}throw e}}const cl=-7169;function Me(e,t){e.f=e.f&cl|t}function Zi(e){(e.f&ct)!==0||e.deps===null?Me(e,Fe):Me(e,bt)}function To(e){if(e!==null)for(const t of e)(t.f&qe)===0||(t.f&pr)===0||(t.f^=pr,To(t.deps))}function Io(e,t,r){(e.f&Le)!==0?t.add(e):(e.f&bt)!==0&&r.add(e),To(e.deps),Me(e,Fe)}function Mo(e,t,r){if(e==null)return t(void 0),$t;const n=ir(()=>e.sLine truncated
|
||||||
|
${l(r)==="overdue"?"bg-red-600 text-white":"bg-amber-500 text-white"}`),z(D,l(r)==="overdue"?"Overdue":"Due soon")}),L(p,x)};V(u,p=>{l(r)&&p(c)})}var f=_(i,2),m=h(f),d=h(m);ca(d,{get rego(){return t.car.rego},size:"sm"});var g=_(d,2);{var b=p=>{var x=Xu(),D=h(x);U(()=>z(D,`${t.car.year??""??""} ${t.car.make??""??""}`)),L(p,x)};V(g,p=>{(t.car.year||t.car.make)&&p(b)})}var C=_(m,2);{var k=p=>{var x=$u(),D=h(x);U(()=>z(D,t.car.model)),L(p,x)};V(C,p=>{t.car.model&&p(k)})}var S=_(C,2),I=h(S),M=h(I),R=_(I,2),A=h(R);U((p,x)=>{Ge(n,"href",`#/cars/${t.car.id??""}`),O(n,1,`${Xn} group block overflow-hidden transition-all hover:-translate-y-0.5 hover:shadow-lg`),z(M,`Rego: ${p??""}`),z(A,`WoF: ${x??""}`)},[()=>It(t.car.regoExpiry),()=>It(t.car.wofExpiry)]),L(e,n),Ce()}var rc=q('<div class="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto p-4 sm:items-center sm:p-6"><button type="button" aria-label="Close" class="fixed inset-0 bg-stone-900/60 backdrop-blur-sm"></button> <div><div class="flex items-center justify-between border-b border-stone-100 px-5 py-4"><h3 class="text-base font-semibold text-stone-900"> </h3> <button type="button" aria-label="Close" class="rounded-md p-1 text-stone-400 hover:bg-stone-100 hover:text-stone-600"><!></button></div> <div class="max-h-[75vh] overflow-y-auto p-5"><!></div></div></div>');function yt(e,t){Se(t,!0);let r=Be(t,"wide",3,!1);function n(b){var C;b.key==="Escape"&&((C=t.onClose)==null||C.call(t))}var i=rc();br("keydown",Hi,n);var a=h(i),o=_(a,2),s=h(o),u=h(s),c=h(u),f=_(u,2),m=h(f);_e(m,{name:"x",class:"h-5 w-5"});var d=_(s,2),g=h(d);su(g,()=>t.children??$t),U(()=>{O(o,1,`relative my-8 w-full ${r()?"max-w-2xl":"max-w-lg"} rounded-lg border border-stone-200 bg-white shadow-xl sm:my-0`),z(c,t.title)}),se("click",a,()=>{var b;return(b=t.onClose)==null?void 0:b.call(t)}),se("click",f,()=>{var b;return(b=t.onClose)==null?void 0:b.call(t)}),L(e,i),Ce()}ze(["click"]);var nc=q("<option> </option>"),ic=q('<div><label for="reminder-label">Label *</label> <input id="reminder-label" placeholder="Spark plugs"/></div>'),ac=q('<p class="text-sm text-red-600"> </p>'),oc=q('<form class="space-y-4"><div><label for="reminder-type">Type</label> <select id="reminder-type"></select></div> <!> <div class="grid grid-cols-2 gap-4"><div><label for="reminder-due-date">Due date</label> <input id="reminder-due-date" type="date"/></div> <div><label for="reminder-due-odometer">Due odometer (km)</label> <input id="reminder-due-odometer" type="number"/></div></div> <div><label for="reminder-notes">Notes</label> <textarea id="reminder-notes" rows="2"></textarea></div> <!> <div class="flex justify-end gap-2 pt-2"><button type="button">Cancel</button> <button type="submit"> </button></div></form>');function Ra(e,t){var oe,X,J,$,ue,Z;Se(t,!0);let r=Be(t,"reminder",3,null);const n=[{value:"service",label:"Service"},{value:"wheel_rotation",label:"Wheel rotation"},{value:"alignment",label:"Alignment"},{value:"custom",label:"Custom…"}];let i=B(ne(((oe=r())==null?void 0:oe.reminderType)??"service")),a=B(ne(((X=r())==null?void 0:X.label)??"")),o=B(ne((($=(J=r())==null?void 0:J.dueDate)==null?void 0:$.slice(0,10))??"")),s=B(ne(((ue=r())==null?void 0:ue.dueOdometer)??"")),u=B(ne(((Z=r())==null?void 0:Z.notes)??"")),c=B(!1),f=B("");async function m(Y){var le;if(Y.preventDefault(),l(i)==="custom"&&!l(a).trim()){v(f,"Label is required for a custom reminder");return}if(!l(o)&&!l(s)){v(f,"Set a due date or a due odometer reading");return}v(c,!0),v(f,"");const ie={reminderType:l(i),label:l(i)==="custom"?l(a).trim():null,dueDate:l(o)||null,dueOdometer:l(s)?Number(l(s)):null,notes:l(u)||null};try{r()?await en(`/reminders/${r().id}`,ie):await wr(`/cars/${t.carId}/reminders`,ie),(le=t.onSaved)==null||le.call(t)}catch(fe){v(f,fe.message,!0)}finally{v(c,!1)}}var d=oc(),g=h(d),b=h(g),C=_(b,2);zt(C,21,()=>n,Y=>Y.value,(Y,ie)=>{var le=nc(),fe=h(le),he={};U(()=>{z(fe,l(ie).label),he!==(he=l(ie).value)&&(le.value=(le.__value=l(ie).value)??"")}),L(Y,le)});var k=_(g,2);{var S=Y=>{var ie=ic(),le=h(ie),fe=_(le,2);U(()=>{O(le,1,j(ye)),O(fe,1,j(be))}),Ee(fe,()=>l(a),he=>v(a,he)),L(Y,ie)};V(k,Y=>{l(i)==="custom"&&Y(S)})}var I=_(k,2),M=h(I),R=h(M),A=_(R,2),p=_(M,2),x=h(p),D=_(x,2),y=_(I,2),w=h(y),T=_(w,2),N=_(y,2);{var F=Y=>{var ie=ac(),le=h(ie);U(()=>z(le,l(f))),L(Y,ie)};V(N,Y=>{l(f)&&Y(F)})}var P=_(N,2),H=h(P),G=_(H,2),Q=h(G);U(()=>{O(b,1,j(ye)),O(C,1,j(be)),O(R,1,j(ye)),O(A,1,j(be)),O(x,1,j(ye)),O(D,1,j(be)),O(w,1,j(ye)),O(T,1,j(be)),O(H,1,j(rr)),G.disabled=l(c),O(G,1,j(Ht)),z(Q,l(c)?"Saving…":r()?"Save changes":"Add reminder")}),br("submit",d,m),fu(C,()=>l(i),Y=>v(i,Y)),Ee(A,()=>l(o),Y=>v(o,Y)),Ee(D,()=>l(s),Y=>v(s,Y)),Ee(T,()=>l(u),Y=>v(u,Y)),se("click",H,()=>{var Y;return(Y=t.onCancel)==null?void 0:Y.call(t)}),L(e,d),Ce()}ze(["click"]);var sc=q('<p class="text-sm text-stone-400">Loading…</p>'),lc=q('<p class="text-sm text-red-600"> </p>'),uc=q('<p class="text-sm text-stone-400"> </p>'),cc=q('<span class="rounded-full
Line truncated
|
||||||
|
]))+`;wt.KANJI=new RegExp(r,"g"),wt.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),wt.BYTE=new RegExp(n,"g"),wt.NUMERIC=new RegExp(e,"g"),wt.ALPHANUMERIC=new RegExp(t,"g");const i=new RegExp("^"+r+"$"),a=new RegExp("^"+e+"$"),o=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return wt.testKanji=function(u){return i.test(u)},wt.testNumeric=function(u){return a.test(u)},wt.testAlphanumeric=function(u){return o.test(u)},wt}var Ga;function kr(){return Ga||(Ga=1,(function(e){const t=_s(),r=bs();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(a,o){if(!a.ccBits)throw new Error("Invalid mode: "+a);if(!t.isValid(o))throw new Error("Invalid version: "+o);return o>=1&&o<10?a.ccBits[0]:o<27?a.ccBits[1]:a.ccBits[2]},e.getBestModeForData=function(a){return r.testNumeric(a)?e.NUMERIC:r.testAlphanumeric(a)?e.ALPHANUMERIC:r.testKanji(a)?e.KANJI:e.BYTE},e.toString=function(a){if(a&&a.id)return a.id;throw new Error("Invalid mode")},e.isValid=function(a){return a&&a.bit&&a.ccBits};function n(i){if(typeof i!="string")throw new Error("Param is not a string");switch(i.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+i)}}e.from=function(a,o){if(e.isValid(a))return a;try{return n(a)}catch{return o}}})(_i)),_i}var Ja;function jc(){return Ja||(Ja=1,(function(e){const t=Er(),r=ms(),n=fa(),i=kr(),a=_s(),o=7973,s=t.getBCHDigit(o);function u(d,g,b){for(let C=1;C<=40;C++)if(g<=e.getCapacity(C,b,d))return C}function c(d,g){return i.getCharCountIndicator(d,g)+4}function f(d,g){let b=0;return d.forEach(function(C){const k=c(C.mode,g);b+=k+C.getBitsLength()}),b}function m(d,g){for(let b=1;b<=40;b++)if(f(d,b)<=e.getCapacity(b,g,i.MIXED))return b}e.from=function(g,b){return a.isValid(g)?parseInt(g,10):b},e.getCapacity=function(g,b,C){if(!a.isValid(g))throw new Error("Invalid QR Code version");typeof C>"u"&&(C=i.BYTE);const k=t.getSymbolTotalCodewords(g),S=r.getTotalCodewordsCount(g,b),I=(k-S)*8;if(C===i.MIXED)return I;const M=I-c(C,g);switch(C){case i.NUMERIC:return Math.floor(M/10*3);case i.ALPHANUMERIC:return Math.floor(M/11*2);case i.KANJI:return Math.floor(M/13);case i.BYTE:default:return Math.floor(M/8)}},e.getBestVersionForData=function(g,b){let C;const k=n.from(b,n.M);if(Array.isArray(g)){if(g.length>1)return m(g,k);if(g.length===0)return 1;C=g[0]}else C=g;return u(C.mode,C.getLength(),k)},e.getEncodedBits=function(g){if(!a.isValid(g)||g<7)throw new Error("Invalid QR Code version");let b=g<<12;for(;t.getBCHDigit(b)-s>=0;)b^=o<<t.getBCHDigit(b)-s;return g<<12|b}})(mi)),mi}var yi={},Wa;function Uc(){if(Wa)return yi;Wa=1;const e=Er(),t=1335,r=21522,n=e.getBCHDigit(t);return yi.getEncodedBits=function(a,o){const s=a.bit<<3|o;let u=s<<10;for(;e.getBCHDigit(u)-n>=0;)u^=t<<e.getBCHDigit(u)-n;return(s<<10|u)^r},yi}var wi={},xi,Qa;function Hc(){if(Qa)return xi;Qa=1;const e=kr();function t(r){this.mode=e.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let i,a,o;for(i=0;i+3<=this.data.length;i+=3)a=this.data.substr(i,3),o=parseInt(a,10),n.put(o,10);const s=this.data.length-i;s>0&&(a=this.data.substr(i),o=parseInt(a,10),n.put(o,s*3+1))},xi=t,xi}var Ei,Za;function zc(){if(Za)return Ei;Za=1;const e=kr(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(i){return 11*Math.floor(i/2)+6*(i%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(i){let a;for(a=0;a+2<=this.data.length;a+=2){let o=t.indexOf(this.data[a])*45;o+=t.indexOf(this.data[a+1]),i.put(o,11)}this.data.length%2&&i.put(t.indexOf(this.data[a]),6)},Ei=r,Ei}var ki,Xa;function Vc(){if(Xa)return ki;Xa=1;const e=kr();function t(r){this.mode=e.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(n){return n*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let n=0,i=this.data.length;n<i;n++)r.put(this.data[n],8)},ki=t,ki}var Si,$a;function Kc(){if($a)return Si;$a=1;const e=kr(),t=Er();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(i){return i*13},r.prototype.getLength=function(){return this.data.length},r.prototype.g
Line truncated
|
||||||
|
Make sure your charset is UTF-8`);a=(a>>>8&255)*192+(a&255),n.put(a,13)}},Si=r,Si}var Ci={exports:{}},eo;function Yc(){return eo||(eo=1,(function(e){var t={single_source_shortest_paths:function(r,n,i){var a={},o={};o[n]=0;var s=t.PriorityQueue.make();s.push(n,0);for(var u,c,f,m,d,g,b,C,k;!s.empty();){u=s.pop(),c=u.value,m=u.cost,d=r[c]||{};for(f in d)d.hasOwnProperty(f)&&(g=d[f],b=m+g,C=o[f],k=typeof o[f]>"u",(k||C>b)&&(o[f]=b,s.push(f,b),a[f]=c))}if(typeof i<"u"&&typeof o[i]>"u"){var S=["Could not find a path from ",n," to ",i,"."].join("");throw new Error(S)}return a},extract_shortest_path_from_predecessor_list:function(r,n){for(var i=[],a=n;a;)i.push(a),r[a],a=r[a];return i.reverse(),i},find_path:function(r,n,i){var a=t.single_source_shortest_paths(r,n,i);return t.extract_shortest_path_from_predecessor_list(a,i)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,i={},a;r=r||{};for(a in n)n.hasOwnProperty(a)&&(i[a]=n[a]);return i.queue=[],i.sorter=r.sorter||n.default_sorter,i},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var i={value:r,cost:n};this.queue.push(i),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(Ci)),Ci.exports}var to;function Gc(){return to||(to=1,(function(e){const t=kr(),r=Hc(),n=zc(),i=Vc(),a=Kc(),o=bs(),s=Er(),u=Yc();function c(S){return unescape(encodeURIComponent(S)).length}function f(S,I,M){const R=[];let A;for(;(A=S.exec(M))!==null;)R.push({data:A[0],index:A.index,mode:I,length:A[0].length});return R}function m(S){const I=f(o.NUMERIC,t.NUMERIC,S),M=f(o.ALPHANUMERIC,t.ALPHANUMERIC,S);let R,A;return s.isKanjiModeEnabled()?(R=f(o.BYTE,t.BYTE,S),A=f(o.KANJI,t.KANJI,S)):(R=f(o.BYTE_KANJI,t.BYTE,S),A=[]),I.concat(M,R,A).sort(function(x,D){return x.index-D.index}).map(function(x){return{data:x.data,mode:x.mode,length:x.length}})}function d(S,I){switch(I){case t.NUMERIC:return r.getBitsLength(S);case t.ALPHANUMERIC:return n.getBitsLength(S);case t.KANJI:return a.getBitsLength(S);case t.BYTE:return i.getBitsLength(S)}}function g(S){return S.reduce(function(I,M){const R=I.length-1>=0?I[I.length-1]:null;return R&&R.mode===M.mode?(I[I.length-1].data+=M.data,I):(I.push(M),I)},[])}function b(S){const I=[];for(let M=0;M<S.length;M++){const R=S[M];switch(R.mode){case t.NUMERIC:I.push([R,{data:R.data,mode:t.ALPHANUMERIC,length:R.length},{data:R.data,mode:t.BYTE,length:R.length}]);break;case t.ALPHANUMERIC:I.push([R,{data:R.data,mode:t.BYTE,length:R.length}]);break;case t.KANJI:I.push([R,{data:R.data,mode:t.BYTE,length:c(R.data)}]);break;case t.BYTE:I.push([{data:R.data,mode:t.BYTE,length:c(R.data)}])}}return I}function C(S,I){const M={},R={start:{}};let A=["start"];for(let p=0;p<S.length;p++){const x=S[p],D=[];for(let y=0;y<x.length;y++){const w=x[y],T=""+p+y;D.push(T),M[T]={node:w,lastCount:0},R[T]={};for(let N=0;N<A.length;N++){const F=A[N];M[F]&&M[F].node.mode===w.mode?(R[F][T]=d(M[F].lastCount+w.length,w.mode)-d(M[F].lastCount,w.mode),M[F].lastCount+=w.length):(M[F]&&(M[F].lastCount=w.length),R[F][T]=d(w.length,w.mode)+4+t.getCharCountIndicator(w.mode,I))}}A=D}for(let p=0;p<A.length;p++)R[A[p]].end=0;return{map:R,table:M}}function k(S,I){let M;const R=t.getBestModeForData(S);if(M=t.from(I,R),M!==t.BYTE&&M.bit<R.bit)throw new Error('"'+S+'" cannot be encoded with mode '+t.toString(M)+`.
|
||||||
|
Suggested mode is: `+t.toString(R));switch(M===t.KANJI&&!s.isKanjiModeEnabled()&&(M=t.BYTE),M){case t.NUMERIC:return new r(S);case t.ALPHANUMERIC:return new n(S);case t.KANJI:return new a(S);case t.BYTE:return new i(S)}}e.fromArray=function(I){return I.reduce(function(M,R){return typeof R=="string"?M.push(k(R,null)):R.data&&M.push(k(R.data,R.mode)),M},[])},e.fromString=function(I,M){const R=m(I,s.isKanjiModeEnabled()),A=b(R),p=C(A,M),x=u.find_path(p.map,"start","end"),D=[];for(let y=1;y<x.length-1;y++)D.push(p.table[x[y]].node);return e.fromArray(g(D))},e.rawSplit=function(I){return e.fromArray(m(I,s.isKanjiModeEnabled()))}})(wi)),wi}var ro;function Jc(){if(ro)return li;ro=1;const e=Er(),t=fa(),r=Rc(),n=Nc(),i=Lc(),a=Dc(),o=Bc(),s=ms(),u=qc(),c=jc(),f=Uc(),m=kr(),d=Gc();function g(p,x){const D=p.size,y=a.getPositions(x);for(let w=0;w<y.length;w++){const T=y[w][0],N=y[w][1];for(let F=-1;F<=7;F++)if(!(T+F<=-1||D<=T+F))for(let P=-1;P<=7;P++)N+P<=-1||D<=N+P||(F>=0&&F<=6&&(P===0||P===6)||P>=0&&P<=6&&(F===0||F===6)||F>=2&&F<=4&&P>=2&&P<=4?p.set(T+F,N+P,!0,!0):p.set(T+F,N+P,!1,!0))}}function b(p){const x=p.size;for(let D=8;D<x-8;D++){const y=D%2===0;p.set(D,6,y,!0),p.set(6,D,y,!0)}}function C(p,x){const D=i.getPositions(x);for(let y=0;y<D.length;y++){const w=D[y][0],T=D[y][1];for(let N=-2;N<=2;N++)for(let F=-2;F<=2;F++)N===-2||N===2||F===-2||F===2||N===0&&F===0?p.set(w+N,T+F,!0,!0):p.set(w+N,T+F,!1,!0)}}function k(p,x){const D=p.size,y=c.getEncodedBits(x);let w,T,N;for(let F=0;F<18;F++)w=Math.floor(F/3),T=F%3+D-8-3,N=(y>>F&1)===1,p.set(w,T,N,!0),p.set(T,w,N,!0)}function S(p,x,D){const y=p.size,w=f.getEncodedBits(x,D);let T,N;for(T=0;T<15;T++)N=(w>>T&1)===1,T<6?p.set(T,8,N,!0):T<8?p.set(T+1,8,N,!0):p.set(y-15+T,8,N,!0),T<8?p.set(8,y-T-1,N,!0):T<9?p.set(8,15-T-1+1,N,!0):p.set(8,15-T-1,N,!0);p.set(y-8,8,1,!0)}function I(p,x){const D=p.size;let y=-1,w=D-1,T=7,N=0;for(let F=D-1;F>0;F-=2)for(F===6&&F--;;){for(let P=0;P<2;P++)if(!p.isReserved(w,F-P)){let H=!1;N<x.length&&(H=(x[N]>>>T&1)===1),p.set(w,F-P,H),T--,T===-1&&(N++,T=7)}if(w+=y,w<0||D<=w){w-=y,y=-y;break}}}function M(p,x,D){const y=new r;D.forEach(function(P){y.put(P.mode.bit,4),y.put(P.getLength(),m.getCharCountIndicator(P.mode,p)),P.write(y)});const w=e.getSymbolTotalCodewords(p),T=s.getTotalCodewordsCount(p,x),N=(w-T)*8;for(y.getLengthInBits()+4<=N&&y.put(0,4);y.getLengthInBits()%8!==0;)y.putBit(0);const F=(N-y.getLengthInBits())/8;for(let P=0;P<F;P++)y.put(P%2?17:236,8);return R(y,p,x)}function R(p,x,D){const y=e.getSymbolTotalCodewords(x),w=s.getTotalCodewordsCount(x,D),T=y-w,N=s.getBlocksCount(x,D),F=y%N,P=N-F,H=Math.floor(y/N),G=Math.floor(T/N),Q=G+1,oe=H-G,X=new u(oe);let J=0;const $=new Array(N),ue=new Array(N);let Z=0;const Y=new Uint8Array(p.buffer);for(let Ie=0;Ie<N;Ie++){const K=Ie<P?G:Q;$[Ie]=Y.slice(J,J+K),ue[Ie]=X.encode($[Ie]),J+=K,Z=Math.max(Z,K)}const ie=new Uint8Array(y);let le=0,fe,he;for(fe=0;fe<Z;fe++)for(he=0;he<N;he++)fe<$[he].length&&(ie[le++]=$[he][fe]);for(fe=0;fe<oe;fe++)for(he=0;he<N;he++)ie[le++]=ue[he][fe];return ie}function A(p,x,D,y){let w;if(Array.isArray(p))w=d.fromArray(p);else if(typeof p=="string"){let H=x;if(!H){const G=d.rawSplit(p);H=c.getBestVersionForData(G,D)}w=d.fromString(p,H||40)}else throw new Error("Invalid data");const T=c.getBestVersionForData(w,D);if(!T)throw new Error("The amount of data is too big to be stored in a QR Code");if(!x)x=T;else if(x<T)throw new Error(`
|
||||||
|
The chosen QR Code version cannot contain this amount of data.
|
||||||
|
Minimum version required to store current data is: `+T+`.
|
||||||
|
`);const N=M(x,D,w),F=e.getSymbolSize(x),P=new n(F);return g(P,x),b(P),C(P,x),S(P,D,0),x>=7&&k(P,x),I(P,N),isNaN(y)&&(y=o.getBestMask(P,S.bind(null,P,D))),o.applyMask(y,P),S(P,D,y),{modules:P,version:x,errorCorrectionLevel:D,maskPattern:y,segments:w}}return li.create=function(x,D){if(typeof x>"u"||x==="")throw new Error("No input text");let y=t.M,w,T;return typeof D<"u"&&(y=t.from(D.errorCorrectionLevel,t.M),w=c.from(D.version),T=o.from(D.maskPattern),D.toSJISFunc&&e.setToSJISFunction(D.toSJISFunc)),A(x,w,y,T)},li}var Ai={},Ti={},no;function ys(){return no||(no=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(a){return[a,a]}))),n.length===6&&n.push("F","F");const i=parseInt(n.join(""),16);return{r:i>>24&255,g:i>>16&255,b:i>>8&255,a:i&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const i=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,a=n.width&&n.width>=21?n.width:void 0,o=n.scale||4;return{width:a,scale:a?4:o,margin:i,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,i){return i.width&&i.width>=n+i.margin*2?i.width/(n+i.margin*2):i.scale},e.getImageWidth=function(n,i){const a=e.getScale(n,i);return Math.floor((n+i.margin*2)*a)},e.qrToImageData=function(n,i,a){const o=i.modules.size,s=i.modules.data,u=e.getScale(o,a),c=Math.floor((o+a.margin*2)*u),f=a.margin*u,m=[a.color.light,a.color.dark];for(let d=0;d<c;d++)for(let g=0;g<c;g++){let b=(d*c+g)*4,C=a.color.light;if(d>=f&&g>=f&&d<c-f&&g<c-f){const k=Math.floor((d-f)/u),S=Math.floor((g-f)/u);C=m[s[k*o+S]?1:0]}n[b++]=C.r,n[b++]=C.g,n[b++]=C.b,n[b]=C.a}}})(Ti)),Ti}var io;function Wc(){return io||(io=1,(function(e){const t=ys();function r(i,a,o){i.clearRect(0,0,a.width,a.height),a.style||(a.style={}),a.height=o,a.width=o,a.style.height=o+"px",a.style.width=o+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(a,o,s){let u=s,c=o;typeof u>"u"&&(!o||!o.getContext)&&(u=o,o=void 0),o||(c=n()),u=t.getOptions(u);const f=t.getImageWidth(a.modules.size,u),m=c.getContext("2d"),d=m.createImageData(f,f);return t.qrToImageData(d.data,a,u),r(m,c,f),m.putImageData(d,0,0),c},e.renderToDataURL=function(a,o,s){let u=s;typeof u>"u"&&(!o||!o.getContext)&&(u=o,o=void 0),u||(u={});const c=e.render(a,o,u),f=u.type||"image/png",m=u.rendererOpts||{};return c.toDataURL(f,m.quality)}})(Ai)),Ai}var Ii={},ao;function Qc(){if(ao)return Ii;ao=1;const e=ys();function t(i,a){const o=i.a/255,s=a+'="'+i.hex+'"';return o<1?s+" "+a+'-opacity="'+o.toFixed(2).slice(1)+'"':s}function r(i,a,o){let s=i+a;return typeof o<"u"&&(s+=" "+o),s}function n(i,a,o){let s="",u=0,c=!1,f=0;for(let m=0;m<i.length;m++){const d=Math.floor(m%a),g=Math.floor(m/a);!d&&!c&&(c=!0),i[m]?(f++,m>0&&d>0&&i[m-1]||(s+=c?r("M",d+o,.5+g+o):r("m",u,0),u=0,c=!1),d+1<a&&i[m+1]||(s+=r("h",f),f=0)):u++}return s}return Ii.render=function(a,o,s){const u=e.getOptions(o),c=a.modules.size,f=a.modules.data,m=c+u.margin*2,d=u.color.light.a?"<path "+t(u.color.light,"fill")+' d="M0 0h'+m+"v"+m+'H0z"/>':"",g="<path "+t(u.color.dark,"stroke")+' d="'+n(f,c,u.margin)+'"/>',b='viewBox="0 0 '+m+" "+m+'"',k='<svg xmlns="http://www.w3.org/2000/svg" '+(u.width?'width="'+u.width+'" height="'+u.width+'" ':"")+b+' shape-rendering="crispEdges">'+d+g+`</svg>
|
||||||
|
`;return typeof s=="function"&&s(null,k),k},Ii}var oo;function Zc(){if(oo)return Mr;oo=1;const e=Pc(),t=Jc(),r=Wc(),n=Qc();function i(a,o,s,u,c){const f=[].slice.call(arguments,1),m=f.length,d=typeof f[m-1]=="function";if(!d&&!e())throw new Error("Callback required as last argument");if(d){if(m<2)throw new Error("Too few arguments provided");m===2?(c=s,s=o,o=u=void 0):m===3&&(o.getContext&&typeof c>"u"?(c=u,u=void 0):(c=u,u=s,s=o,o=void 0))}else{if(m<1)throw new Error("Too few arguments provided");return m===1?(s=o,o=u=void 0):m===2&&!o.getContext&&(u=s,s=o,o=void 0),new Promise(function(g,b){try{const C=t.create(s,u);g(a(C,o,u))}catch(C){b(C)}})}try{const g=t.create(s,u);c(null,a(g,o,u))}catch(g){c(g)}}return Mr.create=t.create,Mr.toCanvas=i.bind(null,r.render),Mr.toDataURL=i.bind(null,r.renderToDataURL),Mr.toString=i.bind(null,function(a,o,s){return n.render(a,s)}),Mr}var Xc=Zc();const $c=Mc(Xc);var ef=q("<button> </button>"),tf=q('<img alt="QR code for share link" class="h-48 w-48"/>'),rf=q('<div class="flex flex-col items-center gap-3 rounded-lg border border-stone-200 p-4"><!> <div class="flex w-full items-center gap-2"><input readonly="" class="flex-1 rounded-md border border-stone-300 bg-stone-50 px-2 py-1.5 text-xs text-stone-600"/> <button> </button></div></div> <div class="flex gap-2"><button>Regenerate link</button> <button>Turn off sharing</button></div>',1),nf=q('<p class="text-sm text-red-600"> </p>'),af=q('<div class="space-y-4"><p class="text-sm text-stone-500"> </p> <!> <!></div>');function of(e,t){Se(t,!0);let r=B(ne(t.car.shareToken)),n=B(""),i=B(!1),a=B(!1),o=B(""),s=Ct(()=>l(r)?`${window.location.origin}/#/share/${l(r)}`:"");it(()=>{if(!l(s)){v(n,"");return}$c.toDataURL(l(s),{width:220,margin:1}).then(R=>v(n,R,!0))});async function u(){var R;v(i,!0),v(o,"");try{const A=await wr(`/cars/${t.car.id}/share`,{});v(r,A.shareToken,!0),(R=t.onUpdated)==null||R.call(t,A)}catch(A){v(o,A.message,!0)}finally{v(i,!1)}}async function c(){confirm("Regenerate the link? The current QR code/link will stop working.")&&await u()}async function f(){var R;if(confirm("Turn off sharing? The current link/QR code will stop working.")){v(i,!0),v(o,"");try{await xr(`/cars/${t.car.id}/share`),v(r,null),(R=t.onUpdated)==null||R.call(t,{...t.car,shareToken:null})}catch(A){v(o,A.message,!0)}finally{v(i,!1)}}}async function m(){await navigator.clipboard.writeText(l(s)),v(a,!0),setTimeout(()=>v(a,!1),1500)}var d=af(),g=h(d),b=h(g),C=_(g,2);{var k=R=>{var A=ef(),p=h(A);U(()=>{A.disabled=l(i),O(A,1,j(Ht)),z(p,l(i)?"Generating…":"Turn on sharing")}),se("click",A,u),L(R,A)},S=R=>{var A=rf(),p=Pe(A),x=h(p);{var D=G=>{var Q=tf();U(()=>Ge(Q,"src",l(n))),L(G,Q)};V(x,G=>{l(n)&&G(D)})}var y=_(x,2),w=h(y),T=_(w,2),N=h(T),F=_(p,2),P=h(F),H=_(P,2);U(()=>{gu(w,l(s)),O(T,1,j(rr)),z(N,l(a)?"Copied!":"Copy"),P.disabled=l(i),O(P,1,j(rr)),H.disabled=l(i),O(H,1,j(vs))}),se("click",T,m),se("click",P,c),se("click",H,f),L(R,A)};V(C,R=>{l(r)?R(S,-1):R(k)})}var I=_(C,2);{var M=R=>{var A=nf(),p=h(A);U(()=>z(p,l(o))),L(R,A)};V(I,R=>{l(o)&&R(M)})}U(()=>z(b,`Share a read-only view of ${t.car.rego??""}'s service history (including attached docs) — no login required. Handy for
|
||||||
|
a QR code in the glovebox, or a link when selling the car.`)),L(e,d),Ce()}ze(["click"]);var sf=q('<p class="text-sm text-red-600"> </p>'),lf=q('<form class="space-y-4"><div><label for="kb-title">Title *</label> <input id="kb-title" placeholder="Coolant type" required=""/></div> <div><label for="kb-body">Details</label> <textarea id="kb-body" rows="8" placeholder="e.g. Toyota Super Long Life Coolant, pink, diluted 50/50. Bleed via the top-left nipple with the heater on full."></textarea></div> <!> <div class="flex justify-end gap-2 pt-2"><button type="button">Cancel</button> <button type="submit"> </button></div></form>');function so(e,t){var A,p;Se(t,!0);let r=Be(t,"entry",3,null),n=B(ne(((A=r())==null?void 0:A.title)??"")),i=B(ne(((p=r())==null?void 0:p.body)??"")),a=B(!1),o=B("");async function s(x){var y;if(x.preventDefault(),!l(n).trim()){v(o,"Title is required");return}v(a,!0),v(o,"");const D={title:l(n).trim(),body:l(i)};try{r()?await en(`/knowledge/${r().id}`,D):await wr(`/cars/${t.carId}/knowledge`,D),(y=t.onSaved)==null||y.call(t)}catch(w){v(o,w.message,!0)}finally{v(a,!1)}}var u=lf(),c=h(u),f=h(c),m=_(f,2),d=_(c,2),g=h(d),b=_(g,2),C=_(d,2);{var k=x=>{var D=sf(),y=h(D);U(()=>z(y,l(o))),L(x,D)};V(C,x=>{l(o)&&x(k)})}var S=_(C,2),I=h(S),M=_(I,2),R=h(M);U(()=>{O(f,1,j(ye)),O(m,1,j(be)),O(g,1,j(ye)),O(b,1,j(be)),O(I,1,j(rr)),M.disabled=l(a),O(M,1,j(Ht)),z(R,l(a)?"Saving…":r()?"Save changes":"Add entry")}),br("submit",u,s),Ee(m,()=>l(n),x=>v(n,x)),Ee(b,()=>l(i),x=>v(i,x)),se("click",I,()=>{var x;return(x=t.onCancel)==null?void 0:x.call(t)}),L(e,u),Ce()}ze(["click"]);var uf=q('<p class="text-sm text-stone-400">Loading…</p>'),cf=q('<p class="text-sm text-red-600"> </p>'),ff=q('<p class="text-sm text-stone-400">No knowledgebase entries yet — document procedures, common problems, or reference info like coolant type.</p>'),df=q('<button type="button" class="flex w-full items-center justify-between gap-2 py-3 text-left hover:text-teal-700"><span class="min-w-0"><span class="block truncate font-medium text-stone-900"> </span> <span class="text-xs text-stone-400"> </span></span> <!></button>'),vf=q("<button><!> </button>"),hf=q('<div class="divide-y divide-stone-100"></div> <!>',1),gf=q('<p class="whitespace-pre-wrap text-sm text-stone-700"> </p> <div class="mt-4 flex items-center justify-between border-t border-stone-100 pt-3"><span class="text-xs text-stone-400"> </span> <div class="flex gap-1"><button aria-label="Edit entry"><!></button> <button aria-label="Delete entry"><!></button></div></div>',1),pf=q("<!> <button><!> Add knowledge</button> <!> <!> <!>",1);function mf(e,t){Se(t,!0);const r=20;let n=B(ne([])),i=B(!1),a=B(!0),o=B(!1),s=B(""),u=B(null),c=B(!1),f=B(null);async function m(){v(a,!0),v(s,"");try{const P=await He(`/cars/${t.carId}/knowledge?limit=${r}&offset=0`);v(n,P.items,!0),v(i,P.hasMore,!0)}catch(P){v(s,P.message,!0)}finally{v(a,!1)}}async function d(){v(o,!0);try{const P=await He(`/cars/${t.carId}/knowledge?limit=${r}&offset=${l(n).length}`);v(n,[...l(n),...P.items],!0),v(i,P.hasMore,!0)}catch(P){v(s,P.message,!0)}finally{v(o,!1)}}it(()=>{t.carId,m()});async function g(P){confirm(`Delete "${P.title}"?`)&&(await xr(`/knowledge/${P.id}`),v(u,null),m())}function b(){v(c,!1),v(f,null),m()}function C(P){v(u,null),v(f,P,!0)}var k=pf(),S=Pe(k);{var I=P=>{var H=uf();L(P,H)},M=P=>{var H=cf(),G=h(H);U(()=>z(G,l(s))),L(P,H)},R=P=>{var H=ff();L(P,H)},A=P=>{var H=hf(),G=Pe(H);zt(G,21,()=>l(n),X=>X.id,(X,J)=>{var $=df(),ue=h($),Z=h(ue),Y=h(Z),ie=_(Z,2),le=h(ie),fe=_(ue,2);_e(fe,{name:"chevronRight",class:"h-4 w-4 shrink-0 text-stone-400"}),U(he=>{z(Y,l(J).title),z(le,`Updated ${he??""}`)},[()=>It(l(J).updatedAt)]),se("click",$,()=>v(u,l(J),!0)),L(X,$)});var Q=_(G,2);{var oe=X=>{var J=vf(),$=h(J);_e($,{name:"chevronDown",class:"h-4 w-4"});var ue=_($);U(()=>{J.disabled=l(o),O(J,1,`${nr} mt-3 disabled:opacity-50`),z(ue,` ${l(o)?"Loading…":"Load more"}`)}),se("click",J,d),L(X,J)};V(Q,X=>{l(i)&&X(oe)})}L(P,H)};V(S,P=>{l(a)?P(I):l(s)?P(M,1):l(n).length===0?P(R,2):P(A,-1)})}var p=_(S,2),x=h(p);_e(x,{name:"plus",class:"h-4 w-4"});var D=_(p,2);{var y=P=>{yt(P,{get title(){return l(u).title},onClose:()=>v(u,null),wide:!0,children:(H,G)=>{var Q=gf(),oe=Pe(Q),X=h(oe),J=_(oe,2),$=h(J),ue=h($),Z=_($,2),Y=h(Z),ie=h(Y);_e(ie,{name:"pencil",class:"h-4 w-4"});var le=_(Y,2),fe=h(le);_e(fe,{name:"trash",class:"h-4 w-4"}),U(he=>{z(X,l(u).body),z(ue,`Updated ${he??""}`),O(Y,1,j(qt)),O(le,1,`${qt} hover:text-red-600`)},[()=>It(l(u).updatedAt)]),se("click",Y,()=>C(l(u))),se("click",le,()=>g(l(u))),L(H,Q)},$$slots:{default:!0}})};V(D,P=>{l(u)&&P(y)})}var w=_(D,2);{var T=P=>{yt(P,{title:"Add knowledge entry",onClose:()=>v(c,!1),children:(H,G)=>{so(H,{get carId(){return t.carId},onSaved:b,onCancel:()=>v(c,!1)})},$$slots:{default:!0}})};V(w,P=>{l(c)&&P(T)})}var N=_(w,2);{var F=P=>{yt(P,{title:"Edit knowledge entry",onClose:()=>v(f,null),children:(H,G)=>{so(H,{get carId(){return t.carId},get entry(){return l(f)},onSaved:
Line truncated
|
||||||
|
${l(c)===l(me).key?"border-teal-700 text-teal-700":"border-transparent text-stone-500 hover:border-stone-300 hover:text-stone-900"}`),z(Pt,` ${l(me).label??""}`)}),se("click",Ae,()=>v(c,l(me).key,!0)),L(ee,Ae)});var le=_(ie,2),fe=h(le);{var he=ee=>{ps(ee,{get carId(){return l(r)}})},Ie=ee=>{mf(ee,{get carId(){return l(r)}})},K=ee=>{Tf(ee,{get carId(){return l(r)}})},ce=ee=>{jf(ee,{get carId(){return l(r)}})};V(fe,ee=>{l(c)==="reminders"?ee(he):l(c)==="knowledge"?ee(Ie,1):l(c)==="service"?ee(K,2):l(c)==="fuel"&&ee(ce,3)})}var pe=_(R,2);{var $e=ee=>{yt(ee,{get title(){return`Share ${l(n).rego??""}`},onClose:()=>v(o,!1),children:(me,Ae)=>{of(me,{get car(){return l(n)},onUpdated:Oe=>v(n,Oe,!0)})},$$slots:{default:!0}})};V(pe,ee=>{l(o)&&ee($e)})}var Ue=_(pe,2);{var vt=ee=>{yt(ee,{title:"Mileage",onClose:()=>v(s,!1),children:(me,Ae)=>{Zf(me,{get carId(){return l(r)},get odometer(){return l(n).odometer},onUpdated:f})},$$slots:{default:!0}})};V(Ue,ee=>{l(s)&&ee(vt)})}U((ee,me)=>{z(w,`${ee??""}${l(n).color?` · ${l(n).color}`:""}`),z(Q,me),O(X,1,j(rr)),Ge($,"href",`#/cars/${l(r)??""}/edit`),O($,1,j(rr)),O(Z,1,j(vs)),O(le,1,j(hs))},[()=>[l(n).year,l(n).make,l(n).model].filter(Boolean).join(" "),()=>l(n).odometer?`${l(n).odometer.toLocaleString()} km`:"Set odometer"]),se("click",G,()=>v(s,!0)),se("click",X,()=>v(o,!0)),se("click",Z,m),L(I,M)};V(b,I=>{l(i)?I(C):l(a)?I(k,1):l(n)&&I(S,2)})}L(e,g),Ce()}ze(["click"]);var nd=q('<p class="text-sm text-red-600"> </p>'),id=q('<form class="space-y-4"><div><label for="car-rego">Rego *</label> <input id="car-rego" required=""/></div> <div class="grid grid-cols-2 gap-4"><div><label for="car-make">Make</label> <input id="car-make"/></div> <div><label for="car-model">Model</label> <input id="car-model"/></div></div> <div class="grid grid-cols-3 gap-4"><div><label for="car-year">Year</label> <input id="car-year" type="number"/></div> <div><label for="car-color">Color</label> <input id="car-color"/></div> <div><label for="car-odometer">Odometer</label> <input id="car-odometer" type="number"/></div></div> <div class="grid grid-cols-2 gap-4"><div><label for="car-rego-expiry">Rego expiry</label> <input id="car-rego-expiry" type="date"/></div> <div><label for="car-wof-expiry">WoF expiry</label> <input id="car-wof-expiry" type="date"/></div></div> <div><span>Service interval (optional)</span> <p class="mb-1.5 -mt-1 text-xs text-stone-400">Whichever comes first triggers a reminder, counted from the last entry marked "full service".</p> <div class="grid grid-cols-2 gap-4"><div><label for="car-service-km" class="sr-only">Every (km)</label> <input id="car-service-km" type="number" placeholder="Every (km)"/></div> <div><label for="car-service-months" class="sr-only">Every (months)</label> <input id="car-service-months" type="number" placeholder="Every (months)"/></div></div></div> <!> <button type="submit"> </button></form>');function ws(e,t){var Oe,Pt,Ve,te,Re,Je,Vt,Kt,Sr,tn;Se(t,!0);let r=Be(t,"car",3,null),n=B(ne(((Oe=r())==null?void 0:Oe.rego)??"")),i=B(ne(((Pt=r())==null?void 0:Pt.make)??"")),a=B(ne(((Ve=r())==null?void 0:Ve.model)??"")),o=B(ne(((te=r())==null?void 0:te.year)??"")),s=B(ne(((Re=r())==null?void 0:Re.color)??"")),u=B(ne(((Je=r())==null?void 0:Je.odometer)??"")),c=B(ne((Vt=r())!=null&&Vt.regoExpiry?r().regoExpiry.slice(0,10):"")),f=B(ne((Kt=r())!=null&&Kt.wofExpiry?r().wofExpiry.slice(0,10):"")),m=B(ne(((Sr=r())==null?void 0:Sr.serviceIntervalKm)??"")),d=B(ne(((tn=r())==null?void 0:tn.serviceIntervalMonths)??"")),g=B(!1),b=B("");async function C(xe){var Cr;if(xe.preventDefault(),!l(n).trim()){v(b,"Rego is required");return}v(g,!0),v(b,"");const Rt={rego:l(n).trim(),make:l(i)||null,model:l(a)||null,year:l(o)?Number(l(o)):null,color:l(s)||null,odometer:l(u)?Number(l(u)):null,regoExpiry:l(c)||null,wofExpiry:l(f)||null,serviceIntervalKm:l(m)?Number(l(m)):null,serviceIntervalMonths:l(d)?Number(l(d)):null};try{const Ar=r()?await en(`/cars/${r().id}`,Rt):await wr("/cars",Rt);(Cr=t.onSave)==null||Cr.call(t,Ar)}catch(Ar){v(b,Ar.message,!0)}finally{v(g,!1)}}var k=id(),S=h(k),I=h(S),M=_(I,2),R=_(S,2),A=h(R),p=h(A),x=_(p,2),D=_(A,2),y=h(D),w=_(y,2),T=_(R,2),N=h(T),F=h(N),P=_(F,2),H=_(N,2),G=h(H),Q=_(G,2),oe=_(H,2),X=h(oe),J=_(X,2),$=_(T,2),ue=h($),Z=h(ue),Y=_(Z,2),ie=_(ue,2),le=h(ie),fe=_(le,2),he=_($,2),Ie=h(he),K=_(Ie,4),ce=h(K),pe=_(h(ce),2),$e=_(ce,2),Ue=_(h($e),2),vt=_(he,2);{var ee=xe=>{var Rt=nd(),Cr=h(Rt);U(()=>z(Cr,l(b))),L(xe,Rt)};V(vt,xe=>{l(b)&&xe(ee)})}var me=_(vt,2),Ae=h(me);U(()=>{O(I,1,j(ye)),O(M,1,j(be)),O(p,1,j(ye)),O(x,1,j(be)),O(y,1,j(ye)),O(w,1,j(be)),O(F,1,j(ye)),O(P,1,j(be)),O(G,1,j(ye)),O(Q,1,j(be)),O(X,1,j(ye)),O(J,1,j(be)),O(Z,1,j(ye)),O(Y,1,j(be)),O(le,1,j(ye)),O(fe,1,j(be)),O(Ie,1,j(ye)),O(pe,1,j(be)),O(Ue,1,j(be)),me.disabled=l(g),O(me,1,j(Ht)),z(Ae,l(g)?"Saving…":r()?"Save changes":"Create car")}),br("submit",k,C),Ee(M,()=>l(n),xe=>v(n,xe)),Ee(x,()=>l(i),xe=>v(i,xe)),Ee(w,()=>l(a),xe=>v(a,xe)),Ee(P,()=>l(o),xe=>v(o,xe)),Ee(Q,()=>l(s),xe=>v(s,xe))
Line truncated
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0}}}@layer theme{:root,:host{--font-sans:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-50:oklch(97.1% .013 17.38);--color-red-100:oklch(93.6% .032 17.717);--color-red-200:oklch(88.5% .062 18.334);--color-red-600:oklch(57.7% .245 27.325);--color-red-700:oklch(50.5% .213 27.518);--color-amber-50:oklch(98.7% .022 95.277);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-200:oklch(92.4% .12 95.746);--color-amber-500:oklch(76.9% .188 70.08);--color-amber-700:oklch(55.5% .163 48.998);--color-teal-50:oklch(98.4% .014 180.72);--color-teal-100:oklch(95.3% .051 180.801);--color-teal-500:oklch(70.4% .14 182.503);--color-teal-600:oklch(60% .118 184.704);--color-teal-700:oklch(51.1% .096 186.391);--color-teal-800:oklch(43.7% .078 188.216);--color-teal-900:oklch(38.6% .063 188.416);--color-stone-50:oklch(98.5% .001 106.423);--color-stone-100:oklch(97% .001 106.424);--color-stone-200:oklch(92.3% .003 48.717);--color-stone-300:oklch(86.9% .005 56.366);--color-stone-400:oklch(70.9% .01 56.259);--color-stone-500:oklch(55.3% .013 58.071);--color-stone-600:oklch(44.4% .011 73.639);--color-stone-700:oklch(37.4% .01 67.558);--color-stone-900:oklch(21.6% .006 56.043);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-2xl:42rem;--container-4xl:56rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-4xl:2.25rem;--text-4xl--line-height:calc(2.5 / 2.25);--text-5xl:3rem;--text-5xl--line-height:1;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-wide:.025em;--tracking-wider:.05em;--tracking-widest:.1em;--radius-md:.375rem;--radius-lg:.5rem;--blur-sm:8px;--aspect-video:16 / 9;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(Line truncated
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>My Garage</title>
|
||||||
|
<script type="module" crossorigin src="/assets/index-CyEkKMVz.js"></script>
|
||||||
|
<link rel="stylesheet" crossorigin href="/assets/index-N5TiDU3Y.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "embed"
|
||||||
|
|
||||||
|
// frontendFS holds the built Svelte SPA (frontend/dist contents, copied into
|
||||||
|
// ./web at build time — see backend/Dockerfile and scripts/build-frontend.sh).
|
||||||
|
// Embedding it means the whole app ships as one binary/container.
|
||||||
|
//
|
||||||
|
//go:embed all:web
|
||||||
|
var frontendFS embed.FS
|
||||||
@@ -0,0 +1,687 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
// End-to-end smoke test against SQLite + local-disk storage — the
|
||||||
|
// DB_DRIVER=sqlite / STORAGE_DRIVER=local combination that lets this app be
|
||||||
|
// tested with no external services at all. Exercises the real mux/handlers;
|
||||||
|
// only OIDC login/callback are skipped (they need a real provider), so the
|
||||||
|
// session cookie is minted directly the same way Callback would.
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"mime/multipart"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"vlog/internal/auth"
|
||||||
|
"vlog/internal/db"
|
||||||
|
"vlog/internal/handlers"
|
||||||
|
"vlog/internal/storage"
|
||||||
|
)
|
||||||
|
|
||||||
|
// a minimal valid 1x1 PNG.
|
||||||
|
var testPNG = []byte{
|
||||||
|
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
|
||||||
|
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
|
||||||
|
0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00,
|
||||||
|
0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x00, 0x01, 0x00, 0x00,
|
||||||
|
0x05, 0x00, 0x01, 0x0d, 0x0a, 0x2d, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x49,
|
||||||
|
0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTestApp(t *testing.T) (*http.ServeMux, string) {
|
||||||
|
t.Helper()
|
||||||
|
dir := t.TempDir()
|
||||||
|
|
||||||
|
database, err := db.Connect("sqlite", filepath.Join(dir, "test.db"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("db.Connect: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { database.Close() })
|
||||||
|
|
||||||
|
store, err := storage.NewLocal(filepath.Join(dir, "uploads"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("storage.NewLocal: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Authenticator is nil — fine as long as the test never hits
|
||||||
|
// /api/auth/login or /api/auth/callback (OIDC needs a real provider).
|
||||||
|
h := handlers.New(database, store, nil, "test-jwt-secret", false)
|
||||||
|
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
registerRoutes(mux, h)
|
||||||
|
|
||||||
|
// Simulate what Callback does on first login: JIT-provision a user row
|
||||||
|
// and mint the same session JWT.
|
||||||
|
userID := uuid.New().String()
|
||||||
|
if _, err := database.Exec(`INSERT INTO users (id, oidc_sub, email, name) VALUES (?, ?, ?, ?)`,
|
||||||
|
userID, "test-sub", "[email protected]", "Test User"); err != nil {
|
||||||
|
t.Fatalf("seed user: %v", err)
|
||||||
|
}
|
||||||
|
token, err := auth.MintSessionJWT("test-jwt-secret", userID, "[email protected]")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("mint session: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return mux, token
|
||||||
|
}
|
||||||
|
|
||||||
|
func doJSON(t *testing.T, mux *http.ServeMux, token, method, path string, body interface{}) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if body != nil {
|
||||||
|
if err := json.NewEncoder(&buf).Encode(body); err != nil {
|
||||||
|
t.Fatalf("encode body: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
req := httptest.NewRequest(method, path, &buf)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token})
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(rec, req)
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
|
||||||
|
func doUpload(t *testing.T, mux *http.ServeMux, token, path, fieldFile string, content []byte) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
var buf bytes.Buffer
|
||||||
|
w := multipart.NewWriter(&buf)
|
||||||
|
part, err := w.CreateFormFile("file", fieldFile)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create form file: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := part.Write(content); err != nil {
|
||||||
|
t.Fatalf("write form file: %v", err)
|
||||||
|
}
|
||||||
|
w.Close()
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodPost, path, &buf)
|
||||||
|
req.Header.Set("Content-Type", w.FormDataContentType())
|
||||||
|
req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token})
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(rec, req)
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFullFlow_SQLiteAndLocalStorage(t *testing.T) {
|
||||||
|
mux, token := newTestApp(t)
|
||||||
|
|
||||||
|
// Me
|
||||||
|
rec := doJSON(t, mux, token, http.MethodGet, "/api/me", nil)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("GET /api/me: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create car
|
||||||
|
rec = doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{
|
||||||
|
"rego": "ABC123",
|
||||||
|
"make": "Toyota",
|
||||||
|
"model": "Corolla",
|
||||||
|
"year": 2018,
|
||||||
|
"regoExpiry": "2026-09-01",
|
||||||
|
"wofExpiry": "2026-08-20",
|
||||||
|
})
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var car struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Rego string `json:"rego"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &car); err != nil {
|
||||||
|
t.Fatalf("decode car: %v", err)
|
||||||
|
}
|
||||||
|
if car.Rego != "ABC123" {
|
||||||
|
t.Fatalf("expected rego ABC123, got %q", car.Rego)
|
||||||
|
}
|
||||||
|
|
||||||
|
// List cars
|
||||||
|
rec = doJSON(t, mux, token, http.MethodGet, "/api/cars", nil)
|
||||||
|
if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("ABC123")) {
|
||||||
|
t.Fatalf("GET /api/cars: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upload photo (local storage)
|
||||||
|
rec = doUpload(t, mux, token, fmt.Sprintf("/api/cars/%s/photo", car.ID), "photo.png", testPNG)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("POST photo: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stream photo back
|
||||||
|
req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/cars/%s/photo", car.ID), nil)
|
||||||
|
req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token})
|
||||||
|
rec2 := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(rec2, req)
|
||||||
|
if rec2.Code != http.StatusOK {
|
||||||
|
t.Fatalf("GET photo: got %d", rec2.Code)
|
||||||
|
}
|
||||||
|
if got := rec2.Body.Bytes(); !bytes.Equal(got, testPNG) {
|
||||||
|
t.Fatalf("photo bytes round-trip mismatch: got %d bytes, want %d", len(got), len(testPNG))
|
||||||
|
}
|
||||||
|
if ct := rec2.Header().Get("Content-Type"); ct != "image/png" {
|
||||||
|
t.Fatalf("expected image/png content-type, got %q", ct)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A renamed non-image file must be rejected (content-sniffing, not extension)
|
||||||
|
rec = doUpload(t, mux, token, fmt.Sprintf("/api/cars/%s/photo", car.ID), "fake.png", []byte("not actually a png"))
|
||||||
|
if rec.Code != http.StatusUnsupportedMediaType {
|
||||||
|
t.Fatalf("expected 415 for fake png, got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add a service entry
|
||||||
|
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), map[string]interface{}{
|
||||||
|
"entryDate": "2026-07-01",
|
||||||
|
"entryType": "Oil change",
|
||||||
|
"performedAt": "Bob's Garage",
|
||||||
|
"odometer": 45000,
|
||||||
|
})
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("POST service-entries: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var entry struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &entry)
|
||||||
|
|
||||||
|
// Attach a PNG to it
|
||||||
|
rec = doUpload(t, mux, token, fmt.Sprintf("/api/service-entries/%s/files", entry.ID), "invoice.png", testPNG)
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("POST service-entry file: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var file struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &file)
|
||||||
|
|
||||||
|
// Timeline shows the entry with its file
|
||||||
|
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), nil)
|
||||||
|
if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("invoice.png")) {
|
||||||
|
t.Fatalf("GET service-entries: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stream the attachment back
|
||||||
|
req = httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/files/%s", file.ID), nil)
|
||||||
|
req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token})
|
||||||
|
rec2 = httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(rec2, req)
|
||||||
|
if rec2.Code != http.StatusOK || !bytes.Equal(rec2.Body.Bytes(), testPNG) {
|
||||||
|
t.Fatalf("GET file: got %d, %d bytes", rec2.Code, rec2.Body.Len())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add a custom reminder due soon, and one far in the future
|
||||||
|
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/reminders", car.ID), map[string]interface{}{
|
||||||
|
"reminderType": "custom",
|
||||||
|
"label": "Spark plugs",
|
||||||
|
"dueDate": "2026-08-20",
|
||||||
|
})
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("POST reminders: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/reminders", car.ID), map[string]interface{}{
|
||||||
|
"reminderType": "service",
|
||||||
|
"dueDate": "2030-01-01",
|
||||||
|
})
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("POST reminders (far future): got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dashboard should surface: the near-due custom reminder, rego expiry,
|
||||||
|
// and WoF expiry (all within 30 days) — but not the 2030 reminder.
|
||||||
|
rec = doJSON(t, mux, token, http.MethodGet, "/api/dashboard", nil)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("GET dashboard: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var items []map[string]interface{}
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &items); err != nil {
|
||||||
|
t.Fatalf("decode dashboard: %v", err)
|
||||||
|
}
|
||||||
|
kinds := map[string]bool{}
|
||||||
|
for _, it := range items {
|
||||||
|
kinds[it["reminderType"].(string)] = true
|
||||||
|
}
|
||||||
|
for _, want := range []string{"custom", "rego", "wof"} {
|
||||||
|
if !kinds[want] {
|
||||||
|
t.Errorf("expected dashboard to include kind %q, items: %+v", want, items)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(items) != 3 {
|
||||||
|
t.Errorf("expected exactly 3 dashboard items (not the 2030 reminder), got %d: %+v", len(items), items)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete the car — must cascade to entries/files/reminders.
|
||||||
|
rec = doJSON(t, mux, token, http.MethodDelete, fmt.Sprintf("/api/cars/%s", car.ID), nil)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("DELETE car: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s", car.ID), nil)
|
||||||
|
if rec.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("GET deleted car: expected 404, got %d", rec.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The attached file should also be gone from local disk (best-effort
|
||||||
|
// delete on cascade) — GET should now 404.
|
||||||
|
req = httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/files/%s", file.ID), nil)
|
||||||
|
req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token})
|
||||||
|
rec2 = httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(rec2, req)
|
||||||
|
if rec2.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("GET file after car delete: expected 404, got %d", rec2.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestKnowledgeBase(t *testing.T) {
|
||||||
|
mux, token := newTestApp(t)
|
||||||
|
|
||||||
|
rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "KB001"})
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var car struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &car)
|
||||||
|
|
||||||
|
// Create
|
||||||
|
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/knowledge", car.ID), map[string]interface{}{
|
||||||
|
"title": "Coolant type",
|
||||||
|
"body": "Use Toyota Super Long Life Coolant, pink, diluted 50/50.",
|
||||||
|
})
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("POST knowledge: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var entry struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &entry)
|
||||||
|
if entry.Title != "Coolant type" {
|
||||||
|
t.Fatalf("expected title Coolant type, got %q", entry.Title)
|
||||||
|
}
|
||||||
|
|
||||||
|
// List
|
||||||
|
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/knowledge", car.ID), nil)
|
||||||
|
if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("Coolant type")) {
|
||||||
|
t.Fatalf("GET knowledge: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update
|
||||||
|
rec = doJSON(t, mux, token, http.MethodPut, fmt.Sprintf("/api/knowledge/%s", entry.ID), map[string]interface{}{
|
||||||
|
"title": "Coolant type (updated)",
|
||||||
|
"body": "Use Toyota Super Long Life Coolant, pink, diluted 50/50. Bleed via the top-left nipple.",
|
||||||
|
})
|
||||||
|
if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("Bleed via")) {
|
||||||
|
t.Fatalf("PUT knowledge: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete
|
||||||
|
rec = doJSON(t, mux, token, http.MethodDelete, fmt.Sprintf("/api/knowledge/%s", entry.ID), nil)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("DELETE knowledge: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/knowledge", car.ID), nil)
|
||||||
|
if rec.Code != http.StatusOK || string(rec.Body.Bytes()) != `{"items":[],"hasMore":false}`+"\n" {
|
||||||
|
t.Fatalf("expected empty knowledge list after delete, got %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestListPagination covers both paginated list endpoints (service entries
|
||||||
|
// and knowledge entries) — the thing that matters for a car with a very
|
||||||
|
// long history: a page at a time, never the whole thing in one response.
|
||||||
|
func TestListPagination(t *testing.T) {
|
||||||
|
mux, token := newTestApp(t)
|
||||||
|
|
||||||
|
rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "PAGE001"})
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var car struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &car)
|
||||||
|
|
||||||
|
const total = 25
|
||||||
|
for i := 0; i < total; i++ {
|
||||||
|
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), map[string]interface{}{
|
||||||
|
"entryDate": fmt.Sprintf("2020-01-%02d", (i%28)+1),
|
||||||
|
"entryType": fmt.Sprintf("Entry %d", i),
|
||||||
|
})
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("seed service entry %d: got %d, body %s", i, rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/knowledge", car.ID), map[string]interface{}{
|
||||||
|
"title": fmt.Sprintf("KB %d", i),
|
||||||
|
"body": "body",
|
||||||
|
})
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("seed knowledge entry %d: got %d, body %s", i, rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, endpoint := range []string{"service-entries", "knowledge"} {
|
||||||
|
// Default page (no ?limit=) should cap at 20 and report more available.
|
||||||
|
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/%s", car.ID, endpoint), nil)
|
||||||
|
var firstPage struct {
|
||||||
|
Items []json.RawMessage `json:"items"`
|
||||||
|
HasMore bool `json:"hasMore"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &firstPage); err != nil {
|
||||||
|
t.Fatalf("%s first page: decode failed: %v, body %s", endpoint, err, rec.Body.String())
|
||||||
|
}
|
||||||
|
if len(firstPage.Items) != 20 || !firstPage.HasMore {
|
||||||
|
t.Fatalf("%s first page: expected 20 items + hasMore=true, got %d items, hasMore=%v",
|
||||||
|
endpoint, len(firstPage.Items), firstPage.HasMore)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Second page (offset=20) should return the remaining 5, hasMore=false.
|
||||||
|
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/%s?limit=20&offset=20", car.ID, endpoint), nil)
|
||||||
|
var secondPage struct {
|
||||||
|
Items []json.RawMessage `json:"items"`
|
||||||
|
HasMore bool `json:"hasMore"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &secondPage); err != nil {
|
||||||
|
t.Fatalf("%s second page: decode failed: %v, body %s", endpoint, err, rec.Body.String())
|
||||||
|
}
|
||||||
|
if len(secondPage.Items) != total-20 || secondPage.HasMore {
|
||||||
|
t.Fatalf("%s second page: expected %d items + hasMore=false, got %d items, hasMore=%v",
|
||||||
|
endpoint, total-20, len(secondPage.Items), secondPage.HasMore)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A tiny explicit page size still respects hasMore correctly.
|
||||||
|
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/%s?limit=3&offset=0", car.ID, endpoint), nil)
|
||||||
|
var smallPage struct {
|
||||||
|
Items []json.RawMessage `json:"items"`
|
||||||
|
HasMore bool `json:"hasMore"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &smallPage)
|
||||||
|
if len(smallPage.Items) != 3 || !smallPage.HasMore {
|
||||||
|
t.Fatalf("%s small page: expected 3 items + hasMore=true, got %d items, hasMore=%v",
|
||||||
|
endpoint, len(smallPage.Items), smallPage.HasMore)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSecondUserCannotSeeFirstUsersCar(t *testing.T) {
|
||||||
|
mux, token1 := newTestApp(t)
|
||||||
|
|
||||||
|
rec := doJSON(t, mux, token1, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "PRIVATE1"})
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var car struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &car)
|
||||||
|
|
||||||
|
// Mint a second user's session against the SAME app/db (simulating a
|
||||||
|
// second OIDC-authenticated user).
|
||||||
|
// newTestApp already seeded one user in its own fresh DB, so instead we
|
||||||
|
// reuse the mux but mint a token for a brand-new, never-provisioned user.
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/api/cars", nil)
|
||||||
|
badToken, err := auth.MintSessionJWT("test-jwt-secret", "00000000-0000-0000-0000-000000000000", "[email protected]")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("mint: %v", err)
|
||||||
|
}
|
||||||
|
req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: badToken})
|
||||||
|
rec2 := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(rec2, req)
|
||||||
|
if rec2.Code != http.StatusOK || string(rec2.Body.Bytes()) != "[]\n" {
|
||||||
|
// (also guards against regressing to encoding an empty list as
|
||||||
|
// JSON null, which would crash the frontend's cars.length checks)
|
||||||
|
t.Fatalf("second user's garage should be empty, got %d: %s", rec2.Code, rec2.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// And can't reach the first user's car by ID either.
|
||||||
|
rec3 := doJSON(t, mux, badToken, http.MethodGet, fmt.Sprintf("/api/cars/%s", car.ID), nil)
|
||||||
|
if rec3.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("expected 404 for other user's car, got %d", rec3.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSharingPublicEndpoints(t *testing.T) {
|
||||||
|
mux, token := newTestApp(t)
|
||||||
|
|
||||||
|
rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "SHARE1", "make": "Honda"})
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("POST /api/cars: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var car struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &car)
|
||||||
|
|
||||||
|
// Not shared yet — public endpoint 404s.
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/api/public/cars/nonexistent-token", nil)
|
||||||
|
rec2 := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(rec2, req)
|
||||||
|
if rec2.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("expected 404 for unknown share token, got %d", rec2.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Turn sharing on.
|
||||||
|
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/share", car.ID), nil)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("POST share: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var shared struct {
|
||||||
|
ShareToken string `json:"shareToken"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &shared)
|
||||||
|
if shared.ShareToken == "" {
|
||||||
|
t.Fatal("expected a non-empty shareToken")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add a service entry with an attachment, to confirm docs are included
|
||||||
|
// in the public view (the whole point of sharing when selling a car).
|
||||||
|
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), map[string]interface{}{
|
||||||
|
"entryDate": "2026-01-01",
|
||||||
|
"entryType": "Oil change",
|
||||||
|
})
|
||||||
|
var entry struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &entry)
|
||||||
|
rec = doUpload(t, mux, token, fmt.Sprintf("/api/service-entries/%s/files", entry.ID), "invoice.png", testPNG)
|
||||||
|
var file struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &file)
|
||||||
|
|
||||||
|
// Public car info — no auth cookie needed at all.
|
||||||
|
req = httptest.NewRequest(http.MethodGet, "/api/public/cars/"+shared.ShareToken, nil)
|
||||||
|
rec2 = httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(rec2, req)
|
||||||
|
if rec2.Code != http.StatusOK || !bytes.Contains(rec2.Body.Bytes(), []byte("SHARE1")) {
|
||||||
|
t.Fatalf("public car: got %d, body %s", rec2.Code, rec2.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Public service history — should include the attachment.
|
||||||
|
req = httptest.NewRequest(http.MethodGet, "/api/public/cars/"+shared.ShareToken+"/service-entries", nil)
|
||||||
|
rec2 = httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(rec2, req)
|
||||||
|
if rec2.Code != http.StatusOK || !bytes.Contains(rec2.Body.Bytes(), []byte("invoice.png")) {
|
||||||
|
t.Fatalf("public service-entries: got %d, body %s", rec2.Code, rec2.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Public file download.
|
||||||
|
req = httptest.NewRequest(http.MethodGet, "/api/public/cars/"+shared.ShareToken+"/files/"+file.ID, nil)
|
||||||
|
rec2 = httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(rec2, req)
|
||||||
|
if rec2.Code != http.StatusOK || !bytes.Equal(rec2.Body.Bytes(), testPNG) {
|
||||||
|
t.Fatalf("public file: got %d, %d bytes", rec2.Code, rec2.Body.Len())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revoke — public endpoint 404s again.
|
||||||
|
rec = doJSON(t, mux, token, http.MethodDelete, fmt.Sprintf("/api/cars/%s/share", car.ID), nil)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("DELETE share: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
req = httptest.NewRequest(http.MethodGet, "/api/public/cars/"+shared.ShareToken, nil)
|
||||||
|
rec2 = httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(rec2, req)
|
||||||
|
if rec2.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("expected 404 after revoke, got %d", rec2.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFuelEntries(t *testing.T) {
|
||||||
|
mux, token := newTestApp(t)
|
||||||
|
|
||||||
|
rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "FUEL1"})
|
||||||
|
var car struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &car)
|
||||||
|
|
||||||
|
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/fuel-entries", car.ID), map[string]interface{}{
|
||||||
|
"entryDate": "2026-07-01",
|
||||||
|
"litres": 45.5,
|
||||||
|
"cost": 98.20,
|
||||||
|
"odometer": 50000,
|
||||||
|
"location": "BP",
|
||||||
|
})
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("POST fuel-entries: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var entry struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Litres float64 `json:"litres"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &entry)
|
||||||
|
if entry.Litres != 45.5 {
|
||||||
|
t.Fatalf("expected litres 45.5, got %v", entry.Litres)
|
||||||
|
}
|
||||||
|
|
||||||
|
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/fuel-entries", car.ID), nil)
|
||||||
|
if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("BP")) {
|
||||||
|
t.Fatalf("GET fuel-entries: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
rec = doJSON(t, mux, token, http.MethodPut, fmt.Sprintf("/api/fuel-entries/%s", entry.ID), map[string]interface{}{
|
||||||
|
"entryDate": "2026-07-01",
|
||||||
|
"litres": 46,
|
||||||
|
"cost": 100,
|
||||||
|
"location": "Z Energy",
|
||||||
|
})
|
||||||
|
if rec.Code != http.StatusOK || !bytes.Contains(rec.Body.Bytes(), []byte("Z Energy")) {
|
||||||
|
t.Fatalf("PUT fuel-entries: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
rec = doJSON(t, mux, token, http.MethodDelete, fmt.Sprintf("/api/fuel-entries/%s", entry.ID), nil)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("DELETE fuel-entries: got %d, body %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMileageAndMilestone(t *testing.T) {
|
||||||
|
mux, token := newTestApp(t)
|
||||||
|
|
||||||
|
rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{"rego": "MILE1", "odometer": 68420})
|
||||||
|
var car struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &car)
|
||||||
|
|
||||||
|
// With no history points yet, still reports current reading, just no
|
||||||
|
// rate/throughput estimate.
|
||||||
|
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/mileage", car.ID), nil)
|
||||||
|
var m struct {
|
||||||
|
CurrentOdometer int `json:"currentOdometer"`
|
||||||
|
KmPerYear *float64 `json:"kmPerYear"`
|
||||||
|
YearsPer100k *float64 `json:"yearsPer100k"`
|
||||||
|
Next100kEta *string `json:"next100kEta"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &m)
|
||||||
|
if m.KmPerYear != nil || m.YearsPer100k != nil {
|
||||||
|
t.Fatalf("expected no rate/throughput with <2 data points, got kmPerYear=%v yearsPer100k=%v", m.KmPerYear, m.YearsPer100k)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add a historical fuel entry a year ago at a lower reading — now there
|
||||||
|
// are two points and a rate/throughput estimate should compute.
|
||||||
|
yearAgo := "2025-08-06"
|
||||||
|
doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/fuel-entries", car.ID), map[string]interface{}{
|
||||||
|
"entryDate": yearAgo, "litres": 40, "cost": 80, "odometer": 50000,
|
||||||
|
})
|
||||||
|
|
||||||
|
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/mileage", car.ID), nil)
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &m)
|
||||||
|
if m.KmPerYear == nil || *m.KmPerYear < 17000 || *m.KmPerYear > 19500 {
|
||||||
|
t.Fatalf("expected ~18,420 km/year, got %v", m.KmPerYear)
|
||||||
|
}
|
||||||
|
// 100,000km / ~18,420km per year is ~5.4 years — a throughput figure
|
||||||
|
// from today, unrelated to the odometer's current position (68,420km
|
||||||
|
// is nowhere near a "100,000km" round number, and that's the point).
|
||||||
|
if m.YearsPer100k == nil || *m.YearsPer100k < 5.0 || *m.YearsPer100k > 6.0 {
|
||||||
|
t.Fatalf("expected ~5.4 years per 100,000km, got %v", m.YearsPer100k)
|
||||||
|
}
|
||||||
|
if m.Next100kEta == nil {
|
||||||
|
t.Fatal("expected a next100kEta date once a rate is known")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSynthesizedReminders(t *testing.T) {
|
||||||
|
mux, token := newTestApp(t)
|
||||||
|
|
||||||
|
rec := doJSON(t, mux, token, http.MethodPost, "/api/cars", map[string]interface{}{
|
||||||
|
"rego": "REM001", "regoExpiry": "2026-08-20", "wofExpiry": "2026-08-15",
|
||||||
|
})
|
||||||
|
var car struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &car)
|
||||||
|
|
||||||
|
// Even with zero real reminders, rego/WoF show up automatically.
|
||||||
|
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/reminders", car.ID), nil)
|
||||||
|
var views []map[string]interface{}
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &views)
|
||||||
|
types := map[string]bool{}
|
||||||
|
for _, v := range views {
|
||||||
|
types[v["reminderType"].(string)] = true
|
||||||
|
if v["id"] != nil && v["reminderType"] == "rego" {
|
||||||
|
t.Fatalf("synthesized rego reminder should have a nil id, got %v", v["id"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !types["rego"] || !types["wof"] {
|
||||||
|
t.Fatalf("expected synthesized rego+wof reminders, got %+v", views)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configure a service interval and log a qualifying service entry —
|
||||||
|
// a synthesized "service" reminder should now also appear.
|
||||||
|
doJSON(t, mux, token, http.MethodPut, fmt.Sprintf("/api/cars/%s", car.ID), map[string]interface{}{
|
||||||
|
"rego": "REM001", "serviceIntervalKm": 10000, "serviceIntervalMonths": 6,
|
||||||
|
})
|
||||||
|
doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/service-entries", car.ID), map[string]interface{}{
|
||||||
|
"entryDate": "2026-01-01", "entryType": "Full service", "odometer": 40000, "isService": true,
|
||||||
|
})
|
||||||
|
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/reminders", car.ID), nil)
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &views)
|
||||||
|
types = map[string]bool{}
|
||||||
|
for _, v := range views {
|
||||||
|
types[v["reminderType"].(string)] = true
|
||||||
|
}
|
||||||
|
if !types["service"] {
|
||||||
|
t.Fatalf("expected synthesized service reminder after logging a qualifying entry, got %+v", views)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A completed real reminder is hidden by default, shown with ?completed=1.
|
||||||
|
rec = doJSON(t, mux, token, http.MethodPost, fmt.Sprintf("/api/cars/%s/reminders", car.ID), map[string]interface{}{
|
||||||
|
"reminderType": "custom", "label": "Test reminder", "dueDate": "2026-09-01",
|
||||||
|
})
|
||||||
|
var reminder struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
json.Unmarshal(rec.Body.Bytes(), &reminder)
|
||||||
|
doJSON(t, mux, token, http.MethodPut, fmt.Sprintf("/api/reminders/%s", reminder.ID), map[string]interface{}{"completed": true})
|
||||||
|
|
||||||
|
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/reminders", car.ID), nil)
|
||||||
|
if bytes.Contains(rec.Body.Bytes(), []byte("Test reminder")) {
|
||||||
|
t.Fatalf("completed reminder should be hidden by default, got %s", rec.Body.String())
|
||||||
|
}
|
||||||
|
rec = doJSON(t, mux, token, http.MethodGet, fmt.Sprintf("/api/cars/%s/reminders?completed=1", car.ID), nil)
|
||||||
|
if !bytes.Contains(rec.Body.Bytes(), []byte("Test reminder")) {
|
||||||
|
t.Fatalf("completed reminder should show with ?completed=1, got %s", rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
// Command server is the whole app: it serves the JSON API and the embedded
|
||||||
|
// Svelte SPA from one binary, and applies DB migrations on startup.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"vlog/internal/auth"
|
||||||
|
"vlog/internal/config"
|
||||||
|
"vlog/internal/db"
|
||||||
|
"vlog/internal/handlers"
|
||||||
|
"vlog/internal/storage"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
cfg, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
database, err := db.Connect(cfg.DBDriver, cfg.DatabaseURL)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("database: %v", err)
|
||||||
|
}
|
||||||
|
defer database.Close()
|
||||||
|
|
||||||
|
store, err := newStorage(ctx, cfg)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("storage: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only require Secure cookies when we're actually serving over https —
|
||||||
|
// lets this run over plain http for local dev.
|
||||||
|
secureCookies := strings.HasPrefix(cfg.PublicBaseURL, "https://")
|
||||||
|
|
||||||
|
authenticator, err := auth.NewAuthenticator(ctx, cfg.OIDCIssuerURL, cfg.OIDCClientID, cfg.OIDCClientSecret, cfg.OIDCRedirectURL, secureCookies)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("oidc: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
h := handlers.New(database, store, authenticator, cfg.JWTSigningSecret, secureCookies)
|
||||||
|
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
registerRoutes(mux, h)
|
||||||
|
|
||||||
|
staticFS, err := fs.Sub(frontendFS, "web")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("frontend assets: %v", err)
|
||||||
|
}
|
||||||
|
mux.Handle("/", spaHandler(staticFS))
|
||||||
|
|
||||||
|
srv := &http.Server{
|
||||||
|
Addr: ":" + cfg.Port,
|
||||||
|
Handler: logMiddleware(mux),
|
||||||
|
ReadHeaderTimeout: 10 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("listening on :%s", cfg.Port)
|
||||||
|
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||||
|
log.Fatalf("server: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// newStorage picks the file storage backend based on STORAGE_DRIVER: "s3"
|
||||||
|
// (production) or "local" (writes to disk — for testing without a real S3
|
||||||
|
// bucket). Handlers depend only on the storage.Storage interface, so
|
||||||
|
// nothing else in the app needs to know which one is active.
|
||||||
|
func newStorage(ctx context.Context, cfg *config.Config) (storage.Storage, error) {
|
||||||
|
switch cfg.StorageDriver {
|
||||||
|
case "s3":
|
||||||
|
return storage.NewS3(ctx, cfg.AWSRegion, cfg.S3Bucket)
|
||||||
|
case "local":
|
||||||
|
return storage.NewLocal(cfg.LocalStoragePath)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("invalid STORAGE_DRIVER %q (must be s3 or local)", cfg.StorageDriver)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// logMiddleware and recovery in one small wrapper — no need for a whole
|
||||||
|
// middleware package for two stdlib one-liners.
|
||||||
|
func logMiddleware(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
defer func() {
|
||||||
|
if rec := recover(); rec != nil {
|
||||||
|
log.Printf("panic handling %s %s: %v", r.Method, r.URL.Path, rec)
|
||||||
|
http.Error(w, "internal server error", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
log.Printf("%s %s %s", r.Method, r.URL.Path, time.Since(start))
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"vlog/internal/auth"
|
||||||
|
"vlog/internal/handlers"
|
||||||
|
)
|
||||||
|
|
||||||
|
// registerRoutes wires up the whole JSON API. Auth login/callback/logout
|
||||||
|
// and the /api/public/... share endpoints are public; everything else
|
||||||
|
// requires the session cookie.
|
||||||
|
func registerRoutes(mux *http.ServeMux, h *handlers.Handlers) {
|
||||||
|
mux.HandleFunc("GET /api/auth/login", h.Login)
|
||||||
|
mux.HandleFunc("GET /api/auth/callback", h.Callback)
|
||||||
|
mux.HandleFunc("POST /api/auth/logout", h.Logout)
|
||||||
|
|
||||||
|
// Public, unauthenticated share view (QR code / link, no login) — a
|
||||||
|
// deliberately narrow read-only surface, see internal/handlers/public.go.
|
||||||
|
mux.HandleFunc("GET /api/public/cars/{shareToken}", h.PublicCar)
|
||||||
|
mux.HandleFunc("GET /api/public/cars/{shareToken}/photo", h.PublicCarPhoto)
|
||||||
|
mux.HandleFunc("GET /api/public/cars/{shareToken}/service-entries", h.PublicServiceEntries)
|
||||||
|
mux.HandleFunc("GET /api/public/cars/{shareToken}/files/{fileId}", h.PublicFile)
|
||||||
|
|
||||||
|
protected := http.NewServeMux()
|
||||||
|
protected.HandleFunc("GET /api/me", h.Me)
|
||||||
|
|
||||||
|
protected.HandleFunc("GET /api/cars", h.ListCars)
|
||||||
|
protected.HandleFunc("POST /api/cars", h.CreateCar)
|
||||||
|
protected.HandleFunc("GET /api/cars/{carId}", h.GetCar)
|
||||||
|
protected.HandleFunc("PUT /api/cars/{carId}", h.UpdateCar)
|
||||||
|
protected.HandleFunc("DELETE /api/cars/{carId}", h.DeleteCar)
|
||||||
|
protected.HandleFunc("POST /api/cars/{carId}/photo", h.UploadCarPhoto)
|
||||||
|
protected.HandleFunc("GET /api/cars/{carId}/photo", h.GetCarPhoto)
|
||||||
|
protected.HandleFunc("PATCH /api/cars/{carId}/odometer", h.UpdateOdometer)
|
||||||
|
protected.HandleFunc("POST /api/cars/{carId}/share", h.GenerateShareLink)
|
||||||
|
protected.HandleFunc("DELETE /api/cars/{carId}/share", h.RevokeShareLink)
|
||||||
|
protected.HandleFunc("GET /api/cars/{carId}/mileage", h.Mileage)
|
||||||
|
|
||||||
|
protected.HandleFunc("GET /api/cars/{carId}/service-entries", h.ListServiceEntries)
|
||||||
|
protected.HandleFunc("POST /api/cars/{carId}/service-entries", h.CreateServiceEntry)
|
||||||
|
protected.HandleFunc("GET /api/service-entries/{entryId}", h.GetServiceEntry)
|
||||||
|
protected.HandleFunc("PUT /api/service-entries/{entryId}", h.UpdateServiceEntry)
|
||||||
|
protected.HandleFunc("DELETE /api/service-entries/{entryId}", h.DeleteServiceEntry)
|
||||||
|
protected.HandleFunc("POST /api/service-entries/{entryId}/files", h.UploadServiceEntryFile)
|
||||||
|
protected.HandleFunc("GET /api/files/{fileId}", h.GetFile)
|
||||||
|
protected.HandleFunc("DELETE /api/files/{fileId}", h.DeleteFile)
|
||||||
|
|
||||||
|
protected.HandleFunc("GET /api/cars/{carId}/reminders", h.ListReminders)
|
||||||
|
protected.HandleFunc("POST /api/cars/{carId}/reminders", h.CreateReminder)
|
||||||
|
protected.HandleFunc("PUT /api/reminders/{reminderId}", h.UpdateReminder)
|
||||||
|
protected.HandleFunc("DELETE /api/reminders/{reminderId}", h.DeleteReminder)
|
||||||
|
|
||||||
|
protected.HandleFunc("GET /api/cars/{carId}/knowledge", h.ListKnowledge)
|
||||||
|
protected.HandleFunc("POST /api/cars/{carId}/knowledge", h.CreateKnowledge)
|
||||||
|
protected.HandleFunc("PUT /api/knowledge/{knowledgeId}", h.UpdateKnowledge)
|
||||||
|
protected.HandleFunc("DELETE /api/knowledge/{knowledgeId}", h.DeleteKnowledge)
|
||||||
|
|
||||||
|
protected.HandleFunc("GET /api/cars/{carId}/fuel-entries", h.ListFuelEntries)
|
||||||
|
protected.HandleFunc("POST /api/cars/{carId}/fuel-entries", h.CreateFuelEntry)
|
||||||
|
protected.HandleFunc("PUT /api/fuel-entries/{entryId}", h.UpdateFuelEntry)
|
||||||
|
protected.HandleFunc("DELETE /api/fuel-entries/{entryId}", h.DeleteFuelEntry)
|
||||||
|
|
||||||
|
protected.HandleFunc("GET /api/dashboard", h.Dashboard)
|
||||||
|
|
||||||
|
// Mounted as a subtree on the outer mux; Go's ServeMux does not strip
|
||||||
|
// the prefix, so the protected mux's patterns include the full "/api/..."
|
||||||
|
// path and match the original request untouched.
|
||||||
|
mux.Handle("/api/", auth.RequireAuth(h.JWTSecret)(protected))
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io/fs"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// spaHandler serves the embedded Svelte build, falling back to index.html
|
||||||
|
// for any path that isn't a real static asset — this is what lets the
|
||||||
|
// client-side router handle "deep" URLs like /cars/123 on a hard refresh.
|
||||||
|
func spaHandler(staticFS fs.FS) http.Handler {
|
||||||
|
fileServer := http.FileServer(http.FS(staticFS))
|
||||||
|
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
path := strings.TrimPrefix(r.URL.Path, "/")
|
||||||
|
if path == "" {
|
||||||
|
path = "index.html"
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := fs.Stat(staticFS, path); err != nil {
|
||||||
|
indexReq := r.Clone(r.Context())
|
||||||
|
indexReq.URL.Path = "/"
|
||||||
|
fileServer.ServeHTTP(w, indexReq)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fileServer.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
Whitespace-only changes.
@@ -0,0 +1,45 @@
|
|||||||
|
module vlog
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/aws/aws-sdk-go-v2 v1.43.4
|
||||||
|
github.com/aws/aws-sdk-go-v2/config v1.32.35
|
||||||
|
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.40
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/s3 v1.106.5
|
||||||
|
github.com/coreos/go-oidc/v3 v3.20.0
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||||
|
github.com/golang-migrate/migrate/v4 v4.19.1
|
||||||
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/jmoiron/sqlx v1.4.0
|
||||||
|
github.com/lib/pq v1.12.3
|
||||||
|
golang.org/x/oauth2 v0.36.0
|
||||||
|
modernc.org/sqlite v1.56.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.16 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/credentials v1.19.34 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.35 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.35 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.35 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.36 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.15 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.28 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.35 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.36 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/signin v1.5.4 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sso v1.33.4 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.38.4 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sts v1.45.4 // indirect
|
||||||
|
github.com/aws/smithy-go v1.27.6 // indirect
|
||||||
|
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||||
|
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||||
|
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||||
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||||
|
golang.org/x/sys v0.47.0 // indirect
|
||||||
|
modernc.org/libc v1.74.4 // indirect
|
||||||
|
modernc.org/mathutil v1.7.1 // indirect
|
||||||
|
modernc.org/memory v1.11.0 // indirect
|
||||||
|
)
|
||||||
+165
@@ -0,0 +1,165 @@
|
|||||||
|
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||||
|
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||||
|
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
|
||||||
|
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
|
||||||
|
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||||
|
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||||
|
github.com/aws/aws-sdk-go-v2 v1.43.4 h1:b9FTvbRwy+JCsfp2Wp6wV/KbOx3Aj7nkoFb2cRX0IhE=
|
||||||
|
github.com/aws/aws-sdk-go-v2 v1.43.4/go.mod h1:70vwSy16txshwG+g55WkpgPKDIByzHI8ccBsOteo3bQ=
|
||||||
|
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.16 h1:aiuaKlDweRC5qExJondpWjOgyzMHpofpwspGXUtwn4c=
|
||||||
|
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.16/go.mod h1:nG/LOlmox9BDe9HvQnXWzgcK8uKbgBMZ/Hp5pVt/21I=
|
||||||
|
github.com/aws/aws-sdk-go-v2/config v1.32.35 h1:UEzXuET8E42lxBPijuACu/tEK7v5lFPlk0Q+GT5WD9E=
|
||||||
|
github.com/aws/aws-sdk-go-v2/config v1.32.35/go.mod h1:KaMtJpFa2JlL2BStjjHQVwQpzZEmw+ND/EgVrfFoo2g=
|
||||||
|
github.com/aws/aws-sdk-go-v2/credentials v1.19.34 h1:y6GkSmcv5myd1ngrYbGmiLlwQqB6TQhOuN/tbSSuWDY=
|
||||||
|
github.com/aws/aws-sdk-go-v2/credentials v1.19.34/go.mod h1:w3dTcnDVoQIewjo7JG45hduAToikiIFLC4FIO7fndvw=
|
||||||
|
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.35 h1:+S7kbJoLDDQ5tE+lHrUBgMkzC8NLgsaioS2F3dVoFAE=
|
||||||
|
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.35/go.mod h1:Ak7xXviIARfFdNUJ9Etb0bdVDt/KAvKjMGJVLWXDzik=
|
||||||
|
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.40 h1:8h8ZlKpMiJDWHptcpP9SYjWds3ppVAKrbI02pqEi8uM=
|
||||||
|
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.40/go.mod h1:K8aokMNmZVa12zR7OJ5vF2+uwBl1QEZqm3AuBS3DqIo=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.35 h1:kzVuGlatQtYinwBJEEyLAbggepCoavosiaHHX9+fD+c=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.35/go.mod h1:0yLx0yEI+SfqeJMPvOtIEFoZbiQYXMGszBueiutQyaI=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.35 h1:WK6CjihTuLisCjSKKbildJ79sGZZgbBz3iNa7VsKIhU=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.35/go.mod h1:KYleN57luLoe97R7vTnx8PMcVrr9gAcRECtOjl91DNg=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.36 h1:jbGY4CXLzZElOXgGsexlC3Hi+3YM0rSmk4opFXKqg/k=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.36/go.mod h1:uBu/9aKsS/UQGc72RAt3y54kjgYQxmhut8ZD2dXCDNE=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.15 h1:JJLBQxwY+AFwuPAi5ivGc1ChnTdUt4cXMv7e76m2c/Y=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.15/go.mod h1:lQknBIe78MVL0cQOQDlag8KGflMbMEVFx9mB6O8ENvk=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.28 h1:Q1TF1J9jVD+vFo0LzNnmNdQ9EAt52TS+MQlq9Ir+Yxo=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.28/go.mod h1:4KqXXC/p1hrotmouDFbrRoWaLy962b9PMUReCG6+uWo=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.35 h1:BBEElKh4a+rKshvjrfpajTe9CbpZvrbb4Jkg2PB7RzA=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.35/go.mod h1:zaZk983w//8beSruBVec/mr4CmDwgZitW/qzGhAAX0g=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.36 h1:EUIwBoN+q7UmhAejxgD27APiRjh1vwCFo53gSqdT0BM=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.36/go.mod h1:6u00gmlTGR6W0b2k9NBrld7MnOEmf1Spqx0VVt6AqyE=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/s3 v1.106.5 h1:HpN6GgZ3T8pSvRp81ZsgumNjlvRsa+9M0ZL2o6W4uLY=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/s3 v1.106.5/go.mod h1:5FTZoQxhmLEiCAtYVk6V+t0iS/B5yGZVLZ3Wq5FDJZI=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/signin v1.5.4 h1:cOJELVNrq5Q3Udry2GLuHUM7MhwpeaQRdYaoa6GI/yI=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/signin v1.5.4/go.mod h1:f4LxzKBtaTxD7xh3PiVg3CE1tchQemfmghaJr+NbK2c=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sso v1.33.4 h1:AMW7a7S8iQaHjBYZdU3PCq4GKRPijTPRAc7e6XtEThY=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sso v1.33.4/go.mod h1:QQNsFV1DVXoXcZt18FS8lI8rtUrlDyAuWZLQ5shunv4=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.38.4 h1:AsbZcJAQPRmHDJG8K1N0pof/1zPWjVT8TFlTWuGLSvo=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.38.4/go.mod h1:6imqztH0//t0mKbl6yWl7swSEl7F/w32oAmqB3vP1ag=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sts v1.45.4 h1:w/AryDYMjSUANSQ2uoZxJovUsMTwWJNTv3IMex30Y+4=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sts v1.45.4/go.mod h1:WeBiAa67azG7Su9Vf+ChGDBLiAozJCXzdjXiPBUwtbc=
|
||||||
|
github.com/aws/smithy-go v1.27.6 h1:0zjT8jgK3jbrTT7JJ3EE6JsMhX8JTrZ+f1sEndYDXrA=
|
||||||
|
github.com/aws/smithy-go v1.27.6/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||||
|
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
|
||||||
|
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
|
||||||
|
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
|
||||||
|
github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=
|
||||||
|
github.com/coreos/go-oidc/v3 v3.20.0 h1:EtE0WIBHk03N+DqGkY4+UONzzZHk7amKt6IyNd7OsZE=
|
||||||
|
github.com/coreos/go-oidc/v3 v3.20.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
|
||||||
|
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||||
|
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/dhui/dktest v0.4.6 h1:+DPKyScKSEp3VLtbMDHcUq6V5Lm5zfZZVb0Sk7Ahom4=
|
||||||
|
github.com/dhui/dktest v0.4.6/go.mod h1:JHTSYDtKkvFNFHJKqCzVzqXecyv+tKt8EzceOmQOgbU=
|
||||||
|
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
|
||||||
|
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||||
|
github.com/docker/docker v28.3.3+incompatible h1:Dypm25kh4rmk49v1eiVbsAtpAsYURjYkaKubwuBdxEI=
|
||||||
|
github.com/docker/docker v28.3.3+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
||||||
|
github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c=
|
||||||
|
github.com/docker/go-connections v0.5.0/go.mod h1:ov60Kzw0kKElRwhNs9UlUHAE/F9Fe6GLaXnqyDdmEXc=
|
||||||
|
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
||||||
|
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||||
|
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||||
|
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||||
|
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||||
|
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||||
|
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
|
||||||
|
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||||
|
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||||
|
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||||
|
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||||
|
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||||
|
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
||||||
|
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||||
|
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||||
|
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||||
|
github.com/golang-migrate/migrate/v4 v4.19.1 h1:OCyb44lFuQfYXYLx1SCxPZQGU7mcaZ7gH9yH4jSFbBA=
|
||||||
|
github.com/golang-migrate/migrate/v4 v4.19.1/go.mod h1:CTcgfjxhaUtsLipnLoQRWCrjYXycRz/g5+RWDuYgPrE=
|
||||||
|
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
|
||||||
|
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
|
||||||
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||||
|
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||||
|
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
|
||||||
|
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
|
||||||
|
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||||
|
github.com/lib/pq v1.12.3 h1:tTWxr2YLKwIvK90ZXEw8GP7UFHtcbTtty8zsI+YjrfQ=
|
||||||
|
github.com/lib/pq v1.12.3/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
|
||||||
|
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||||
|
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||||
|
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
|
||||||
|
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
|
||||||
|
github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=
|
||||||
|
github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=
|
||||||
|
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
|
||||||
|
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
|
||||||
|
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||||
|
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||||
|
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||||
|
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||||
|
github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug=
|
||||||
|
github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM=
|
||||||
|
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||||
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
|
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||||
|
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||||
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||||
|
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||||
|
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||||
|
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
|
||||||
|
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
|
||||||
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus=
|
||||||
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q=
|
||||||
|
go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ=
|
||||||
|
go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I=
|
||||||
|
go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE=
|
||||||
|
go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E=
|
||||||
|
go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4=
|
||||||
|
go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0=
|
||||||
|
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
|
||||||
|
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
|
||||||
|
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
||||||
|
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||||
|
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
|
||||||
|
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||||
|
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||||
|
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
|
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
|
||||||
|
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
modernc.org/cc/v4 v4.29.1 h1:MKgdCV3WykTSPqpVrnxdEDS0HEd2FHpKZDzxzU5LyeI=
|
||||||
|
modernc.org/cc/v4 v4.29.1/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
|
||||||
|
modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU=
|
||||||
|
modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk=
|
||||||
|
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
|
||||||
|
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
|
||||||
|
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||||
|
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||||
|
modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI=
|
||||||
|
modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||||
|
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||||
|
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||||
|
modernc.org/libc v1.74.4 h1:fX1Omw4o2/1C2iRkkIsrQTasJQldLhRmuPreXLoWs9k=
|
||||||
|
modernc.org/libc v1.74.4/go.mod h1:eeQAS9W3sZeKYMFubydxJpII9ybHWshk+7or7bLG9co=
|
||||||
|
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||||
|
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||||
|
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||||
|
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||||
|
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
|
||||||
|
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||||
|
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||||
|
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||||
|
modernc.org/sqlite v1.56.0 h1:/D8e2RfFqoy/Zc6PuC76U28zFwmI/sYx1Kjm4yEn9e0=
|
||||||
|
modernc.org/sqlite v1.56.0/go.mod h1:yCJ2cmAaIkHQ25oXWrF8H4O1lIfPYPR26yCEDj2P3pQ=
|
||||||
|
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||||
|
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||||
|
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||||
|
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||||
@@ -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,
|
||||||
|
}
|
||||||
|
)
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
// Package migrations embeds the DB schema for both supported drivers so the
|
||||||
|
// server can apply it on startup with no separate migrate step.
|
||||||
|
//
|
||||||
|
// Postgres uses versioned golang-migrate .sql files (PostgresFS). SQLite
|
||||||
|
// uses one idempotent schema file applied directly (SQLiteSchemaSQL) — it's
|
||||||
|
// a local dev/testing convenience DB, not something that needs migration
|
||||||
|
// history.
|
||||||
|
package migrations
|
||||||
|
|
||||||
|
import "embed"
|
||||||
|
|
||||||
|
//go:embed postgres/*.sql
|
||||||
|
var PostgresFS embed.FS
|
||||||
|
|
||||||
|
//go:embed sqlite/schema.sql
|
||||||
|
var SQLiteSchemaSQL string
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
DROP TABLE IF EXISTS reminders;
|
||||||
|
DROP TABLE IF EXISTS service_entry_files;
|
||||||
|
DROP TABLE IF EXISTS service_entries;
|
||||||
|
DROP TABLE IF EXISTS cars;
|
||||||
|
DROP TABLE IF EXISTS users;
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
-- IDs are generated in Go (uuid.New()) rather than via a DB default, so the
|
||||||
|
-- same INSERT statements work unchanged against SQLite too — no pgcrypto
|
||||||
|
-- extension needed.
|
||||||
|
|
||||||
|
CREATE TABLE users (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
oidc_sub TEXT NOT NULL UNIQUE,
|
||||||
|
email TEXT NOT NULL,
|
||||||
|
name TEXT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE cars (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
rego TEXT NOT NULL,
|
||||||
|
make TEXT,
|
||||||
|
model TEXT,
|
||||||
|
year INT,
|
||||||
|
color TEXT,
|
||||||
|
odometer INT,
|
||||||
|
rego_expiry DATE,
|
||||||
|
wof_expiry DATE,
|
||||||
|
photo_s3_key TEXT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
UNIQUE (user_id, rego)
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_cars_user_id ON cars(user_id);
|
||||||
|
|
||||||
|
CREATE TABLE service_entries (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
car_id UUID NOT NULL REFERENCES cars(id) ON DELETE CASCADE,
|
||||||
|
entry_date DATE NOT NULL,
|
||||||
|
entry_type TEXT NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
performed_at TEXT,
|
||||||
|
odometer INT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_service_entries_car_id ON service_entries(car_id);
|
||||||
|
CREATE INDEX idx_service_entries_date ON service_entries(entry_date);
|
||||||
|
|
||||||
|
CREATE TABLE service_entry_files (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
service_entry_id UUID NOT NULL REFERENCES service_entries(id) ON DELETE CASCADE,
|
||||||
|
s3_key TEXT NOT NULL,
|
||||||
|
file_name TEXT NOT NULL,
|
||||||
|
content_type TEXT NOT NULL,
|
||||||
|
size_bytes BIGINT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_service_entry_files_entry_id ON service_entry_files(service_entry_id);
|
||||||
|
|
||||||
|
CREATE TABLE reminders (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
car_id UUID NOT NULL REFERENCES cars(id) ON DELETE CASCADE,
|
||||||
|
reminder_type TEXT NOT NULL,
|
||||||
|
label TEXT,
|
||||||
|
due_date DATE,
|
||||||
|
due_odometer INT,
|
||||||
|
notes TEXT,
|
||||||
|
completed_at TIMESTAMPTZ,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CHECK (due_date IS NOT NULL OR due_odometer IS NOT NULL)
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_reminders_car_id ON reminders(car_id);
|
||||||
|
CREATE INDEX idx_reminders_due_date ON reminders(due_date) WHERE completed_at IS NULL;
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
DROP TABLE IF EXISTS knowledge_entries;
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
CREATE TABLE knowledge_entries (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
car_id UUID NOT NULL REFERENCES cars(id) ON DELETE CASCADE,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
body TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_knowledge_entries_car_id ON knowledge_entries(car_id);
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
DROP TABLE IF EXISTS fuel_entries;
|
||||||
|
ALTER TABLE cars DROP COLUMN IF EXISTS share_token;
|
||||||
|
ALTER TABLE cars DROP COLUMN IF EXISTS service_interval_km;
|
||||||
|
ALTER TABLE cars DROP COLUMN IF EXISTS service_interval_months;
|
||||||
|
ALTER TABLE service_entries DROP COLUMN IF EXISTS is_service;
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
-- Nullable, unique when set: NULL means sharing is off for that car. A
|
||||||
|
-- random opaque token (not the car's own id) so a share link can't be
|
||||||
|
-- guessed and doesn't leak the car's real UUID.
|
||||||
|
ALTER TABLE cars ADD COLUMN share_token TEXT UNIQUE;
|
||||||
|
|
||||||
|
-- Either/both may be set; whichever comes first triggers the synthesized
|
||||||
|
-- "service due" reminder (computed from the most recent is_service entry).
|
||||||
|
ALTER TABLE cars ADD COLUMN service_interval_km INT;
|
||||||
|
ALTER TABLE cars ADD COLUMN service_interval_months INT;
|
||||||
|
|
||||||
|
-- Marks a service_entries row as "this was a full service" — i.e. the
|
||||||
|
-- baseline the next service-due reminder counts forward from. Most entries
|
||||||
|
-- (oil top-up, tyre rotation, etc.) won't set this.
|
||||||
|
ALTER TABLE service_entries ADD COLUMN is_service BOOLEAN NOT NULL DEFAULT false;
|
||||||
|
|
||||||
|
CREATE TABLE fuel_entries (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
car_id UUID NOT NULL REFERENCES cars(id) ON DELETE CASCADE,
|
||||||
|
entry_date DATE NOT NULL,
|
||||||
|
litres DOUBLE PRECISION NOT NULL,
|
||||||
|
cost DOUBLE PRECISION NOT NULL,
|
||||||
|
odometer INT,
|
||||||
|
location TEXT,
|
||||||
|
notes TEXT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_fuel_entries_car_id ON fuel_entries(car_id);
|
||||||
|
CREATE INDEX idx_fuel_entries_date ON fuel_entries(entry_date);
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
-- Applied idempotently (CREATE ... IF NOT EXISTS) on every startup rather
|
||||||
|
-- than through golang-migrate — this is a local dev/testing convenience DB,
|
||||||
|
-- not something that needs versioned migration history. For production, use
|
||||||
|
-- Postgres (DB_DRIVER=postgres) and the versioned migrations/postgres/ set.
|
||||||
|
--
|
||||||
|
-- Column types matter here beyond documentation: modernc.org/sqlite only
|
||||||
|
-- auto-converts to/from Go's time.Time when a column's declared type
|
||||||
|
-- contains DATE/DATETIME/TIMESTAMP (plain TEXT would come back as a string
|
||||||
|
-- and fail to scan), and only auto-converts to/from Go's bool when the
|
||||||
|
-- declared type is BOOLEAN — both verified empirically, not assumed.
|
||||||
|
--
|
||||||
|
-- NOTE: "IF NOT EXISTS" means new columns added to an existing table
|
||||||
|
-- definition here do NOT retroactively appear in an already-created local
|
||||||
|
-- .db file — CREATE TABLE IF NOT EXISTS is a no-op once the table exists.
|
||||||
|
-- db.go's ensureSQLiteColumns() handles that: it ALTER TABLE ADD COLUMNs
|
||||||
|
-- anything new (see internal/db/sqlite_migrate.go), so an existing local
|
||||||
|
-- .db file picks up schema growth automatically — no need to delete it.
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS 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 IF NOT EXISTS cars (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
rego TEXT NOT NULL,
|
||||||
|
make TEXT,
|
||||||
|
model TEXT,
|
||||||
|
year INTEGER,
|
||||||
|
color TEXT,
|
||||||
|
odometer INTEGER,
|
||||||
|
rego_expiry DATE,
|
||||||
|
wof_expiry DATE,
|
||||||
|
photo_s3_key TEXT,
|
||||||
|
share_token TEXT UNIQUE,
|
||||||
|
service_interval_km INTEGER,
|
||||||
|
service_interval_months INTEGER,
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
UNIQUE (user_id, rego)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_cars_user_id ON cars(user_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS service_entries (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
car_id TEXT NOT NULL REFERENCES cars(id) ON DELETE CASCADE,
|
||||||
|
entry_date DATE NOT NULL,
|
||||||
|
entry_type TEXT NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
performed_at TEXT,
|
||||||
|
odometer INTEGER,
|
||||||
|
is_service BOOLEAN NOT NULL DEFAULT 0,
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_service_entries_car_id ON service_entries(car_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_service_entries_date ON service_entries(entry_date);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS service_entry_files (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
service_entry_id TEXT NOT NULL REFERENCES service_entries(id) ON DELETE CASCADE,
|
||||||
|
s3_key TEXT NOT NULL,
|
||||||
|
file_name TEXT NOT NULL,
|
||||||
|
content_type TEXT NOT NULL,
|
||||||
|
size_bytes INTEGER NOT NULL,
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_service_entry_files_entry_id ON service_entry_files(service_entry_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS reminders (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
car_id TEXT NOT NULL REFERENCES cars(id) ON DELETE CASCADE,
|
||||||
|
reminder_type TEXT NOT NULL,
|
||||||
|
label TEXT,
|
||||||
|
due_date DATE,
|
||||||
|
due_odometer INTEGER,
|
||||||
|
notes TEXT,
|
||||||
|
completed_at DATETIME,
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
CHECK (due_date IS NOT NULL OR due_odometer IS NOT NULL)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_reminders_car_id ON reminders(car_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_reminders_due_date ON reminders(due_date) WHERE completed_at IS NULL;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS knowledge_entries (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
car_id TEXT NOT NULL REFERENCES cars(id) ON DELETE CASCADE,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
body TEXT NOT NULL,
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_knowledge_entries_car_id ON knowledge_entries(car_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS fuel_entries (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
car_id TEXT NOT NULL REFERENCES cars(id) ON DELETE CASCADE,
|
||||||
|
entry_date DATE NOT NULL,
|
||||||
|
litres REAL NOT NULL,
|
||||||
|
cost REAL NOT NULL,
|
||||||
|
odometer INTEGER,
|
||||||
|
location TEXT,
|
||||||
|
notes TEXT,
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_fuel_entries_car_id ON fuel_entries(car_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_fuel_entries_date ON fuel_entries(entry_date);
|
||||||
Reference in new issue
Block a user