-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolka.go
More file actions
65 lines (53 loc) · 1.7 KB
/
polka.go
File metadata and controls
65 lines (53 loc) · 1.7 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
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/google/uuid"
"github.com/mdmdj/bootdev-chirpy/internal/auth"
)
type polkaWebhooksRequest struct {
Event string `json:"event"`
Data struct {
UserID string `json:"user_id"`
} `json:"data"`
}
func polkaWebhooksRoute(w http.ResponseWriter, r *http.Request) {
requestParams := polkaWebhooksRequest{}
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&requestParams)
if err != nil {
log.Printf("polkaWebhooksRoute Error decoding polkaWebhooksRequest parameters: %s", err)
respondWithError(w, http.StatusBadRequest, "400 Bad Request")
return
}
apiKey, err := auth.GetAPIKey(r.Header)
if err != nil {
log.Printf("polkaWebhooksRoute error getting API Key: %s", err)
respondWithError(w, http.StatusUnauthorized, "401 Unauthorized")
return
}
if apiKey != cfg.polkaKey {
log.Printf("polkaWebhooksRoute error bad API Key: %s", apiKey)
respondWithError(w, http.StatusUnauthorized, "401 Unauthorized")
return
}
if requestParams.Event != "user.upgraded" {
log.Printf("polkaWebhooksRoute skipping unknown event: %s", requestParams.Event)
w.WriteHeader(http.StatusNoContent)
return
}
userID := requestParams.Data.UserID
userUUID, err := uuid.Parse(userID)
if userID == "" || err != nil {
log.Printf("polkaWebhooksRoute error with data, bad ID: %s", userID)
respondWithError(w, http.StatusBadRequest, "400 Invalid Data")
return
}
_, err = cfg.db.UpdateUserChirpyRedEnable(r.Context(), userUUID)
if err != nil {
log.Printf("polkaWebhooksRoute error with UpdateUserChirpyRedEnable: %s %s", userID, err)
respondWithError(w, http.StatusNotFound, "404 User Not Found")
}
w.WriteHeader(http.StatusNoContent)
}