diff options
author | 2025-04-26 01:06:54 +0530 | |
---|---|---|
committer | 2025-04-26 01:06:54 +0530 | |
commit | 9d65a782ca3e2084ef0f560500f6014d7bd09bc0 (patch) | |
tree | e97195e8b967267d8d40098ae40a940fa2d44571 /backend/internal/api/handlers/user_handler.go | |
parent | 84622698f6c0e9d76ebe434c00df587908a37015 (diff) | |
download | finance-9d65a782ca3e2084ef0f560500f6014d7bd09bc0.tar.gz finance-9d65a782ca3e2084ef0f560500f6014d7bd09bc0.tar.bz2 finance-9d65a782ca3e2084ef0f560500f6014d7bd09bc0.zip |
finance/backend: mvfeat: moved the backend api handlers to api/handlers and added couple of more api request handlers
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}) +} |