-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser-update.go
More file actions
67 lines (55 loc) · 1.69 KB
/
user-update.go
File metadata and controls
67 lines (55 loc) · 1.69 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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/mdmdj/bootdev-chirpy/internal/auth"
"github.com/mdmdj/bootdev-chirpy/internal/database"
)
func userUpdateRoute(w http.ResponseWriter, r *http.Request) {
fmt.Println("userUpdateRoute")
token, err := auth.GetBearerToken(r.Header)
if err != nil {
log.Printf("Error in GetBearerToken: %s %s", token, err)
respondWithError(w, http.StatusUnauthorized, "Something went wrong")
return
}
userID, err := auth.ValidateJWT(token, cfg.secret)
if err != nil {
log.Printf("Error in ValidateJWT: %s", err)
respondWithError(w, http.StatusUnauthorized, "Something went wrong")
return
}
requestParams := userCreateRequest{}
decoder := json.NewDecoder(r.Body)
err = decoder.Decode(&requestParams)
if err != nil {
log.Printf("Error decoding userCreateRequest parameters: %s", err)
respondWithError(w, http.StatusBadRequest, "Something went wrong")
return
}
hasedPassword, err := auth.HashPassword(requestParams.Password)
if err != nil {
log.Printf("Error hashing password: %s", err)
respondWithError(w, http.StatusBadRequest, "Something went wrong")
return
}
dbUser, err := cfg.db.UpdateUserPassword(r.Context(), database.UpdateUserPasswordParams{
ID: userID,
HashedPassword: hasedPassword,
Email: requestParams.Email,
})
if err != nil {
log.Printf("Error updating user: %s %s %s", userID, requestParams.Email, err)
respondWithError(w, http.StatusBadRequest, "Something went wrong")
return
}
// Map database.User to main.User
user := User{
ID: dbUser.ID,
Email: dbUser.Email,
IsChirpyRed: dbUser.IsChirpyRed.Bool,
}
respondWithJSON(w, http.StatusOK, user)
}