-
Notifications
You must be signed in to change notification settings - Fork 0
/
postPolkaWebhook.go
84 lines (69 loc) · 1.91 KB
/
postPolkaWebhook.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 (
"encoding/json"
"errors"
"log"
"net/http"
"github.com/adamhu714/chirpy/internal/database"
)
func (cfg *apiConfig) handlerPostPolkaWebhooks(w http.ResponseWriter, r *http.Request) {
userId, err := validatePostPolkaWebhook(w, r)
if err != nil {
return
}
authHeaderContent := r.Header.Get("Authorization")
if len(authHeaderContent) < 7 {
w.WriteHeader(http.StatusUnauthorized)
return
}
if authHeaderContent[7:] != cfg.polkaApiKey {
w.WriteHeader(http.StatusUnauthorized)
}
db, err := database.NewDB("database.json")
if err != nil {
log.Printf("handlerPostUsers - Error while connecting database: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
users, err := db.GetUsers()
if err != nil {
log.Printf("handlerPostPolkaWebhooks - error getting users: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
if userId < 1 || userId > len(users) {
w.WriteHeader(http.StatusNotFound)
return
}
err = db.UpdateIsRed(userId, true)
if err != nil {
log.Printf("handlerPostUsers - Error while creating user: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func validatePostPolkaWebhook(w http.ResponseWriter, r *http.Request) (int, error) {
type requestParams struct {
Event string `json:"event"`
Data struct {
UserId int `json:"user_id"`
} `json:"data"`
}
var requestBody requestParams
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&requestBody)
if err != nil {
log.Printf("Error while json decoding: %s", err.Error())
respBody := errorStruct{
Error: "Something went wrong",
}
respondWithJSON(w, http.StatusInternalServerError, respBody)
return 0, err
}
if requestBody.Event != "user.upgraded" {
w.WriteHeader(http.StatusOK)
return 0, errors.New("webhook event is not \"user.upgraded\"")
}
return requestBody.Data.UserId, nil
}