diff options
Diffstat (limited to 'backend/internal/api/handlers/user_handler.go')
-rw-r--r-- | backend/internal/api/handlers/user_handler.go | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/backend/internal/api/handlers/user_handler.go b/backend/internal/api/handlers/user_handler.go new file mode 100644 index 0000000..aff2d03 --- /dev/null +++ b/backend/internal/api/handlers/user_handler.go @@ -0,0 +1,69 @@ +package handlers + +import ( + "finance/backend/internal/database" + "finance/backend/internal/models" + "net/http" + + "github.com/gin-gonic/gin" +) + +// UserHandler handles user-related operations +type UserHandler struct { +} + +// NewUserHandler creates and returns a new UserHandler instance +func NewUserHandler() *UserHandler { + return &UserHandler{} +} + +// GetCurrentUser returns the authenticated user's information +func (h *UserHandler) GetCurrentUser(c *gin.Context) { + // Get user from context (set by auth middleware) + user, exists := c.Get("user") + if !exists { + c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) + return + } + + c.JSON(http.StatusOK, gin.H{"user": user}) +} + +// UpdateCurrentUser updates the authenticated user's information +func (h *UserHandler) UpdateCurrentUser(c *gin.Context) { + userID := c.MustGet("userID").(uint) + var user models.User + + // Fetch the current user + if err := database.DB.First(&user, userID).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) + return + } + + // Define update structure + type UpdateUserInput struct { + Name string `json:"name"` + } + + var input UpdateUserInput + if err := c.ShouldBindJSON(&input); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + // Update fields if provided + if input.Name != "" { + user.Name = input.Name + } + + // Save the changes + if err := database.DB.Save(&user).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update user"}) + return + } + + // Hide sensitive data + user.PasswordHash = "" + + c.JSON(http.StatusOK, gin.H{"user": user}) +} |