| 476 | ) |
| 477 | |
| 478 | func (ua *UserAuth) HandleUpdateMe(w http.ResponseWriter, r *http.Request) { |
| 479 | user := ua.AuthenticateRequest(r) |
| 480 | if user == nil { |
| 481 | http.Error(w, "not authenticated", http.StatusUnauthorized) |
| 482 | return |
| 483 | } |
| 484 | |
| 485 | var req struct { |
| 486 | Name *string `json:"name"` |
| 487 | } |
| 488 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil { |
| 489 | http.Error(w, "invalid JSON body", http.StatusBadRequest) |
| 490 | return |
| 491 | } |
| 492 | |
| 493 | if req.Name == nil { |
| 494 | http.Error(w, "no fields to update", http.StatusBadRequest) |
| 495 | return |
| 496 | } |
| 497 | |
| 498 | name := *req.Name |
| 499 | if name != strings.TrimSpace(name) { |
| 500 | http.Error(w, "name must not have leading or trailing whitespace", http.StatusBadRequest) |
| 501 | return |
| 502 | } |
| 503 | if len(name) < minDisplayNameLen || len(name) > maxDisplayNameLen { |
| 504 | http.Error(w, "name must be 1–80 characters", http.StatusBadRequest) |
| 505 | return |
| 506 | } |
| 507 | |
| 508 | updated, err := ua.store.UpdateUserName(r.Context(), user.ID, name) |
| 509 | if err != nil { |
| 510 | http.Error(w, "failed to update profile", http.StatusInternalServerError) |
| 511 | return |
| 512 | } |
| 513 | |
| 514 | w.Header().Set("Content-Type", "application/json") |
| 515 | writeJSON(w, updated) |
| 516 | } |
| 517 | |
| 518 | // AuthenticateRequest extracts the user from the session cookie. Returns nil if not authenticated. |
| 519 | func (ua *UserAuth) AuthenticateRequest(r *http.Request) *identity.User { |