mitbringsl/backend/internal/httpapi/lists.go
Tronax 67033e561c
Tests for shared lists & docs catch-up to post-MVP state
Integration tests for the invite/join/membership feature that shipped
without any coverage:

- internal/store/liststore_test.go: CreateList adds owner as member with
  invite code, GetLists returns owned+joined but not foreign lists,
  GetList access control (owner/member yes, stranger and soft-deleted no),
  JoinByInviteCode normalization/idempotency/role-keeping, lazy invite
  code generation. Runs against TEST_DATABASE_URL, skips otherwise.
- internal/httpapi/api_test.go: full E2E over the real router — register,
  create list (code in response), invite endpoint, join (lowercase),
  cross-member op push/pull sync, stranger gets 404 on every list
  endpoint, invalid code 400, idempotent re-join, and 401 gating of all
  protected routes.
- lists.go Invite handler: store errors now map through apiError, so
  non-members get 404 instead of 400 (consistent with Get/Push/Pull).

Docs updated to the actual post-MVP state: AGENTS.md (post-MVP features,
repo structure, roadmap with open points like join rate limiting),
API.md (join/invite endpoints, invite_code fields, membership rules),
SYNC.md (shared lists section), README (local-only default, sharing,
integration test recipe).
2026-08-22 09:40:57 +02:00

236 lines
6.2 KiB
Go

package httpapi
import (
"log/slog"
"net/http"
"strings"
"github.com/google/uuid"
"github.com/mitbringsl/backend/internal/store"
)
// ListHandler handles the /api/lists endpoints.
type ListHandler struct {
lists *store.ListStore
items *store.ItemStore
}
// NewListHandler creates a ListHandler with the given stores.
func NewListHandler(lists *store.ListStore, items *store.ItemStore) *ListHandler {
return &ListHandler{lists: lists, items: items}
}
// --- request / response types -----------------------------------------------
type createListRequest struct {
Name string `json:"name"`
}
type joinListRequest struct {
InviteCode string `json:"invite_code"`
}
type inviteCodeResponse struct {
InviteCode string `json:"invite_code"`
}
type listDTO struct {
ID string `json:"id"`
Name string `json:"name"`
InviteCode string `json:"invite_code,omitempty"`
UpdatedAt string `json:"updated_at"`
HLCTS int64 `json:"hlc_ts"`
}
type listDetailDTO struct {
listDTO
Items []store.Item `json:"items"`
}
type listListResponse struct {
Lists []listDTO `json:"lists"`
}
// --- handlers ---------------------------------------------------------------
// List returns all non-deleted lists for the authenticated user (owner or member).
// GET /api/lists
func (h *ListHandler) List(w http.ResponseWriter, r *http.Request) {
userID, ok := userIDFromCtx(r)
if !ok {
renderError(w, http.StatusUnauthorized, "Unauthorized", "Missing user context.")
return
}
ls, err := h.lists.GetLists(r.Context(), userID)
if err != nil {
slog.Error("list lists failed", "error", err, "user_id", userID)
renderError(w, http.StatusInternalServerError, "Internal error", "Could not load lists.")
return
}
dtos := make([]listDTO, len(ls))
for i, l := range ls {
dtos[i] = listDTO{
ID: l.ID.String(),
Name: l.Name,
InviteCode: l.InviteCode,
UpdatedAt: l.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"),
HLCTS: l.HLCTS,
}
}
renderJSON(w, http.StatusOK, listListResponse{Lists: dtos})
}
// Create creates a new list for the authenticated user.
// POST /api/lists
func (h *ListHandler) Create(w http.ResponseWriter, r *http.Request) {
userID, ok := userIDFromCtx(r)
if !ok {
renderError(w, http.StatusUnauthorized, "Unauthorized", "Missing user context.")
return
}
var req createListRequest
if !decodeJSON(w, r, &req) {
return
}
name := strings.TrimSpace(req.Name)
if name == "" {
renderError(w, http.StatusBadRequest, "Bad request", "List name must not be empty.")
return
}
l, err := h.lists.CreateList(r.Context(), userID, name)
if err != nil {
slog.Error("create list failed", "error", err, "user_id", userID)
renderError(w, http.StatusInternalServerError, "Internal error", "Could not create list.")
return
}
renderJSON(w, http.StatusCreated, listDTO{
ID: l.ID.String(),
Name: l.Name,
InviteCode: l.InviteCode,
UpdatedAt: l.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"),
HLCTS: l.HLCTS,
})
}
// Get returns a single list with its items.
// GET /api/lists/{id}
func (h *ListHandler) Get(w http.ResponseWriter, r *http.Request) {
userID, ok := userIDFromCtx(r)
if !ok {
renderError(w, http.StatusUnauthorized, "Unauthorized", "Missing user context.")
return
}
listID, err := uuid.Parse(r.PathValue("id"))
if err != nil {
renderError(w, http.StatusBadRequest, "Bad request", "Invalid list ID.")
return
}
l, err := h.lists.GetList(r.Context(), listID, userID)
if err != nil {
if !apiError(w, err) {
slog.Error("get list failed", "error", err, "list_id", listID)
renderError(w, http.StatusInternalServerError, "Internal error", "Could not load list.")
}
return
}
its, err := h.items.GetItems(r.Context(), listID)
if err != nil {
slog.Error("get items failed", "error", err, "list_id", listID)
renderError(w, http.StatusInternalServerError, "Internal error", "Could not load items.")
return
}
if its == nil {
its = []store.Item{}
}
renderJSON(w, http.StatusOK, listDetailDTO{
listDTO: listDTO{
ID: l.ID.String(),
Name: l.Name,
InviteCode: l.InviteCode,
UpdatedAt: l.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"),
HLCTS: l.HLCTS,
},
Items: its,
})
}
// Invite returns or generates the invite code for a list.
// POST /api/lists/{id}/invite
func (h *ListHandler) Invite(w http.ResponseWriter, r *http.Request) {
userID, ok := userIDFromCtx(r)
if !ok {
renderError(w, http.StatusUnauthorized, "Unauthorized", "Missing user context.")
return
}
listID, err := uuid.Parse(r.PathValue("id"))
if err != nil {
renderError(w, http.StatusBadRequest, "Bad request", "Invalid list ID.")
return
}
code, err := h.lists.GetInviteCode(r.Context(), listID, userID)
if err != nil {
if !apiError(w, err) {
slog.Error("get invite code failed", "error", err, "list_id", listID)
renderError(w, http.StatusInternalServerError, "Internal error", "Could not get invite code.")
}
return
}
renderJSON(w, http.StatusOK, inviteCodeResponse{InviteCode: code})
}
// Join adds the authenticated user to a list using an invite code.
// POST /api/lists/join
func (h *ListHandler) Join(w http.ResponseWriter, r *http.Request) {
userID, ok := userIDFromCtx(r)
if !ok {
renderError(w, http.StatusUnauthorized, "Unauthorized", "Missing user context.")
return
}
var req joinListRequest
if !decodeJSON(w, r, &req) {
return
}
code := strings.TrimSpace(req.InviteCode)
if code == "" {
renderError(w, http.StatusBadRequest, "Bad request", "Invite code must not be empty.")
return
}
l, err := h.lists.JoinByInviteCode(r.Context(), userID, code)
if err != nil {
slog.Error("join list failed", "error", err, "user_id", userID, "code", code)
renderError(w, http.StatusBadRequest, "Bad request", "Ungültiger Einladungs-Code.")
return
}
renderJSON(w, http.StatusOK, listDTO{
ID: l.ID.String(),
Name: l.Name,
InviteCode: l.InviteCode,
UpdatedAt: l.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"),
HLCTS: l.HLCTS,
})
}
// userIDFromCtx extracts the user UUID from the request context (set by RequireAuth).
func userIDFromCtx(r *http.Request) (uuid.UUID, bool) {
v := r.Context().Value(ctxKeyUserID)
if v == nil {
return uuid.Nil, false
}
id, ok := v.(uuid.UUID)
return id, ok
}