Files
SproutGate/sproutgate-backend/internal/handlers/profile.go
2026-05-13 12:19:36 +08:00

90 lines
2.3 KiB
Go

package handlers
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
"sproutgate-backend/internal/auth"
)
// UpdateProfile
// @Summary 更新个人资料(可选改密码)
// @Tags auth
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param body body UpdateProfileRequest true "资料字段"
// @Success 200 {object} map[string]interface{}
// @Failure 400 {object} map[string]interface{}
// @Failure 401 {object} map[string]interface{}
// @Failure 500 {object} map[string]interface{}
// @Router /api/auth/profile [put]
func (h *Handler) UpdateProfile(c *gin.Context) {
token := bearerToken(c.GetHeader("Authorization"))
if token == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
return
}
claims, err := auth.ParseToken(h.store.JWTSecret(), h.store.JWTIssuer(), token)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
return
}
var req UpdateProfileRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
return
}
user, found, err := h.store.GetUser(claims.Account)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load user"})
return
}
if !found {
c.JSON(http.StatusUnauthorized, gin.H{"error": "user not found"})
return
}
if abortIfUserBanned(c, user) {
return
}
if abortIfTokenEpochStale(c, claims, user) {
return
}
if req.Password != nil && strings.TrimSpace(*req.Password) != "" {
hash, err := bcrypt.GenerateFromPassword([]byte(*req.Password), bcrypt.DefaultCost)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to hash password"})
return
}
user.PasswordHash = string(hash)
}
if req.Username != nil {
user.Username = *req.Username
}
if req.Phone != nil {
user.Phone = *req.Phone
}
if req.AvatarURL != nil {
user.AvatarURL = *req.AvatarURL
}
if req.WebsiteURL != nil {
wu, err := normalizePublicWebsiteURL(*req.WebsiteURL)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
user.WebsiteURL = wu
}
if req.Bio != nil {
user.Bio = *req.Bio
}
if err := h.store.SaveUser(user); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save user"})
return
}
c.JSON(http.StatusOK, gin.H{"user": user.OwnerPublic()})
}