blob: aff2d0379276deb4e2dd69800715e1b184ca804f (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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})
}
|