Files
minstrel/internal/api/me_profile.go
T
bvandeusen aa73c93f85 feat(server/m7-user-mgmt): self-service /me endpoints (U3)
Four authenticated endpoints for the user's own account:

- PUT /api/me/password — change own password. Caller must
  supply current_password (verified via bcrypt). Distinct from
  admin-driven reset (which doesn't require knowing the old).
  Audits ActionPasswordChangeSelf.

- PUT /api/me/profile — set display_name + email. Both fields
  are nullable; empty string clears, omitted leaves unchanged.
  Email is lowercased before store + format-validated. Unique
  violation → 409 email_taken.

- GET  /api/me/api-token — returns current API token (for
  copy-paste into Subsonic clients).
- POST /api/me/api-token — regenerates token. Old one stops
  working immediately. Audits ActionTokenRegenerate.

All four use the existing RequireUser middleware on the authed
sub-router; audit writes are best-effort (logged on failure).

Tests cover happy paths, wrong-password 401, password-too-short
400, email-invalid 400, email-taken 409, clear-by-empty-string,
omit-leaves-unchanged, token GET + regen.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 12:38:48 -04:00

131 lines
3.6 KiB
Go

package api
import (
"encoding/json"
"errors"
"net/http"
"regexp"
"strings"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5/pgconn"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
// emailRe is a simple format check. We don't try to validate
// deliverability — the SMTP send itself is the real check.
var emailRe = regexp.MustCompile(`^[^@\s]+@[^@\s]+\.[^@\s]+$`)
type updateProfileReq struct {
// Pointer fields so the caller can omit-vs-clear distinctly.
// nil = leave unchanged; non-nil empty string = clear; non-nil
// non-empty = update to that value. Note: distinguishing
// omit-vs-clear at JSON-decode time requires custom unmarshaling
// or a sentinel; for v1 we use the simpler "empty string clears"
// semantics: any field present in the JSON body is applied.
DisplayName *string `json:"display_name"`
Email *string `json:"email"`
}
type meProfileResp struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName *string `json:"display_name"`
Email *string `json:"email"`
IsAdmin bool `json:"is_admin"`
}
func (h *handlers) handleUpdateMyProfile(w http.ResponseWriter, r *http.Request) {
user, ok := auth.UserFromContext(r.Context())
if !ok {
writeErr(w, http.StatusUnauthorized, "auth_required", "")
return
}
var req updateProfileReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErr(w, http.StatusBadRequest, "invalid_body", "")
return
}
// Normalize: trim spaces; treat empty string as "clear" (NULL).
var displayName, email *string
if req.DisplayName != nil {
s := strings.TrimSpace(*req.DisplayName)
if s == "" {
displayName = nil
} else {
displayName = &s
}
}
if req.Email != nil {
s := strings.ToLower(strings.TrimSpace(*req.Email))
if s == "" {
email = nil
} else {
if !emailRe.MatchString(s) {
writeErr(w, http.StatusBadRequest, "email_invalid", "")
return
}
email = &s
}
}
// If neither field was provided, no-op (just re-fetch and return).
q := dbq.New(h.pool)
if req.DisplayName == nil && req.Email == nil {
current, err := q.GetUserByID(r.Context(), user.ID)
if err != nil {
h.logger.Error("update profile: lookup failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
writeJSON(w, http.StatusOK, profileViewFromUser(current))
return
}
// To preserve existing values for fields not in the request, we need
// to fetch the current row and merge.
current, err := q.GetUserByID(r.Context(), user.ID)
if err != nil {
h.logger.Error("update profile: lookup failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
if req.DisplayName == nil {
displayName = current.DisplayName
}
if req.Email == nil {
email = current.Email
}
updated, err := q.UpdateUserProfile(r.Context(), dbq.UpdateUserProfileParams{
ID: user.ID,
DisplayName: displayName,
Email: email,
})
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation {
writeErr(w, http.StatusConflict, "email_taken", "")
return
}
h.logger.Error("update profile: update failed", "err", err)
writeErr(w, http.StatusInternalServerError, "server_error", "")
return
}
writeJSON(w, http.StatusOK, profileViewFromUser(updated))
}
func profileViewFromUser(u dbq.User) meProfileResp {
return meProfileResp{
ID: uuidToString(u.ID),
Username: u.Username,
DisplayName: u.DisplayName,
Email: u.Email,
IsAdmin: u.IsAdmin,
}
}