-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler_users_update.go
More file actions
92 lines (85 loc) · 2.51 KB
/
handler_users_update.go
File metadata and controls
92 lines (85 loc) · 2.51 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"database/sql"
"encoding/json"
"log"
"net/http"
"github.com/google/uuid"
"github.com/huangmatty/crumbs/internal/auth"
"github.com/huangmatty/crumbs/internal/database"
)
func (cfg *apiConfig) handlerUsersUpdate(w http.ResponseWriter, r *http.Request) {
params := struct {
Username *string `json:"username,omitempty"`
Email *string `json:"email,omitempty"`
Password *string `json:"password,omitempty"`
}{}
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(¶ms); err != nil {
log.Printf("Error decoding JSON: %v", err)
http.Error(w, "Couldn't decode JSON", http.StatusBadRequest)
return
}
userID := r.Context().Value(cfg.authUserContextKey).(uuid.UUID)
dbUser, err := cfg.db.GetUserByID(r.Context(), userID)
if err == sql.ErrNoRows {
http.Error(w, "User doesn't exist", http.StatusNotFound)
return
}
if err != nil {
log.Printf("Error retrieving user: %v", err)
http.Error(w, "Couldn't retrieve user", http.StatusInternalServerError)
return
}
if params.Username != nil {
dbUser, err = cfg.db.UpdateUsername(r.Context(), database.UpdateUsernameParams{
Username: *params.Username,
ID: userID,
})
if err != nil {
log.Printf("Error updating user: %v", err)
http.Error(w, "Failed to update user", http.StatusInternalServerError)
return
}
}
if params.Email != nil {
dbUser, err = cfg.db.UpdateUserEmail(r.Context(), database.UpdateUserEmailParams{
Email: *params.Email,
ID: userID,
})
if err != nil {
log.Printf("Error updating user: %v", err)
http.Error(w, "Failed to update user", http.StatusInternalServerError)
return
}
}
if params.Password != nil {
if len(*params.Password) < minPasswordLength {
http.Error(w, "Password must have at least 12 characters", http.StatusBadRequest)
return
}
hashedPassword, err := auth.HashPassword(*params.Password)
if err != nil {
log.Printf("Error hashing password: %v", err)
http.Error(w, "Failed to hash password", http.StatusInternalServerError)
return
}
dbUser, err = cfg.db.UpdateUserPassword(r.Context(), database.UpdateUserPasswordParams{
HashedPassword: hashedPassword,
ID: userID,
})
if err != nil {
log.Printf("Error updating user: %v", err)
http.Error(w, "Failed to update user", http.StatusInternalServerError)
return
}
}
user := UserDTO{
ID: dbUser.ID,
CreatedAt: dbUser.CreatedAt,
UpdatedAt: dbUser.UpdatedAt,
Username: dbUser.Username,
Email: dbUser.Email,
}
respondWithJSON(w, http.StatusOK, user)
}