Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

The API answers in sentences (#154)

Carter66542f4f95a9
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index c968d65..81d41fb 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -91,7 +91,13 @@ jobs:
go-version: '1.26'
cache-dependency-path: backend/go.sum
- run: cd backend && go mod download
- - run: cd backend && go test ./controllers/ ./db/ ./routes/ -timeout 30s
+ # ./... not a hand-listed subset: this job ran 3 packages of 7, so utils/,
+ # stores/, config/ and oedb/ were invisible here. utils/ owns every error
+ # sentence the API emits, and this PR adds 223 lines of tests to it that
+ # would otherwise never gate a merge. Measured hermetic (httptest only, no
+ # outbound hosts) and ~23s total; -timeout is per package, and the slowest
+ # is 15s.
+ - run: cd backend && go test ./... -timeout 30s
unit:
name: Web unit tests
diff --git a/backend/controllers/active_session.go b/backend/controllers/active_session.go
index 9e1349d..f31cfa0 100644
--- a/backend/controllers/active_session.go
+++ b/backend/controllers/active_session.go
@@ -27,7 +27,7 @@ func (h *Handler) UpsertActiveSession(c *gin.Context) {
Data string `json:"data" binding:"required"`
}
if err := c.ShouldBindJSON(&body); err != nil {
- utils.BadRequest(c, err.Error())
+ utils.BadRequest(c, utils.BindMessage(err))
return
}
if utils.DBError(c, h.s.ActiveSession.Upsert(uid, body.Data)) {
diff --git a/backend/controllers/auth.go b/backend/controllers/auth.go
index 22e02f3..0f11f6e 100644
--- a/backend/controllers/auth.go
+++ b/backend/controllers/auth.go
@@ -10,15 +10,14 @@ import (
"github.com/Cawlumm/lyftr-backend/stores"
"github.com/Cawlumm/lyftr-backend/utils"
"github.com/gin-gonic/gin"
- "github.com/go-playground/validator/v10"
)
-var validate = validator.New()
+var validate = utils.NewValidator()
// RegistrationClosedMessage is what a rejected signup sees. One constant so the two
// ways of being closed (REGISTRATION=closed, and first-user with the slot taken) are
// indistinguishable to a caller — and so the handler and its tests cannot drift.
-const RegistrationClosedMessage = "registration is closed on this server"
+const RegistrationClosedMessage = "Registration is closed on this server."
// registrationOpen reports whether a new account may be created right now. Errors are
// reported as closed: advertising an open instance because a COUNT failed is the wrong
@@ -54,7 +53,7 @@ func (h *Handler) Register(c *gin.Context) {
var req models.RegisterRequest
if err := c.ShouldBindJSON(&req); err != nil {
- utils.BadRequest(c, err.Error())
+ utils.BadRequest(c, utils.BindMessage(err))
return
}
if err := validate.Struct(req); err != nil {
@@ -87,7 +86,7 @@ func (h *Handler) Register(c *gin.Context) {
return
}
if utils.IsUniqueViolation(err) {
- utils.Conflict(c, "email already registered")
+ utils.Conflict(c, "That email is already registered.")
return
}
if utils.DBError(c, err) {
@@ -117,7 +116,7 @@ func (h *Handler) Register(c *gin.Context) {
func (h *Handler) Login(c *gin.Context) {
var req models.LoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
- utils.BadRequest(c, err.Error())
+ utils.BadRequest(c, utils.BindMessage(err))
return
}
if err := validate.Struct(req); err != nil {
@@ -132,14 +131,14 @@ func (h *Handler) Login(c *gin.Context) {
// anyone asking exactly which addresses are registered — undoing the point of
// giving both cases the same message.
utils.BurnPasswordComparison(req.Password)
- utils.Unauthorized(c, "invalid email or password")
+ utils.Unauthorized(c, "Invalid email or password.")
return
}
if utils.DBError(c, err) {
return
}
if !utils.CheckPassword(req.Password, user.Password) {
- utils.Unauthorized(c, "invalid email or password")
+ utils.Unauthorized(c, "Invalid email or password.")
return
}
@@ -161,7 +160,7 @@ func (h *Handler) ChangePassword(c *gin.Context) {
var req models.ChangePasswordRequest
if err := c.ShouldBindJSON(&req); err != nil {
- utils.BadRequest(c, err.Error())
+ utils.BadRequest(c, utils.BindMessage(err))
return
}
if err := validate.Struct(req); err != nil {
@@ -173,7 +172,7 @@ func (h *Handler) ChangePassword(c *gin.Context) {
// token was minted would otherwise resolve to the wrong row or to none at all.
user, err := h.s.User.GetByID(uid)
if err == sql.ErrNoRows {
- utils.Unauthorized(c, "account no longer exists")
+ utils.Unauthorized(c, "That account no longer exists.")
return
}
if utils.DBError(c, err) {
@@ -181,14 +180,14 @@ func (h *Handler) ChangePassword(c *gin.Context) {
}
if !utils.CheckPassword(req.CurrentPassword, user.Password) {
- utils.Unauthorized(c, "current password is incorrect")
+ utils.Unauthorized(c, "Your current password is incorrect.")
return
}
// Rejected before hashing. Allowing it would burn a bcrypt round to no effect and,
// worse, still bump token_version — signing every other device out for a change
// that never happened.
if req.CurrentPassword == req.NewPassword {
- utils.BadRequest(c, "new password must be different from the current one")
+ utils.BadRequest(c, "Your new password must be different from your current one.")
return
}
@@ -205,7 +204,7 @@ func (h *Handler) ChangePassword(c *gin.Context) {
version, err := h.s.User.ChangePassword(uid, user.Password, newHash)
if errors.Is(err, stores.ErrPasswordChanged) {
- utils.Conflict(c, "password was changed elsewhere, please try again")
+ utils.Conflict(c, "Your password was changed elsewhere. Please try again.")
return
}
if utils.DBError(c, err) {
@@ -216,7 +215,7 @@ func (h *Handler) ChangePassword(c *gin.Context) {
if err != nil {
// The password did change — reporting a failure here would send the user off to
// retry with a password that no longer works. Say what happened instead.
- utils.Unauthorized(c, "password changed, please sign in again")
+ utils.Unauthorized(c, "Your password changed. Please sign in again.")
return
}
@@ -226,13 +225,13 @@ func (h *Handler) ChangePassword(c *gin.Context) {
func (h *Handler) RefreshToken(c *gin.Context) {
var req models.RefreshRequest
if err := c.ShouldBindJSON(&req); err != nil {
- utils.BadRequest(c, err.Error())
+ utils.BadRequest(c, utils.BindMessage(err))
return
}
claims, err := utils.ValidateToken(req.RefreshToken)
if err != nil || claims.Type != "refresh" {
- utils.Unauthorized(c, "invalid refresh token")
+ utils.Unauthorized(c, "Your session isn't valid. Please sign in again.")
return
}
@@ -243,14 +242,14 @@ func (h *Handler) RefreshToken(c *gin.Context) {
// fresh access tokens for a month.
current, err := h.s.User.TokenVersion(claims.UserID)
if err == sql.ErrNoRows {
- utils.Unauthorized(c, "invalid refresh token")
+ utils.Unauthorized(c, "Your session isn't valid. Please sign in again.")
return
}
if utils.DBError(c, err) {
return
}
if utils.NormalizeTokenVersion(claims.TokenVersion) != current {
- utils.Unauthorized(c, "session expired, please sign in again")
+ utils.Unauthorized(c, "Your session expired. Please sign in again.")
return
}
diff --git a/backend/controllers/exercises.go b/backend/controllers/exercises.go
index f23c6db..167bba8 100644
--- a/backend/controllers/exercises.go
+++ b/backend/controllers/exercises.go
@@ -35,12 +35,12 @@ func (h *Handler) ListExercises(c *gin.Context) {
func (h *Handler) GetExercise(c *gin.Context) {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
- utils.BadRequest(c, "invalid exercise id")
+ utils.BadRequest(c, "That exercise id isn't valid.")
return
}
e, err := h.s.Exercise.Get(id)
if err == sql.ErrNoRows {
- utils.NotFound(c, "exercise not found")
+ utils.NotFound(c, "That exercise no longer exists.")
return
}
if utils.DBError(c, err) {
@@ -53,7 +53,7 @@ func (h *Handler) GetExercisePRs(c *gin.Context) {
uid := middleware.UserID(c)
exerciseID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
- utils.BadRequest(c, "invalid exercise id")
+ utils.BadRequest(c, "That exercise id isn't valid.")
return
}
pr, err := h.s.Workout.PRForExercise(uid, exerciseID)
@@ -77,7 +77,7 @@ func (h *Handler) GetExerciseHistory(c *gin.Context) {
uid := middleware.UserID(c)
exerciseID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
- utils.BadRequest(c, "invalid exercise id")
+ utils.BadRequest(c, "That exercise id isn't valid.")
return
}
limit := 20
@@ -100,11 +100,11 @@ func (h *Handler) GetExerciseHistory(c *gin.Context) {
func (h *Handler) RefreshExerciseCache(c *gin.Context) {
n, err := h.s.Exercise.RefreshCached(c.Request.Context())
if errors.Is(err, stores.ErrNoCatalog) {
- utils.BadRequest(c, "no exercise catalog configured")
+ utils.BadRequest(c, "This server has no exercise catalog configured.")
return
}
if err != nil {
- utils.BadRequest(c, err.Error())
+ utils.BadRequest(c, utils.BindMessage(err))
return
}
utils.OK(c, gin.H{"refreshed": n})
diff --git a/backend/controllers/food.go b/backend/controllers/food.go
index fed7f1e..992d82d 100644
--- a/backend/controllers/food.go
+++ b/backend/controllers/food.go
@@ -33,7 +33,7 @@ func (h *Handler) ListFoodLogs(c *gin.Context) {
// only to answer "what is today" when the parameter is omitted.
date, ok := h.resolveQueryDay(uid, c.Query("date"))
if !ok {
- utils.BadRequest(c, "date must be YYYY-MM-DD")
+ utils.BadRequest(c, "Date must be in YYYY-MM-DD format.")
return
}
logs, err := h.s.Food.ListByDay(uid, date)
@@ -43,18 +43,17 @@ func (h *Handler) ListFoodLogs(c *gin.Context) {
utils.OK(c, logs)
}
-
func (h *Handler) GetFoodLog(c *gin.Context) {
uid := middleware.UserID(c)
lid, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
- utils.BadRequest(c, "invalid id")
+ utils.BadRequest(c, "That id isn't valid.")
return
}
f, err := h.s.Food.Get(uid, lid)
if err == sql.ErrNoRows {
- utils.NotFound(c, "log entry not found")
+ utils.NotFound(c, "That entry no longer exists.")
return
}
if utils.DBError(c, err) {
@@ -67,7 +66,7 @@ func (h *Handler) LogFood(c *gin.Context) {
uid := middleware.UserID(c)
var req models.LogFoodRequest
if err := c.ShouldBindJSON(&req); err != nil {
- utils.BadRequest(c, err.Error())
+ utils.BadRequest(c, utils.BindMessage(err))
return
}
// Same normalisation the favourites path applies, and for a reason that only exists
@@ -82,23 +81,23 @@ func (h *Handler) LogFood(c *gin.Context) {
return
}
if len(req.Name) > 200 {
- utils.BadRequest(c, "name exceeds 200 characters")
+ utils.BadRequest(c, "Name must be 200 characters or fewer.")
return
}
if len(req.Brand) > 200 {
- utils.BadRequest(c, "brand exceeds 200 characters")
+ utils.BadRequest(c, "Brand must be 200 characters or fewer.")
return
}
if len(req.ServingSize) > 100 {
- utils.BadRequest(c, "serving_size exceeds 100 characters")
+ utils.BadRequest(c, "Serving size must be 100 characters or fewer.")
return
}
if len(req.Barcode) > 50 {
- utils.BadRequest(c, "barcode exceeds 50 characters")
+ utils.BadRequest(c, "Barcode must be 50 characters or fewer.")
return
}
if len(req.ImageURL) > 500 {
- utils.BadRequest(c, "image_url exceeds 500 characters")
+ utils.BadRequest(c, "Image URL must be 500 characters or fewer.")
return
}
@@ -109,7 +108,7 @@ func (h *Handler) LogFood(c *gin.Context) {
day, ok := h.resolveDay(uid, req.LoggedOn, req.LoggedAt)
if !ok {
- utils.BadRequest(c, "logged_on must be YYYY-MM-DD")
+ utils.BadRequest(c, "Logged on must be in YYYY-MM-DD format.")
return
}
@@ -124,13 +123,13 @@ func (h *Handler) UpdateFoodLog(c *gin.Context) {
uid := middleware.UserID(c)
lid, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
- utils.BadRequest(c, "invalid id")
+ utils.BadRequest(c, "That id isn't valid.")
return
}
var req models.LogFoodRequest
if err := c.ShouldBindJSON(&req); err != nil {
- utils.BadRequest(c, err.Error())
+ utils.BadRequest(c, utils.BindMessage(err))
return
}
// Same normalisation the favourites path applies, and for a reason that only exists
@@ -145,23 +144,23 @@ func (h *Handler) UpdateFoodLog(c *gin.Context) {
return
}
if len(req.Name) > 200 {
- utils.BadRequest(c, "name exceeds 200 characters")
+ utils.BadRequest(c, "Name must be 200 characters or fewer.")
return
}
if len(req.Brand) > 200 {
- utils.BadRequest(c, "brand exceeds 200 characters")
+ utils.BadRequest(c, "Brand must be 200 characters or fewer.")
return
}
if len(req.ServingSize) > 100 {
- utils.BadRequest(c, "serving_size exceeds 100 characters")
+ utils.BadRequest(c, "Serving size must be 100 characters or fewer.")
return
}
if len(req.Barcode) > 50 {
- utils.BadRequest(c, "barcode exceeds 50 characters")
+ utils.BadRequest(c, "Barcode must be 50 characters or fewer.")
return
}
if len(req.ImageURL) > 500 {
- utils.BadRequest(c, "image_url exceeds 500 characters")
+ utils.BadRequest(c, "Image URL must be 500 characters or fewer.")
return
}
req.LoggedAt = normalizeLoggedAt(req.LoggedAt)
@@ -171,13 +170,13 @@ func (h *Handler) UpdateFoodLog(c *gin.Context) {
day, ok := h.resolveDay(uid, req.LoggedOn, req.LoggedAt)
if !ok {
- utils.BadRequest(c, "logged_on must be YYYY-MM-DD")
+ utils.BadRequest(c, "Logged on must be in YYYY-MM-DD format.")
return
}
f, err := h.s.Food.Update(uid, lid, req, day)
if err == sql.ErrNoRows {
- utils.NotFound(c, "log entry not found")
+ utils.NotFound(c, "That entry no longer exists.")
return
}
if utils.DBError(c, err) {
@@ -190,7 +189,7 @@ func (h *Handler) DeleteFoodLog(c *gin.Context) {
uid := middleware.UserID(c)
lid, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
- utils.BadRequest(c, "invalid id")
+ utils.BadRequest(c, "That id isn't valid.")
return
}
@@ -199,7 +198,7 @@ func (h *Handler) DeleteFoodLog(c *gin.Context) {
return
}
if n == 0 {
- utils.NotFound(c, "log entry not found")
+ utils.NotFound(c, "That entry no longer exists.")
return
}
utils.OK(c, gin.H{"deleted": true})
@@ -209,7 +208,7 @@ func (h *Handler) GetDailyStats(c *gin.Context) {
uid := middleware.UserID(c)
date, ok := h.resolveQueryDay(uid, c.Query("date"))
if !ok {
- utils.BadRequest(c, "date must be YYYY-MM-DD")
+ utils.BadRequest(c, "Date must be in YYYY-MM-DD format.")
return
}
stats, err := h.s.Food.DailyMacros(uid, date)
@@ -323,7 +322,10 @@ func offProductToResult(p offProduct) models.FoodSearchResult {
carb = p.Nutriments.Carbohydrates100g
fat = p.Nutriments.Fat100g
fiber = p.Nutriments.Fiber100g
- servingLabel = "per 100g"
+ // "100 g", not "per 100g": the serving branch above passes through
+ // OpenFoodFacts' own label ("30 g", "250 ml"), which carries no preposition, and
+ // the clients supply the "per". Including it here produced "per per 100g".
+ servingLabel = "100 g"
}
return models.FoodSearchResult{
@@ -360,7 +362,7 @@ func doOFFRequest(ctx context.Context, rawURL string) ([]byte, int, error) {
func (h *Handler) SearchFood(c *gin.Context) {
q := c.Query("q")
if q == "" {
- utils.BadRequest(c, "q is required")
+ utils.BadRequest(c, "A search term is required.")
return
}
@@ -386,11 +388,11 @@ func (h *Handler) SearchFood(c *gin.Context) {
if err != nil {
if ctx.Err() == context.DeadlineExceeded {
log.Printf("[food/search] OFF timeout after %dms", elapsed.Milliseconds())
- utils.ServiceUnavailable(c, "food search timed out — try again")
+ utils.ServiceUnavailable(c, "The food database didn't respond in time. Try again.")
return
}
log.Printf("[food/search] OFF network error: %v", err)
- utils.ServiceUnavailable(c, "could not reach food database")
+ utils.ServiceUnavailable(c, "Couldn't reach the food database.")
return
}
@@ -398,15 +400,15 @@ func (h *Handler) SearchFood(c *gin.Context) {
case status == 429:
log.Printf("[food/search] OFF rate limit hit")
c.Header("Retry-After", "60")
- c.JSON(http.StatusTooManyRequests, gin.H{"error": "too many requests — wait a moment and try again"})
+ c.JSON(http.StatusTooManyRequests, gin.H{"error": "Too many requests. Wait a moment and try again."})
return
case status >= 500:
log.Printf("[food/search] OFF upstream error: %d", status)
- utils.ServiceUnavailable(c, "food search temporarily unavailable")
+ utils.ServiceUnavailable(c, "Food search is temporarily unavailable.")
return
case status != 200:
log.Printf("[food/search] OFF unexpected status: %d", status)
- utils.ServiceUnavailable(c, "food search temporarily unavailable")
+ utils.ServiceUnavailable(c, "Food search is temporarily unavailable.")
return
}
@@ -440,13 +442,13 @@ type offBarcodeResponse struct {
func (h *Handler) LookupBarcode(c *gin.Context) {
code := c.Param("code")
if code == "" {
- utils.BadRequest(c, "barcode is required")
+ utils.BadRequest(c, "A barcode is required.")
return
}
matched, err := regexp.MatchString(`^\d{6,14}$`, code)
if err != nil || !matched {
- utils.BadRequest(c, "Invalid barcode format")
+ utils.BadRequest(c, "That barcode isn't valid.")
return
}
@@ -464,11 +466,11 @@ func (h *Handler) LookupBarcode(c *gin.Context) {
if err != nil {
if ctx.Err() == context.DeadlineExceeded {
log.Printf("[food/barcode] OFF timeout after %dms", elapsed.Milliseconds())
- utils.ServiceUnavailable(c, "barcode lookup timed out — try again")
+ utils.ServiceUnavailable(c, "The food database didn't respond in time. Try again.")
return
}
log.Printf("[food/barcode] OFF network error: %v", err)
- utils.ServiceUnavailable(c, "could not reach food database")
+ utils.ServiceUnavailable(c, "Couldn't reach the food database.")
return
}
@@ -476,11 +478,11 @@ func (h *Handler) LookupBarcode(c *gin.Context) {
case status == 429:
log.Printf("[food/barcode] OFF rate limit hit")
c.Header("Retry-After", "60")
- c.JSON(http.StatusTooManyRequests, gin.H{"error": "too many requests — wait a moment and try again"})
+ c.JSON(http.StatusTooManyRequests, gin.H{"error": "Too many requests. Wait a moment and try again."})
return
case status >= 500:
log.Printf("[food/barcode] OFF upstream error: %d", status)
- utils.ServiceUnavailable(c, "barcode lookup temporarily unavailable")
+ utils.ServiceUnavailable(c, "Barcode lookup is temporarily unavailable.")
return
}
@@ -492,7 +494,7 @@ func (h *Handler) LookupBarcode(c *gin.Context) {
}
if !strings.HasPrefix(parsed.Status, "success") || parsed.Product.ProductName == "" {
- utils.NotFound(c, "product not found")
+ utils.NotFound(c, "No product matched that barcode.")
return
}
@@ -515,7 +517,7 @@ func (h *Handler) CreateSavedFood(c *gin.Context) {
uid := middleware.UserID(c)
var req models.SaveFoodRequest
if err := c.ShouldBindJSON(&req); err != nil {
- utils.BadRequest(c, err.Error())
+ utils.BadRequest(c, utils.BindMessage(err))
return
}
// Surrounding whitespace is not a distinguishing feature of a food:
@@ -531,19 +533,19 @@ func (h *Handler) CreateSavedFood(c *gin.Context) {
return
}
if len(req.Name) > 200 {
- utils.BadRequest(c, "name exceeds 200 characters")
+ utils.BadRequest(c, "Name must be 200 characters or fewer.")
return
}
if len(req.Brand) > 200 {
- utils.BadRequest(c, "brand exceeds 200 characters")
+ utils.BadRequest(c, "Brand must be 200 characters or fewer.")
return
}
if len(req.ServingSize) > 100 {
- utils.BadRequest(c, "serving_size exceeds 100 characters")
+ utils.BadRequest(c, "Serving size must be 100 characters or fewer.")
return
}
if len(req.Barcode) > 50 {
- utils.BadRequest(c, "barcode exceeds 50 characters")
+ utils.BadRequest(c, "Barcode must be 50 characters or fewer.")
return
}
@@ -571,7 +573,7 @@ func (h *Handler) DeleteSavedFood(c *gin.Context) {
uid := middleware.UserID(c)
fid, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
- utils.BadRequest(c, "invalid id")
+ utils.BadRequest(c, "That id isn't valid.")
return
}
@@ -580,7 +582,7 @@ func (h *Handler) DeleteSavedFood(c *gin.Context) {
return
}
if n == 0 {
- utils.NotFound(c, "saved food not found")
+ utils.NotFound(c, "That saved food no longer exists.")
return
}
utils.OK(c, gin.H{"deleted": true})
diff --git a/backend/controllers/food_test.go b/backend/controllers/food_test.go
index 2e3531d..ffe0f48 100644
--- a/backend/controllers/food_test.go
+++ b/backend/controllers/food_test.go
@@ -684,8 +684,10 @@ func TestOffProductToResult_fallsBackTo100g(t *testing.T) {
if r.Calories != 265 {
t.Errorf("expected per-100g calories 265, got %v", r.Calories)
}
- if r.ServingSize != "per 100g" {
- t.Errorf("expected 'per 100g' label, got %q", r.ServingSize)
+ // Without the preposition: the clients render "per {serving_size}", so a label of
+ // "per 100g" showed as "per per 100g". Seen in the browser on every search result.
+ if r.ServingSize != "100 g" {
+ t.Errorf("expected '100 g' label, got %q", r.ServingSize)
}
}
diff --git a/backend/controllers/message_voice_test.go b/backend/controllers/message_voice_test.go
new file mode 100644
index 0000000..c1da8fd
--- /dev/null
+++ b/backend/controllers/message_voice_test.go
@@ -0,0 +1,149 @@
+package controllers
+
+import (
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+ "unicode"
+)
+
+// Everything the API says lands in the same `error` field, and the client renders it
+// verbatim — apiErrorMessage prefers a server message over anything it would write
+// itself, because a server message is the most specific thing available. That makes
+// this copy the product's copy, not internal logging.
+//
+// validation.go has answered in sentences since it was written ("Calories must be a
+// number."). Every other handler answered in log lines ("workout not found"), so a
+// login form could show one of each, stacked. This pins the agreement rather than the
+// individual strings: a new handler is free to say anything, in this voice.
+//
+// Lives in controllers, not utils, because CI runs `go test ./controllers/ ./db/
+// ./routes/` — a guard in a package CI never runs is a guard that does not exist.
+
+var messageHelpers = map[string]bool{
+ "BadRequest": true,
+ "Unauthorized": true,
+ "Forbidden": true,
+ "NotFound": true,
+ "Conflict": true,
+ "ServiceUnavailable": true,
+}
+
+// backendRoot walks up from this package to the module root, so the scan covers
+// middleware and stores as well as controllers.
+func backendRoot(t *testing.T) string {
+ t.Helper()
+ wd, err := os.Getwd()
+ if err != nil {
+ t.Fatalf("getwd: %v", err)
+ }
+ return filepath.Dir(wd)
+}
+
+func checkSentence(t *testing.T, where, msg string, terminal bool) {
+ t.Helper()
+ if msg == "" {
+ return
+ }
+ if strings.TrimSpace(msg) != strings.TrimRight(msg, " ") {
+ t.Errorf("%s: %q has leading whitespace", where, msg)
+ }
+ if first := []rune(msg)[0]; !unicode.IsUpper(first) {
+ t.Errorf("%s: %q should start with a capital — it is shown to a person, not logged", where, msg)
+ }
+ if !terminal {
+ return
+ }
+ switch msg[len(msg)-1] {
+ case '.', '!', '?':
+ default:
+ t.Errorf("%s: %q should end in punctuation, like the validator's own messages", where, msg)
+ }
+}
+
+func TestEveryAPIMessageIsASentence(t *testing.T) {
+ root := backendRoot(t)
+ fset := token.NewFileSet()
+
+ err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
+ if err != nil {
+ return err
+ }
+ if info.IsDir() {
+ if name := info.Name(); name == "data" || strings.HasPrefix(name, ".") {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
+ return nil
+ }
+
+ file, perr := parser.ParseFile(fset, path, nil, 0)
+ if perr != nil {
+ return perr
+ }
+
+ ast.Inspect(file, func(n ast.Node) bool {
+ // const RegistrationClosedMessage = "..." — a message by another route.
+ if vs, ok := n.(*ast.ValueSpec); ok {
+ for i, name := range vs.Names {
+ if !strings.HasSuffix(name.Name, "Message") || i >= len(vs.Values) {
+ continue
+ }
+ if lit, ok := vs.Values[i].(*ast.BasicLit); ok && lit.Kind == token.STRING {
+ if s, e := strconv.Unquote(lit.Value); e == nil {
+ checkSentence(t, fset.Position(lit.Pos()).String(), s, true)
+ }
+ }
+ }
+ return true
+ }
+
+ call, ok := n.(*ast.CallExpr)
+ if !ok || len(call.Args) < 2 {
+ return true
+ }
+ switch fn := call.Fun.(type) {
+ case *ast.SelectorExpr: // utils.NotFound(c, "…")
+ if !messageHelpers[fn.Sel.Name] {
+ return true
+ }
+ case *ast.Ident: // inside package utils itself
+ if !messageHelpers[fn.Name] {
+ return true
+ }
+ default:
+ return true
+ }
+
+ pos := fset.Position(call.Pos()).String()
+ switch arg := call.Args[1].(type) {
+ case *ast.BasicLit:
+ if arg.Kind == token.STRING {
+ if s, e := strconv.Unquote(arg.Value); e == nil {
+ checkSentence(t, pos, s, true)
+ }
+ }
+ case *ast.BinaryExpr:
+ // "Unknown timezone: " + zone + "." — only the opening literal is fixed,
+ // so the capital is checkable and the full stop is not.
+ if lit, ok := arg.X.(*ast.BasicLit); ok && lit.Kind == token.STRING {
+ if s, e := strconv.Unquote(lit.Value); e == nil {
+ checkSentence(t, pos, s, false)
+ }
+ }
+ }
+ return true
+ })
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("walking backend: %v", err)
+ }
+}
diff --git a/backend/controllers/programs.go b/backend/controllers/programs.go
index 8279829..af85625 100644
--- a/backend/controllers/programs.go
+++ b/backend/controllers/programs.go
@@ -56,12 +56,12 @@ func (h *Handler) GetProgram(c *gin.Context) {
uid := middleware.UserID(c)
pid, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
- utils.BadRequest(c, "invalid program id")
+ utils.BadRequest(c, "That program id isn't valid.")
return
}
p, err := h.s.Program.Get(uid, pid)
if err == sql.ErrNoRows {
- utils.NotFound(c, "program not found")
+ utils.NotFound(c, "That program no longer exists.")
return
}
if utils.DBError(c, err) {
@@ -74,7 +74,7 @@ func (h *Handler) CreateProgram(c *gin.Context) {
uid := middleware.UserID(c)
var req models.CreateProgramRequest
if err := c.ShouldBindJSON(&req); err != nil {
- utils.BadRequest(c, err.Error())
+ utils.BadRequest(c, utils.BindMessage(err))
return
}
if err := validate.Struct(req); err != nil {
@@ -83,7 +83,7 @@ func (h *Handler) CreateProgram(c *gin.Context) {
}
p, err := h.s.Program.Create(uid, req)
if utils.IsForeignKeyViolation(err) {
- utils.BadRequest(c, "one or more exercises do not exist")
+ utils.BadRequest(c, "One or more of those exercises no longer exist.")
return
}
if utils.DBError(c, err) {
@@ -96,12 +96,12 @@ func (h *Handler) UpdateProgram(c *gin.Context) {
uid := middleware.UserID(c)
pid, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
- utils.BadRequest(c, "invalid program id")
+ utils.BadRequest(c, "That program id isn't valid.")
return
}
var req models.CreateProgramRequest
if err := c.ShouldBindJSON(&req); err != nil {
- utils.BadRequest(c, err.Error())
+ utils.BadRequest(c, utils.BindMessage(err))
return
}
if err := validate.Struct(req); err != nil {
@@ -110,11 +110,11 @@ func (h *Handler) UpdateProgram(c *gin.Context) {
}
p, err := h.s.Program.Update(uid, pid, req)
if err == sql.ErrNoRows {
- utils.NotFound(c, "program not found")
+ utils.NotFound(c, "That program no longer exists.")
return
}
if utils.IsForeignKeyViolation(err) {
- utils.BadRequest(c, "one or more exercises do not exist")
+ utils.BadRequest(c, "One or more of those exercises no longer exist.")
return
}
if utils.DBError(c, err) {
@@ -127,7 +127,7 @@ func (h *Handler) DeleteProgram(c *gin.Context) {
uid := middleware.UserID(c)
pid, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
- utils.BadRequest(c, "invalid program id")
+ utils.BadRequest(c, "That program id isn't valid.")
return
}
n, err := h.s.Program.Delete(uid, pid)
@@ -135,7 +135,7 @@ func (h *Handler) DeleteProgram(c *gin.Context) {
return
}
if n == 0 {
- utils.NotFound(c, "program not found")
+ utils.NotFound(c, "That program no longer exists.")
return
}
utils.OK(c, gin.H{"deleted": true})
@@ -147,12 +147,12 @@ func (h *Handler) ResolveSuggestions(c *gin.Context) {
uid := middleware.UserID(c)
pid, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
- utils.BadRequest(c, "invalid program id")
+ utils.BadRequest(c, "That program id isn't valid.")
return
}
var req models.ResolveSuggestionsReq
if err := c.ShouldBindJSON(&req); err != nil {
- utils.BadRequest(c, err.Error())
+ utils.BadRequest(c, utils.BindMessage(err))
return
}
if err := validate.Struct(req); err != nil {
@@ -161,7 +161,7 @@ func (h *Handler) ResolveSuggestions(c *gin.Context) {
}
p, err := h.s.Program.ResolveSuggestions(uid, pid, req.Accept, req.Dismiss)
if err == sql.ErrNoRows {
- utils.NotFound(c, "program not found")
+ utils.NotFound(c, "That program no longer exists.")
return
}
if utils.DBError(c, err) {
diff --git a/backend/controllers/user.go b/backend/controllers/user.go
index a0099c3..99cc77a 100644
--- a/backend/controllers/user.go
+++ b/backend/controllers/user.go
@@ -13,7 +13,7 @@ func (h *Handler) GetMe(c *gin.Context) {
uid := middleware.UserID(c)
u, err := h.s.User.GetMe(uid)
if err == sql.ErrNoRows {
- utils.Unauthorized(c, "account no longer exists")
+ utils.Unauthorized(c, "That account no longer exists.")
return
}
if utils.DBError(c, err) {
@@ -40,14 +40,14 @@ func (h *Handler) UpdateSettings(c *gin.Context) {
uid := middleware.UserID(c)
var req models.UpdateSettingsRequest
if err := c.ShouldBindJSON(&req); err != nil {
- utils.BadRequest(c, err.Error())
+ utils.BadRequest(c, utils.BindMessage(err))
return
}
// Enforce the request tags (weight_unit oneof, targets gte=0) like every other
// controller — binding alone doesn't run them, so without this an invalid unit
// or a negative target would be persisted unchecked.
if err := validate.Struct(req); err != nil {
- utils.BadRequest(c, err.Error())
+ utils.BadRequest(c, utils.BindMessage(err))
return
}
// A zone name is only valid if the runtime can load it, so check it here rather
@@ -60,11 +60,11 @@ func (h *Handler) UpdateSettings(c *gin.Context) {
// that silently reverts every day boundary to UTC — a 200 OK, a stored value
// that is neither null nor rejected, and nothing to point at afterwards.
if *req.Timezone == "" {
- utils.BadRequest(c, "timezone cannot be empty")
+ utils.BadRequest(c, "Timezone can't be empty.")
return
}
if _, err := ParseLocation(*req.Timezone); err != nil {
- utils.BadRequest(c, "unknown timezone: "+*req.Timezone)
+ utils.BadRequest(c, "Unknown timezone: "+*req.Timezone+".")
return
}
}
diff --git a/backend/controllers/weight.go b/backend/controllers/weight.go
index d86b9fb..89060b1 100644
--- a/backend/controllers/weight.go
+++ b/backend/controllers/weight.go
@@ -34,7 +34,7 @@ func (h *Handler) ListWeightLogs(c *gin.Context) {
if from := c.Query("from"); from != "" {
day, ok := h.resolveQueryDay(uid, from)
if !ok {
- utils.BadRequest(c, "from must be YYYY-MM-DD")
+ utils.BadRequest(c, "From must be in YYYY-MM-DD format.")
return
}
f.FromDay = &day
@@ -42,7 +42,7 @@ func (h *Handler) ListWeightLogs(c *gin.Context) {
if to := c.Query("to"); to != "" {
day, ok := h.resolveQueryDay(uid, to)
if !ok {
- utils.BadRequest(c, "to must be YYYY-MM-DD")
+ utils.BadRequest(c, "To must be in YYYY-MM-DD format.")
return
}
f.ToDay = &day
@@ -59,7 +59,7 @@ func (h *Handler) LogWeight(c *gin.Context) {
uid := middleware.UserID(c)
var req models.LogWeightRequest
if err := c.ShouldBindJSON(&req); err != nil {
- utils.BadRequest(c, err.Error())
+ utils.BadRequest(c, utils.BindMessage(err))
return
}
if err := validate.Struct(req); err != nil {
@@ -70,7 +70,7 @@ func (h *Handler) LogWeight(c *gin.Context) {
day, ok := h.resolveDay(uid, req.LoggedOn, req.LoggedAt)
if !ok {
- utils.BadRequest(c, "logged_on must be YYYY-MM-DD")
+ utils.BadRequest(c, "Logged on must be in YYYY-MM-DD format.")
return
}
log, err := h.s.Weight.UpsertForDay(uid, req, day)
@@ -84,12 +84,12 @@ func (h *Handler) GetWeightLog(c *gin.Context) {
uid := middleware.UserID(c)
lid, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
- utils.BadRequest(c, "invalid id")
+ utils.BadRequest(c, "That id isn't valid.")
return
}
log, err := h.s.Weight.Get(uid, lid)
if err == sql.ErrNoRows {
- utils.NotFound(c, "log entry not found")
+ utils.NotFound(c, "That entry no longer exists.")
return
}
if utils.DBError(c, err) {
@@ -102,12 +102,12 @@ func (h *Handler) UpdateWeightLog(c *gin.Context) {
uid := middleware.UserID(c)
lid, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
- utils.BadRequest(c, "invalid id")
+ utils.BadRequest(c, "That id isn't valid.")
return
}
var req models.LogWeightRequest
if err := c.ShouldBindJSON(&req); err != nil {
- utils.BadRequest(c, err.Error())
+ utils.BadRequest(c, utils.BindMessage(err))
return
}
if err := validate.Struct(req); err != nil {
@@ -118,12 +118,12 @@ func (h *Handler) UpdateWeightLog(c *gin.Context) {
day, ok := h.resolveDay(uid, req.LoggedOn, req.LoggedAt)
if !ok {
- utils.BadRequest(c, "logged_on must be YYYY-MM-DD")
+ utils.BadRequest(c, "Logged on must be in YYYY-MM-DD format.")
return
}
log, err := h.s.Weight.Update(uid, lid, req, day)
if err == sql.ErrNoRows {
- utils.NotFound(c, "log entry not found")
+ utils.NotFound(c, "That entry no longer exists.")
return
}
if utils.DBError(c, err) {
@@ -136,7 +136,7 @@ func (h *Handler) DeleteWeightLog(c *gin.Context) {
uid := middleware.UserID(c)
lid, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
- utils.BadRequest(c, "invalid id")
+ utils.BadRequest(c, "That id isn't valid.")
return
}
n, err := h.s.Weight.Delete(uid, lid)
@@ -144,7 +144,7 @@ func (h *Handler) DeleteWeightLog(c *gin.Context) {
return
}
if n == 0 {
- utils.NotFound(c, "log entry not found")
+ utils.NotFound(c, "That entry no longer exists.")
return
}
utils.OK(c, gin.H{"deleted": true})
diff --git a/backend/controllers/workouts.go b/backend/controllers/workouts.go
index a95b1be..132c5da 100644
--- a/backend/controllers/workouts.go
+++ b/backend/controllers/workouts.go
@@ -51,12 +51,12 @@ func (h *Handler) GetWorkout(c *gin.Context) {
uid := middleware.UserID(c)
wid, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
- utils.BadRequest(c, "invalid workout id")
+ utils.BadRequest(c, "That workout id isn't valid.")
return
}
w, err := h.s.Workout.Get(uid, wid)
if err == sql.ErrNoRows {
- utils.NotFound(c, "workout not found")
+ utils.NotFound(c, "That workout no longer exists.")
return
}
if utils.DBError(c, err) {
@@ -69,7 +69,7 @@ func (h *Handler) CreateWorkout(c *gin.Context) {
uid := middleware.UserID(c)
var req models.CreateWorkoutRequest
if err := c.ShouldBindJSON(&req); err != nil {
- utils.BadRequest(c, err.Error())
+ utils.BadRequest(c, utils.BindMessage(err))
return
}
if err := validate.Struct(req); err != nil {
@@ -96,7 +96,7 @@ func (h *Handler) CreateWorkout(c *gin.Context) {
// never fails the already-saved workout.
w, progression, err := h.s.CreateWorkoutWithProgression(uid, req)
if utils.IsForeignKeyViolation(err) {
- utils.BadRequest(c, "one or more exercises do not exist")
+ utils.BadRequest(c, "One or more of those exercises no longer exist.")
return
}
if utils.DBError(c, err) {
@@ -110,12 +110,12 @@ func (h *Handler) UpdateWorkout(c *gin.Context) {
uid := middleware.UserID(c)
wid, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
- utils.BadRequest(c, "invalid workout id")
+ utils.BadRequest(c, "That workout id isn't valid.")
return
}
var req models.CreateWorkoutRequest
if err := c.ShouldBindJSON(&req); err != nil {
- utils.BadRequest(c, err.Error())
+ utils.BadRequest(c, utils.BindMessage(err))
return
}
if err := validate.Struct(req); err != nil {
@@ -138,11 +138,11 @@ func (h *Handler) UpdateWorkout(c *gin.Context) {
}
w, err := h.s.Workout.Update(uid, wid, req)
if err == sql.ErrNoRows {
- utils.NotFound(c, "workout not found")
+ utils.NotFound(c, "That workout no longer exists.")
return
}
if utils.IsForeignKeyViolation(err) {
- utils.BadRequest(c, "one or more exercises do not exist")
+ utils.BadRequest(c, "One or more of those exercises no longer exist.")
return
}
if utils.DBError(c, err) {
@@ -155,7 +155,7 @@ func (h *Handler) DeleteWorkout(c *gin.Context) {
uid := middleware.UserID(c)
wid, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
- utils.BadRequest(c, "invalid workout id")
+ utils.BadRequest(c, "That workout id isn't valid.")
return
}
n, err := h.s.Workout.Delete(uid, wid)
@@ -163,7 +163,7 @@ func (h *Handler) DeleteWorkout(c *gin.Context) {
return
}
if n == 0 {
- utils.NotFound(c, "workout not found")
+ utils.NotFound(c, "That workout no longer exists.")
return
}
utils.OK(c, gin.H{"deleted": true})
diff --git a/backend/go.mod b/backend/go.mod
index ea65940..66a79be 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -5,6 +5,8 @@ go 1.26.6
require (
github.com/gin-contrib/cors v1.7.7
github.com/gin-gonic/gin v1.12.0
+ github.com/go-playground/locales v0.14.1
+ github.com/go-playground/universal-translator v0.18.1
github.com/go-playground/validator/v10 v10.30.2
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/joho/godotenv v1.5.1
@@ -21,8 +23,6 @@ require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
- github.com/go-playground/locales v0.14.1 // indirect
- github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect
github.com/google/uuid v1.6.0 // indirect
diff --git a/backend/middleware/auth.go b/backend/middleware/auth.go
index 6ccfc8b..8cfe745 100644
--- a/backend/middleware/auth.go
+++ b/backend/middleware/auth.go
@@ -14,20 +14,20 @@ func Auth() gin.HandlerFunc {
return func(c *gin.Context) {
header := c.GetHeader("Authorization")
if !strings.HasPrefix(header, "Bearer ") {
- utils.Unauthorized(c, "missing or invalid authorization header")
+ utils.Unauthorized(c, "You need to sign in to do that.")
c.Abort()
return
}
claims, err := utils.ValidateToken(strings.TrimPrefix(header, "Bearer "))
if err != nil {
- utils.Unauthorized(c, "invalid or expired token")
+ utils.Unauthorized(c, "Your session isn't valid. Please sign in again.")
c.Abort()
return
}
if claims.Type != "access" {
- utils.Unauthorized(c, "invalid token type")
+ utils.Unauthorized(c, "That token can't be used here.")
c.Abort()
return
}
diff --git a/backend/stores/exercise.go b/backend/stores/exercise.go
index fcb7687..0a0458e 100644
--- a/backend/stores/exercise.go
+++ b/backend/stores/exercise.go
@@ -301,11 +301,11 @@ func (s *ExerciseStore) fetchCatalog(ctx context.Context, f ExerciseFilter) ([]o
}
// with no upstream configured.
-var errNoCatalog = errors.New("no exercise catalog configured")
+var errNoCatalog = errors.New("This server has no exercise catalog configured.")
// ErrNoCatalog is returned by the cache-management operations on an instance with
// no upstream configured.
-var ErrNoCatalog = errors.New("no exercise catalog configured")
+var ErrNoCatalog = errors.New("This server has no exercise catalog configured.")
// CachedCount reports how many catalog rows this instance currently holds.
//
diff --git a/backend/utils/dberr.go b/backend/utils/dberr.go
index e806217..916d6fe 100644
--- a/backend/utils/dberr.go
+++ b/backend/utils/dberr.go
@@ -70,7 +70,7 @@ func DBError(c *gin.Context, err error) bool {
}
if IsLocked(err) {
log.Printf("db locked on %s %s: %v", c.Request.Method, c.Request.URL.Path, err)
- ServiceUnavailable(c, "the database is busy, please try again in a moment")
+ ServiceUnavailable(c, "The database is busy. Try again in a moment.")
return true
}
log.Printf("db error on %s %s: %v", c.Request.Method, c.Request.URL.Path, err)
diff --git a/backend/utils/password.go b/backend/utils/password.go
index 3d75ad9..2aadd25 100644
--- a/backend/utils/password.go
+++ b/backend/utils/password.go
@@ -22,7 +22,7 @@ func PasswordTooLong(plain string) bool {
// PasswordTooLongMessage is the one wording for the limit, so the two handlers and the
// reset-password command cannot describe it differently.
-const PasswordTooLongMessage = "password must be 72 bytes or fewer (accented letters and emoji count for more than one)"
+const PasswordTooLongMessage = "Password must be 72 bytes or fewer — accented letters and emoji count for more than one."
func HashPassword(plain string) (string, error) {
b, err := bcrypt.GenerateFromPassword([]byte(plain), bcrypt.DefaultCost)
diff --git a/backend/utils/response.go b/backend/utils/response.go
index 18d5686..c5ef582 100644
--- a/backend/utils/response.go
+++ b/backend/utils/response.go
@@ -31,11 +31,13 @@ func NotFound(c *gin.Context, msg string) {
}
func InternalError(c *gin.Context) {
- c.JSON(http.StatusInternalServerError, gin.H{"error": "internal server error"})
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Something went wrong on the server."})
}
+// ValidationError reports a request whose fields broke a rule. The message is built
+// by validationMessage rather than taken from err.Error(), which is a Go struct dump.
func ValidationError(c *gin.Context, err error) {
- c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
+ c.JSON(http.StatusUnprocessableEntity, gin.H{"error": validationMessage(err)})
}
func Conflict(c *gin.Context, msg string) {
diff --git a/backend/utils/validation.go b/backend/utils/validation.go
new file mode 100644
index 0000000..dcf442a
--- /dev/null
+++ b/backend/utils/validation.go
@@ -0,0 +1,207 @@
+package utils
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "reflect"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/Cawlumm/lyftr-backend/models"
+ "github.com/go-playground/locales/en"
+ ut "github.com/go-playground/universal-translator"
+ "github.com/go-playground/validator/v10"
+ entrans "github.com/go-playground/validator/v10/translations/en"
+)
+
+// One place that turns a rejected request into a sentence a person can act on.
+//
+// Before this, handlers passed the raw Go error straight to the client, and the client
+// faithfully rendered it — apiErrorMessage prefers the server's message over anything it
+// would write itself, which is correct and is exactly why this mattered. Someone who
+// mistyped their email during sign-up was shown:
+//
+// Key: 'RegisterRequest.Email' Error:Field validation for 'Email' failed on the 'email' tag
+//
+// That is a struct dump. It names a Go type the user has never heard of, says "tag", and
+// does not say what to do. The client cannot rescue it: a message from the server is the
+// most specific thing available, so the client is right to trust it. The fix has to be
+// here, at the point where we know what the rule actually was.
+//
+// The mirror of packages/shared/src/utils/networkError.ts, which owns the half of this the
+// server can never answer: a request that never arrived has no server-side story at all.
+
+// The library ships the sentences. go-playground/validator carries an English translation
+// for every one of its own tags, so a rule nobody here has thought about still comes out as
+// a sentence — where the hand-written switch this replaced fell through to "X isn't valid."
+// universal-translator and locales were already in go.sum as indirect dependencies of the
+// validator itself, so this adds nothing to the module graph.
+var translator = func() ut.Translator {
+ locale := en.New()
+ t, _ := ut.New(locale, locale).GetTranslator("en")
+ return t
+}()
+
+// NewValidator returns the validator every handler shares, reporting fields by a readable
+// name rather than their Go one. Without this the messages would say "CalorieTarget" — a
+// name that appears nowhere in the API, the docs, or the app — and the library's own
+// sentences would read "calorie_target must be 0 or greater", underscore and all.
+// NewValidator returns that shared instance. It is built once: RegisterDefaultTranslations
+// writes into the translator above, so a second call registers the same keys again and the
+// library rejects them — "conflicting key 'required'". The doc comment already said every
+// handler shares one validator; this makes the code say it too.
+func NewValidator() *validator.Validate { return shared() }
+
+var shared = sync.OnceValue(func() *validator.Validate {
+ v := validator.New()
+ v.RegisterTagNameFunc(func(f reflect.StructField) string {
+ name := strings.SplitN(f.Tag.Get("json"), ",", 2)[0]
+ if name == "" || name == "-" {
+ return "" // the validator falls back to the Go field name
+ }
+ return label(name)
+ })
+ if err := entrans.RegisterDefaultTranslations(v, translator); err != nil {
+ // Only reachable if the library's own translation table is malformed. Failing at
+ // construction is right: the alternative is every rejected request answering with
+ // the struct dump this file exists to prevent.
+ panic("validator: registering English translations: " + err.Error())
+ }
+
+ // The default renders the options as a Go slice — "must be one of [breakfast lunch
+ // dinner snack]", brackets and all.
+ translate(v, "oneof", "{0} must be one of: {1}", func(fe validator.FieldError) []string {
+ return []string{fe.Field(), strings.ReplaceAll(fe.Param(), " ", ", ")}
+ })
+
+ // Struct-level tags are ours, so their sentences have to be too. Without these,
+ // Translate falls through to fe.Error() — see sentenceFor.
+ translate(v, "maxtotalrows", fmt.Sprintf("A program can't have more than %d days, exercises and sets combined.", models.MaxProgramRows), nil)
+ translate(v, "maxtotalsets", fmt.Sprintf("A workout can't have more than %d sets.", models.MaxWorkoutSets), nil)
+
+ return v
+})
+
+// translate registers one override. args picks what fills {0}, {1}…; nil means the text
+// stands alone.
+func translate(v *validator.Validate, tag, text string, args func(validator.FieldError) []string) {
+ _ = v.RegisterTranslation(tag, translator,
+ func(t ut.Translator) error { return t.Add(tag, text, true) },
+ func(t ut.Translator, fe validator.FieldError) string {
+ var params []string
+ if args != nil {
+ params = args(fe)
+ }
+ out, err := t.T(tag, params...)
+ if err != nil {
+ return fe.Field() + " isn't valid."
+ }
+ return out
+ })
+}
+
+// label turns a JSON field name into something readable at the start of a sentence:
+// "calorie_target" -> "Calorie target".
+func label(field string) string {
+ spaced := strings.ReplaceAll(field, "_", " ")
+ return strings.ToUpper(spaced[:1]) + spaced[1:]
+}
+
+// sentenceFor renders one failed rule, and guards the one way translations can regress on
+// the switch they replaced: Translate returns fe.Error() verbatim for a tag with no
+// translation registered, and fe.Error() is the struct dump. A future custom tag would leak
+// it silently, so an untranslated tag is answered here the way the old default case did —
+// true and useless, never a Go type name.
+//
+// The full stop is added here rather than baked into each template because validationMessage
+// joins every failed rule with a space, and the library's English messages carry no
+// terminal punctuation.
+func sentenceFor(fe validator.FieldError) string {
+ msg := fe.Translate(translator)
+ if msg == "" || msg == fe.Error() {
+ return fe.Field() + " isn't valid."
+ }
+ if last := msg[len(msg)-1]; last == '.' || last == '!' || last == '?' {
+ return msg
+ }
+ return msg + "."
+}
+
+// validationMessage renders a validator failure. Every failed rule is reported, not just
+// the first: a sign-up form with a bad email AND a short password should say both, or the
+// user fixes one and gets turned away again.
+func validationMessage(err error) string {
+ var fieldErrs validator.ValidationErrors
+ if !errors.As(err, &fieldErrs) || len(fieldErrs) == 0 {
+ return "Some of the details you entered aren't valid."
+ }
+ parts := make([]string, 0, len(fieldErrs))
+ for _, e := range fieldErrs {
+ parts = append(parts, sentenceFor(e))
+ }
+ return strings.Join(parts, " ")
+}
+
+// shapeName says what a field wanted in words a person can act on. typeErr.Type is a Go
+// type, and printing it put "expected float64" in front of someone logging a meal — the
+// same leak this file exists to stop, one size smaller and past a test that only checked
+// for the name of the *error* type. Empty means we have no better word than "wrong type".
+func shapeName(t reflect.Type) string {
+ for t.Kind() == reflect.Ptr {
+ t = t.Elem()
+ }
+ if t == reflect.TypeOf(time.Time{}) {
+ return "a date"
+ }
+ switch t.Kind() {
+ case reflect.Bool:
+ return "true or false"
+ case reflect.String:
+ return "text"
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
+ reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
+ reflect.Float32, reflect.Float64:
+ return "a number"
+ case reflect.Slice, reflect.Array:
+ return "a list"
+ case reflect.Map, reflect.Struct:
+ return "an object"
+ }
+ return ""
+}
+
+// BindMessage renders a request body we could not read at all. These are not user
+// mistakes so much as client bugs or truncated uploads, but the person holding the phone
+// still has to be told something — and "unexpected EOF" is not it.
+func BindMessage(err error) string {
+ var typeErr *json.UnmarshalTypeError
+ if errors.As(err, &typeErr) {
+ if typeErr.Field != "" {
+ if want := shapeName(typeErr.Type); want != "" {
+ return fmt.Sprintf("%s must be %s.", label(typeErr.Field), want)
+ }
+ return fmt.Sprintf("%s has the wrong type.", label(typeErr.Field))
+ }
+ return "The request body had a field of the wrong type."
+ }
+
+ var syntaxErr *json.SyntaxError
+ if errors.As(err, &syntaxErr) || errors.Is(err, io.ErrUnexpectedEOF) {
+ return "The request body wasn't valid JSON."
+ }
+
+ if errors.Is(err, io.EOF) {
+ return "The request body was empty."
+ }
+
+ // gin also surfaces validator failures through Bind when binding tags are used.
+ var fieldErrs validator.ValidationErrors
+ if errors.As(err, &fieldErrs) {
+ return validationMessage(err)
+ }
+
+ return "The request couldn't be read."
+}
diff --git a/backend/utils/validation_test.go b/backend/utils/validation_test.go
new file mode 100644
index 0000000..9656a55
--- /dev/null
+++ b/backend/utils/validation_test.go
@@ -0,0 +1,223 @@
+package utils
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/go-playground/validator/v10"
+)
+
+// The rule these all serve: whatever we put in "error" is read by a person, because the
+// clients prefer the server's message over anything they would write themselves. Anything
+// that names a Go type, a struct field, or a validator tag has escaped from the wrong side
+// of the boundary.
+type signup struct {
+ Email string `json:"email" validate:"required,email"`
+ Password string `json:"password" validate:"required,min=8"`
+}
+
+type entry struct {
+ Meal string `json:"meal" validate:"required,oneof=breakfast lunch dinner snacks"`
+ Calories float64 `json:"calories" validate:"gte=0"`
+ Servings float64 `json:"servings" validate:"gt=0,lte=2000"`
+ Note string `json:"note" validate:"max=500"`
+}
+
+func messageFor(t *testing.T, v any) string {
+ t.Helper()
+ err := NewValidator().Struct(v)
+ if err == nil {
+ t.Fatal("expected the struct to fail validation")
+ }
+ return validationMessage(err)
+}
+
+func TestValidationMessageNeverLeaksTheStructDump(t *testing.T) {
+ msg := messageFor(t, signup{Email: "notanemail", Password: "abc"})
+
+ for _, leak := range []string{"Key:", "Error:Field validation", "tag", "signup", "Email'"} {
+ if strings.Contains(msg, leak) {
+ t.Fatalf("message leaks internals (%q): %s", leak, msg)
+ }
+ }
+}
+
+func TestValidationMessageUsesJSONFieldNames(t *testing.T) {
+ // The Go field is CalorieTarget-style; the name a user has ever seen is the JSON one.
+ type settings struct {
+ CalorieTarget int `json:"calorie_target" validate:"required"`
+ }
+ msg := messageFor(t, settings{})
+
+ if msg != "Calorie target is a required field." {
+ t.Fatalf("got %q", msg)
+ }
+}
+
+// A sign-up with two problems should say both. Reporting only the first means the user
+// fixes it, submits again, and is turned away a second time for something we already knew.
+func TestValidationMessageReportsEveryFailedRule(t *testing.T) {
+ msg := messageFor(t, signup{Email: "notanemail", Password: "abc"})
+
+ if !strings.Contains(msg, "Email must be a valid email address.") {
+ t.Fatalf("missing the email sentence: %s", msg)
+ }
+ if !strings.Contains(msg, "Password must be at least 8 characters in length.") {
+ t.Fatalf("missing the password sentence: %s", msg)
+ }
+}
+
+// Most of these sentences are the library's, not ours — pinned so a validator upgrade
+// cannot quietly reword what a user reads. The oneof case is ours: the default renders the
+// options as a Go slice.
+func TestValidationMessagePerTag(t *testing.T) {
+ cases := []struct {
+ name string
+ in any
+ want string
+ }{
+ {"required", signup{Password: "longenough"}, "Email is a required field."},
+ {"email", signup{Email: "nope", Password: "longenough"}, "Email must be a valid email address."},
+ {"min on a string counts characters", signup{Email: "[email protected]", Password: "short"}, "Password must be at least 8 characters in length."},
+ {"oneof lists the options", entry{Meal: "brunch", Servings: 1}, "Meal must be one of: breakfast, lunch, dinner, snacks."},
+ {"gte=0 reads as a floor", entry{Meal: "lunch", Calories: -5, Servings: 1}, "Calories must be 0 or greater."},
+ {"gt=0 excludes the floor", entry{Meal: "lunch", Servings: 0}, "Servings must be greater than 0."},
+ {"lte gives the ceiling", entry{Meal: "lunch", Servings: 5000}, "Servings must be 2,000 or less."},
+ {"max on a string counts characters", entry{Meal: "lunch", Servings: 1, Note: strings.Repeat("x", 501)}, "Note must be a maximum of 500 characters in length."},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := messageFor(t, tc.in); got != tc.want {
+ t.Fatalf("got %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+// Not a validator failure at all — a body we could not decode. "unexpected EOF" is the Go
+// runtime talking to itself.
+func TestBindMessage(t *testing.T) {
+ var target signup
+
+ cases := []struct {
+ name string
+ body string
+ want string
+ }{
+ {"truncated", `{"email":`, "The request body wasn't valid JSON."},
+ {"garbage", `not json at all`, "The request body wasn't valid JSON."},
+ {"empty", ``, "The request body was empty."},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ err := json.Unmarshal([]byte(tc.body), &target)
+ if tc.body == "" {
+ err = json.NewDecoder(strings.NewReader("")).Decode(&target)
+ }
+ if err == nil {
+ t.Fatal("expected a decode error")
+ }
+ if got := BindMessage(err); got != tc.want {
+ t.Fatalf("got %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+// The field is named, and the SHAPE it wanted is said in English. The previous version of
+// this test only rejected "UnmarshalTypeError" — the name of the error type — which is why
+// "expected float64" reached users unnoticed. Go type names are checked for explicitly now.
+func TestBindMessageNamesTheFieldWithTheWrongType(t *testing.T) {
+ cases := []struct {
+ name string
+ into any
+ body string
+ want string
+ }{
+ {"number", &struct {
+ Calories float64 `json:"calories"`
+ }{}, `{"calories":"lots"}`, "Calories must be a number."},
+ {"text", &struct {
+ Name string `json:"name"`
+ }{}, `{"name":12}`, "Name must be text."},
+ {"boolean", &struct {
+ IsWarmup bool `json:"is_warmup"`
+ }{}, `{"is_warmup":"yes"}`, "Is warmup must be true or false."},
+ {"list", &struct {
+ Sets []int `json:"sets"`
+ }{}, `{"sets":3}`, "Sets must be a list."},
+ {"pointer is followed", &struct {
+ ProgramID *int64 `json:"program_id"`
+ }{}, `{"program_id":"seven"}`, "Program id must be a number."},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ err := json.Unmarshal([]byte(tc.body), tc.into)
+ if err == nil {
+ t.Fatal("expected a type error")
+ }
+ got := BindMessage(err)
+ if got != tc.want {
+ t.Fatalf("got %q, want %q", got, tc.want)
+ }
+ for _, goName := range []string{"float64", "int64", "int", "string", "bool", "[]", "*", "UnmarshalTypeError"} {
+ if strings.Contains(got, goName) {
+ t.Fatalf("leaks the Go type %q: %s", goName, got)
+ }
+ }
+ })
+ }
+}
+
+// A tag nobody here has written a sentence for still reads as one — this is what moving to
+// the library's translations bought. Before, `alphanum` fell through to "Code isn't valid."
+func TestValidationMessageCoversTagsWeNeverWrote(t *testing.T) {
+ type odd struct {
+ Code string `json:"code" validate:"alphanum"`
+ }
+ msg := messageFor(t, odd{Code: "!!!"})
+
+ if msg != "Code can only contain alphanumeric characters." {
+ t.Fatalf("got %q", msg)
+ }
+}
+
+// The guard that keeps the whole file honest. Translate returns fe.Error() verbatim for a
+// tag with no translation — and fe.Error() is the struct dump this package exists to keep
+// out of a response. Struct-level tags are ours to register, so it is a live risk every
+// time someone adds one, not a theoretical branch.
+func TestValidationMessageNeverLeaksAnUntranslatedTag(t *testing.T) {
+ type custom struct {
+ Days int `json:"days" validate:"required"`
+ }
+ v := NewValidator()
+ v.RegisterStructValidation(func(sl validator.StructLevel) {
+ sl.ReportError(sl.Current().Interface().(custom).Days, "Days", "Days", "notranslationforthis", "")
+ }, custom{})
+
+ msg := validationMessage(v.Struct(custom{Days: 1}))
+
+ if strings.Contains(msg, "Key:") || strings.Contains(msg, "Error:Field validation") {
+ t.Fatalf("leaked the struct dump: %s", msg)
+ }
+ if msg != "Days isn't valid." {
+ t.Fatalf("got %q", msg)
+ }
+}
+
+// The two struct-level tags this repo actually registers get real sentences, from the same
+// limits the rules are built from.
+func TestValidationMessageTranslatesOurStructTags(t *testing.T) {
+ type capped struct {
+ Sets int `json:"sets" validate:"required"`
+ }
+ v := NewValidator()
+ v.RegisterStructValidation(func(sl validator.StructLevel) {
+ sl.ReportError(sl.Current().Interface().(capped).Sets, "Sets", "Sets", "maxtotalsets", "")
+ }, capped{})
+
+ if got := validationMessage(v.Struct(capped{Sets: 1})); got != "A workout can't have more than 500 sets." {
+ t.Fatalf("got %q", got)
+ }
+}