package auth import ( "encoding/json" "fmt" "io" "math" "net/http" "strings" "unicode/utf8" "github.com/gin-gonic/gin" "galo/internal/httpx" ) type Handler struct { svc *Service } func NewHandler(svc *Service) *Handler { return &Handler{svc: svc} } type registerRequest struct { Email string `json:"email"` Phone string `json:"phone"` Password string `json:"password" binding:"required"` Name string `json:"name" binding:"required"` } func (h *Handler) Register(c *gin.Context) { var req registerRequest if err := c.ShouldBindJSON(&req); err != nil { httpx.RespondError(c, httpx.BadRequest("invalid_request", "name and password are required")) return } u, pair, err := h.svc.Register(c.Request.Context(), req.Email, req.Phone, req.Password, req.Name) if err != nil { httpx.RespondError(c, err) return } c.JSON(http.StatusCreated, gin.H{"user": u.Self(), "tokens": pair}) } type loginRequest struct { Identifier string `json:"identifier" binding:"required"` Password string `json:"password" binding:"required"` } func (h *Handler) Login(c *gin.Context) { var req loginRequest if err := c.ShouldBindJSON(&req); err != nil { httpx.RespondError(c, httpx.BadRequest("invalid_request", "identifier and password are required")) return } u, pair, err := h.svc.Login(c.Request.Context(), req.Identifier, req.Password) if err != nil { httpx.RespondError(c, err) return } c.JSON(http.StatusOK, gin.H{"user": u.Self(), "tokens": pair}) } type refreshRequest struct { RefreshToken string `json:"refresh_token" binding:"required"` } func (h *Handler) Refresh(c *gin.Context) { var req refreshRequest if err := c.ShouldBindJSON(&req); err != nil { httpx.RespondError(c, httpx.BadRequest("invalid_request", "refresh_token is required")) return } pair, err := h.svc.Refresh(c.Request.Context(), req.RefreshToken) if err != nil { httpx.RespondError(c, err) return } c.JSON(http.StatusOK, gin.H{"tokens": pair}) } func (h *Handler) Logout(c *gin.Context) { var req refreshRequest _ = c.ShouldBindJSON(&req) if req.RefreshToken != "" { if err := h.svc.Logout(c.Request.Context(), req.RefreshToken); err != nil { httpx.RespondError(c, err) return } } c.Status(http.StatusNoContent) } func (h *Handler) Me(c *gin.Context) { u, err := h.svc.store.GetUserByID(c.Request.Context(), UserID(c)) if err != nil { httpx.RespondError(c, httpx.Unauthorized("unauthorized", "user not found")) return } prefs := u.Preferences if prefs == nil { prefs = map[string]any{} } c.JSON(http.StatusOK, gin.H{"user": u.Self(), "preferences": prefs}) } type updateMeRequest struct { Name string `json:"name"` } // UpdateMe changes the display name of the authenticated user. func (h *Handler) UpdateMe(c *gin.Context) { var req updateMeRequest if err := c.ShouldBindJSON(&req); err != nil { httpx.RespondError(c, httpx.BadRequest("invalid_request", "name is required")) return } u, err := h.svc.UpdateName(c.Request.Context(), UserID(c), req.Name) if err != nil { httpx.RespondError(c, err) return } c.JSON(http.StatusOK, gin.H{"user": u.Self()}) } type changePasswordRequest struct { CurrentPassword string `json:"current_password" binding:"required"` NewPassword string `json:"new_password" binding:"required"` } // ChangePassword verifies the current password and revokes all refresh tokens. func (h *Handler) ChangePassword(c *gin.Context) { var req changePasswordRequest if err := c.ShouldBindJSON(&req); err != nil { httpx.RespondError(c, httpx.BadRequest("invalid_request", "current_password and new_password are required")) return } if err := h.svc.ChangePassword(c.Request.Context(), UserID(c), req.CurrentPassword, req.NewPassword); err != nil { httpx.RespondError(c, err) return } c.Status(http.StatusNoContent) } type addIdentifierRequest struct { Email string `json:"email"` Phone string `json:"phone"` } // AddIdentifier adds the one missing login identifier. func (h *Handler) AddIdentifier(c *gin.Context) { var req addIdentifierRequest if err := c.ShouldBindJSON(&req); err != nil { httpx.RespondError(c, httpx.BadRequest("invalid_request", "email or phone is required")) return } u, err := h.svc.AddIdentifier(c.Request.Context(), UserID(c), req.Email, req.Phone) if err != nil { httpx.RespondError(c, err) return } c.JSON(http.StatusOK, gin.H{"user": u.Self()}) } type deleteMeRequest struct { Password string `json:"password" binding:"required"` } // DeleteMe deletes the authenticated account and all cascading content. func (h *Handler) DeleteMe(c *gin.Context) { var req deleteMeRequest if err := c.ShouldBindJSON(&req); err != nil { httpx.RespondError(c, httpx.BadRequest("invalid_request", "password is required")) return } if err := h.svc.DeleteAccount(c.Request.Context(), UserID(c), req.Password); err != nil { httpx.RespondError(c, err) return } c.Status(http.StatusNoContent) } const ( maxVisibleAttrs = 500 maxLabelEntries = 500 maxPreferenceKeyLen = 128 maxPreferenceValueLen = 128 maxCurvePresets = 100 maxCurvePresetNameLen = 64 maxCurvePresetPoints = 16 ) type photoInfoPreferences struct { Visible []string `json:"visible"` Labels map[string]string `json:"labels,omitempty"` } type curvePresetPoint struct { X float64 `json:"x"` Y float64 `json:"y"` } type curvePresetChannels struct { RGB []curvePresetPoint `json:"rgb"` Red []curvePresetPoint `json:"red"` Green []curvePresetPoint `json:"green"` Blue []curvePresetPoint `json:"blue"` } type curvePreset struct { Name string `json:"name"` Channels curvePresetChannels `json:"channels"` } type preferencesPayload struct { PhotoInfo *photoInfoPreferences `json:"photo_info,omitempty"` CurvePresets *[]curvePreset `json:"curve_presets,omitempty"` } // normalize trims preset names before they are validated and stored. func (p *preferencesPayload) normalize() { if p.CurvePresets == nil { return } for i := range *p.CurvePresets { (*p.CurvePresets)[i].Name = strings.TrimSpace((*p.CurvePresets)[i].Name) } } func (p preferencesPayload) validate() error { pi := p.PhotoInfo if pi != nil { if len(pi.Visible) > maxVisibleAttrs { return fmt.Errorf("too many visible attributes") } for _, k := range pi.Visible { if k == "" || len(k) > maxPreferenceKeyLen { return fmt.Errorf("invalid visible attribute key") } } if len(pi.Labels) > maxLabelEntries { return fmt.Errorf("too many label overrides") } for k, v := range pi.Labels { if k == "" || len(k) > maxPreferenceKeyLen { return fmt.Errorf("invalid label key") } if len(v) > maxPreferenceValueLen { return fmt.Errorf("label value too long") } } } if p.CurvePresets != nil { return validateCurvePresets(*p.CurvePresets) } return nil } func validateCurvePresets(presets []curvePreset) error { if len(presets) > maxCurvePresets { return fmt.Errorf("too many curve presets") } names := make(map[string]struct{}, len(presets)) for _, preset := range presets { if preset.Name == "" || utf8.RuneCountInString(preset.Name) > maxCurvePresetNameLen { return fmt.Errorf("invalid curve preset name") } channels := []struct { name string points []curvePresetPoint }{ {"rgb", preset.Channels.RGB}, {"red", preset.Channels.Red}, {"green", preset.Channels.Green}, {"blue", preset.Channels.Blue}, } for _, channel := range channels { if len(channel.points) < 2 || len(channel.points) > maxCurvePresetPoints { return fmt.Errorf("invalid curve preset points for %s", channel.name) } for _, pt := range channel.points { if math.IsNaN(pt.X) || math.IsNaN(pt.Y) || math.IsInf(pt.X, 0) || math.IsInf(pt.Y, 0) { return fmt.Errorf("invalid curve preset point") } if pt.X < 0 || pt.X > 1 || pt.Y < 0 || pt.Y > 1 { return fmt.Errorf("invalid curve preset point") } } } if _, dup := names[preset.Name]; dup { return fmt.Errorf("duplicate curve preset name") } names[preset.Name] = struct{}{} } return nil } func (h *Handler) UpdatePreferences(c *gin.Context) { body, err := io.ReadAll(io.LimitReader(c.Request.Body, 1<<20)) if err != nil { httpx.RespondError(c, httpx.BadRequest("invalid_preferences", "could not read request body")) return } var payload preferencesPayload if err := json.Unmarshal(body, &payload); err != nil { httpx.RespondError(c, httpx.BadRequest("invalid_preferences", "preferences must be a JSON object")) return } payload.normalize() if err := payload.validate(); err != nil { httpx.RespondError(c, httpx.BadRequest("invalid_preferences", err.Error())) return } ctx := c.Request.Context() u, err := h.svc.store.GetUserByID(ctx, UserID(c)) if err != nil { httpx.RespondError(c, httpx.Unauthorized("unauthorized", "user not found")) return } // Merge the submitted sections into the stored blob so saving one section // never clears the others. Unknown keys are preserved. merged := make(map[string]any, len(u.Preferences)+2) for k, v := range u.Preferences { merged[k] = v } if payload.PhotoInfo != nil { merged["photo_info"] = payload.PhotoInfo } if payload.CurvePresets != nil { merged["curve_presets"] = *payload.CurvePresets } if payload.PhotoInfo != nil || payload.CurvePresets != nil { raw, err := json.Marshal(merged) if err != nil { httpx.RespondError(c, httpx.BadRequest("invalid_preferences", "could not encode preferences")) return } if err := h.svc.store.UpdatePreferences(ctx, UserID(c), raw); err != nil { httpx.RespondError(c, err) return } } c.JSON(http.StatusOK, gin.H{"preferences": merged}) }