package main import ( "crypto/subtle" "database/sql" "encoding/json" "errors" "log" "net/http" "strconv" "strings" ) // Integration is a read-only, token-authenticated view of one account's walks // and meals, for other services on the same host (the household planner, // schema, ticks off its dog duties from it). It is not a session: there is no // cookie, it sees one configured account, and it can't write anything. type Integration struct { db *sql.DB token string // email picks the account whose events are exposed. Empty means "the only // account", and refuses to guess once there are several. email string } type integrationEvent struct { ID string `json:"id"` Type string `json:"type"` At int64 `json:"at"` Deleted bool `json:"deleted,omitempty"` } func (in *Integration) userID() (string, error) { if in.email != "" { var id string err := in.db.QueryRow(`SELECT id FROM users WHERE email = ? COLLATE NOCASE`, in.email).Scan(&id) return id, err } rows, err := in.db.Query(`SELECT id FROM users LIMIT 2`) if err != nil { return "", err } defer rows.Close() var ids []string for rows.Next() { var id string if err := rows.Scan(&id); err != nil { return "", err } ids = append(ids, id) } if len(ids) != 1 { return "", errors.New("set -integration-user: there is not exactly one account") } return ids[0], nil } // GET /api/integration/events?since= returns the account's walk // starts and meals that happened, or were changed, since then — tombstones // included, so a consumer can undo what a deleted event did. func (in *Integration) handleEvents(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } got, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") if !ok || subtle.ConstantTimeCompare([]byte(got), []byte(in.token)) != 1 { http.Error(w, "unauthorized", http.StatusUnauthorized) return } since, err := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64) if err != nil { http.Error(w, "since: want unix milliseconds", http.StatusBadRequest) return } uid, err := in.userID() if err != nil { log.Printf("integration: %v", err) http.Error(w, "no account to read from", http.StatusConflict) return } rows, err := in.db.Query(` SELECT id, type, at, deleted FROM events WHERE user_id = ? AND type IN ('walk-start', 'eat') AND (at >= ? OR updated >= ?) ORDER BY at`, uid, since, since) if err != nil { log.Printf("integration: %v", err) http.Error(w, "server error", http.StatusInternalServerError) return } defer rows.Close() out := []integrationEvent{} for rows.Next() { var e integrationEvent if err := rows.Scan(&e.ID, &e.Type, &e.At, &e.Deleted); err != nil { log.Printf("integration: %v", err) http.Error(w, "server error", http.StatusInternalServerError) return } out = append(out, e) } w.Header().Set("Content-Type", "application/json") w.Header().Set("Cache-Control", "no-store") _ = json.NewEncoder(w).Encode(map[string]any{"events": out}) }