-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_webhooks.go
56 lines (48 loc) · 1.13 KB
/
handler_webhooks.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
package main
import (
"encoding/json"
"errors"
"net/http"
"github.com/erwaen/Chirpy/auth"
"github.com/erwaen/Chirpy/database"
)
func (cfg *apiConfig) handlerWBUpgrade(w http.ResponseWriter, r *http.Request) {
type Data struct {
UserID int `json:"user_id"`
}
type parameters struct {
Event string `json:"event"`
Data Data `json:"data"`
}
token, err := auth.GetApiKeyToken(r.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't find token")
return
}
if token != cfg.polkaKey {
respondWithError(w, http.StatusUnauthorized, "Not allowed")
return
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err = decoder.Decode(¶ms)
if err != nil {
respondWithError(w, 500, "Couldn't decode parameters")
return
}
if params.Event != "user.upgraded" {
respondWithoutJson(w, 204)
return
}
userID := params.Data.UserID
_, err = cfg.db.UpgradeUserRed(userID)
if err != nil {
if errors.Is(err, database.ErrNotExist) {
respondWithError(w, 404, "User not found")
} else {
respondWithError(w, 500, "Couldn't retrieve user")
}
return
}
respondWithoutJson(w, 204)
}