-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandle_users_update.go
71 lines (57 loc) · 1.7 KB
/
handle_users_update.go
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
package main
import (
"encoding/json"
"net/http"
"time"
"github.com/google/uuid"
"github.com/toine08/http-server/internal/auth"
"github.com/toine08/http-server/internal/database"
)
func (cfg *apiConfig) handleUpdateUser(w http.ResponseWriter, req *http.Request) {
type parameters struct {
Email string `json:"email"`
Password string `json:"password"`
}
type userResponse struct {
ID uuid.UUID `json:"id"`
Email string `json:"email"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ChirpySub bool `json:"is_chirpy_red"`
}
tokenString, err := auth.GetBearerToken(req.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "No valid bearer token provided", err)
return
}
claims, err := auth.ValidateJWT(tokenString, cfg.tokenSecret)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Invalid or expired token", err)
return
}
decoder := json.NewDecoder(req.Body)
params := parameters{}
err = decoder.Decode(¶ms)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Couldn't decode parameters", err)
return
}
hashedPassword, err := auth.HashPassword(params.Password)
newUser, err := cfg.dbQueries.UpdateUser(req.Context(), database.UpdateUserParams{
ID: claims,
Email: params.Email,
HashedPassword: hashedPassword,
})
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Error while updating the password", err)
return
}
response := userResponse{
ID: newUser.ID,
Email: newUser.Email,
CreatedAt: newUser.CreatedAt,
UpdatedAt: newUser.UpdatedAt,
ChirpySub: newUser.IsChirpyRed.Bool,
}
respondWithJSON(w, http.StatusOK, response)
}