[feature/backend] update put /users/me endpoint, allow setting username and display name

This commit is contained in:
CDN 2025-02-21 19:57:00 +08:00
parent 1526c27b49
commit 79912925db
Signed by: CDN
GPG key ID: 0C656827F9F80080
4 changed files with 46 additions and 3 deletions

View file

@ -11,6 +11,7 @@ import (
)
type UpdateCurrentUserRequest struct {
Username string `json:"username,omitempty" binding:"omitempty,min=3,max=32"`
Email string `json:"email,omitempty" binding:"omitempty,email"`
CurrentPassword string `json:"current_password,omitempty"`
NewPassword string `json:"new_password,omitempty" binding:"omitempty,min=8"`
@ -211,12 +212,20 @@ func (h *Handler) GetCurrentUser(c *gin.Context) {
// UpdateCurrentUser updates the current user's information
func (h *Handler) UpdateCurrentUser(c *gin.Context) {
// 从上下文中获取用户ID由认证中间件设置
userID, exists := c.Get("user_id")
userIDStr, exists := c.Get("user_id")
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
// 将用户ID转换为整数
userID, err := strconv.Atoi(userIDStr.(string))
if err != nil {
log.Error().Err(err).Msg("Failed to convert user ID to integer")
c.JSON(http.StatusInternalServerError, gin.H{"error": "Invalid user ID format"})
return
}
var req UpdateCurrentUserRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
@ -231,20 +240,25 @@ func (h *Handler) UpdateCurrentUser(c *gin.Context) {
}
// 验证当前密码
if err := h.service.VerifyPassword(c.Request.Context(), userID.(int), req.CurrentPassword); err != nil {
if err := h.service.VerifyPassword(c.Request.Context(), userID, req.CurrentPassword); err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid current password"})
return
}
}
// 更新用户信息
user, err := h.service.UpdateUser(c.Request.Context(), userID.(int), &types.UpdateUserInput{
user, err := h.service.UpdateUser(c.Request.Context(), userID, &types.UpdateUserInput{
Username: req.Username,
Email: req.Email,
Password: req.NewPassword,
DisplayName: req.DisplayName,
})
if err != nil {
log.Error().Err(err).Msg("Failed to update user")
if err.Error() == "username already taken" {
c.JSON(http.StatusConflict, gin.H{"error": "Username already taken"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update user information"})
return
}