-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusers.go
84 lines (72 loc) · 2.1 KB
/
users.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
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"chirpy/internal/auth"
"encoding/json"
"net/http"
"strconv"
)
type User struct {
ID int `json:"id"`
Email string `json:"email"`
Password string `json:"-"`
IsChirpyRed bool `json:"is_chirpy_red"`
}
func (cfg *apiConfig) handleCreateUser(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Email string `json:"email"`
Password string `json:"password"`
}
type response struct {
User
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err := decoder.Decode(¶ms)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't decode parameters")
return
}
user, err := cfg.DB.CreateUser(params.Email, params.Password)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't create user")
return
}
respondWithJSON(w, http.StatusCreated, response{User: User{ID: user.ID, Email: user.Email, IsChirpyRed: user.IsChirpyRed}})
}
func (cfg *apiConfig) handleUpdateUser(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Email string `json:"email"`
Password string `json:"password"`
}
type response struct {
User
}
token, err := auth.GetBearerToken(r.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't find JWT")
return
}
subject, err := auth.ValidateAccessJWT(token, cfg.jwtSecret)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't validate JWT")
return
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err = decoder.Decode(¶ms)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't decode parameters")
return
}
userID, err := strconv.Atoi(subject)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't parse user ID")
return
}
user, err := cfg.DB.UpdateUser(userID, params.Email, params.Password)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't update user")
return
}
respondWithJSON(w, http.StatusOK, response{User: User{ID: user.ID, Email: user.Email, IsChirpyRed: user.IsChirpyRed}})
}