-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler_users_update.go
More file actions
71 lines (54 loc) · 1.56 KB
/
handler_users_update.go
File metadata and controls
71 lines (54 loc) · 1.56 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
package main
import (
"encoding/json"
"net/http"
"github.com/SandeshNarayan/chirpy/internal/auth"
"github.com/SandeshNarayan/chirpy/internal/database"
)
func (cfg *apiConfig) handlerUsersUpdate(w http.ResponseWriter, r *http.Request){
accessToken, err := auth.GetBearerToken(r.Header)
if err!=nil {
respondWithError(w, http.StatusUnauthorized, "Missing or invalid token", err)
return
}
userID, err := auth.ValidateJWT(accessToken, cfg.jwtSecret)
if err!=nil{
respondWithError(w, http.StatusUnauthorized, "Invalid token", err)
return
}
type parameters struct {
Password string `json:"password"`
Email string `json:"email"`
}
var params parameters
if err:= json.NewDecoder(r.Body).Decode(¶ms); err!=nil{
respondWithError(w, http.StatusBadRequest, "Invalid request parameters", err)
return
}
HashPassword, err := auth.HashPassword(params.Password)
if err!=nil{
respondWithError(w, http.StatusInternalServerError, "Couldnt hash password", err)
return
}
newUser, err := cfg.dbQueries.UpdateUser(r.Context(), database.UpdateUserParams{
Email: params.Email,
HashedPassword: HashPassword,
ID: userID,
})
if err!=nil{
respondWithError(w, http.StatusInternalServerError, "Couldnt update user", err)
return
}
type response struct {
User
}
respondWithJson(w, http.StatusOK, response{
User: User{
ID: newUser.ID,
CreatedAt: newUser.CreatedAt,
UpdatedAt: newUser.UpdatedAt,
Email: newUser.Email,
IsChirpyRed: newUser.IsChirpyRed,
},
})
}