Refactor user profile update handler to support optional email field and dynamic query construction

This commit is contained in:
Leon Bösche
2026-01-27 08:47:21 +01:00
parent 8400e97d17
commit 425bfcb495
3 changed files with 78 additions and 60 deletions

View File

@@ -3735,7 +3735,7 @@ func updateUserProfileHandler(w http.ResponseWriter, r *http.Request, db *databa
var req struct {
DisplayName *string `json:"displayName"`
Email string `json:"email"`
Email *string `json:"email"`
AvatarURL *string `json:"avatarUrl"`
BlurHash *string `json:"blurHash"`
}
@@ -3745,11 +3745,44 @@ func updateUserProfileHandler(w http.ResponseWriter, r *http.Request, db *databa
return
}
// Update user
_, err = db.ExecContext(r.Context(),
`UPDATE users SET display_name = $1, email = $2, avatar_url = $3, blur_hash = $4, updated_at = NOW()
WHERE id = $5`,
req.DisplayName, req.Email, req.AvatarURL, req.BlurHash, userID)
// Build dynamic update query
var setParts []string
var args []interface{}
argIndex := 1
if req.DisplayName != nil {
setParts = append(setParts, fmt.Sprintf("display_name = $%d", argIndex))
args = append(args, *req.DisplayName)
argIndex++
}
if req.Email != nil {
setParts = append(setParts, fmt.Sprintf("email = $%d", argIndex))
args = append(args, *req.Email)
argIndex++
}
if req.AvatarURL != nil {
setParts = append(setParts, fmt.Sprintf("avatar_url = $%d", argIndex))
args = append(args, *req.AvatarURL)
argIndex++
}
if req.BlurHash != nil {
setParts = append(setParts, fmt.Sprintf("blur_hash = $%d", argIndex))
args = append(args, *req.BlurHash)
argIndex++
}
if len(setParts) == 0 {
// No fields to update
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"message": "No changes to update"})
return
}
setParts = append(setParts, "updated_at = NOW()")
query := fmt.Sprintf("UPDATE users SET %s WHERE id = $%d", strings.Join(setParts, ", "), argIndex)
args = append(args, userID)
_, err = db.ExecContext(r.Context(), query, args...)
if err != nil {
errors.LogError(r, err, "Failed to update user profile")
errors.WriteError(w, errors.CodeInternal, "Server error", http.StatusInternalServerError)
@@ -3757,14 +3790,25 @@ func updateUserProfileHandler(w http.ResponseWriter, r *http.Request, db *databa
}
// Audit log
metadata := make(map[string]interface{})
if req.DisplayName != nil {
metadata["displayName"] = *req.DisplayName
}
if req.Email != nil {
metadata["email"] = *req.Email
}
if req.AvatarURL != nil {
metadata["avatarUrl"] = *req.AvatarURL
}
if req.BlurHash != nil {
metadata["blurHash"] = *req.BlurHash
}
auditLogger.Log(r.Context(), audit.Entry{
UserID: &userID,
Action: "profile_update",
Success: true,
Metadata: map[string]interface{}{
"displayName": req.DisplayName,
"email": req.Email,
},
UserID: &userID,
Action: "profile_update",
Success: true,
Metadata: metadata,
})
w.WriteHeader(http.StatusOK)