-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_polka.go
59 lines (51 loc) · 1.26 KB
/
handler_polka.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
package main
import (
"database/sql"
"encoding/json"
"net/http"
"github.com/chichigami/chirpy/internal/auth"
"github.com/chichigami/chirpy/internal/database"
"github.com/google/uuid"
)
func (cfg *apiConfig) handlerPolkaWebhook(w http.ResponseWriter, req *http.Request) {
type parameter struct {
Event string `json:"event"`
Data struct {
UserID string `json:"user_id"`
} `json:"data"`
}
param := parameter{}
decoder := json.NewDecoder(req.Body)
if decodeErr := decoder.Decode(¶m); decodeErr != nil {
respondWithError(w, 400, decodeErr.Error())
return
}
clientAPIKey, err := auth.GetAPIKey(req.Header)
if err != nil {
respondWithError(w, 401, err.Error())
return
}
if clientAPIKey != cfg.polka {
respondWithError(w, 401, "key does not match")
return
}
if param.Event != "user.upgraded" {
w.WriteHeader(204)
return
}
userID, err := uuid.Parse(param.Data.UserID)
if err != nil {
respondWithError(w, 500, "problem with parsing user id")
return
}
err = cfg.db.UpdateMembership(req.Context(), database.UpdateMembershipParams{
ID: userID,
IsChirpyRed: sql.NullBool{Bool: true, Valid: true},
})
if err != nil {
respondWithError(w, 404, "user cannot be found")
return
}
w.WriteHeader(204)
w.Write([]byte{})
}