-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscribe.go
208 lines (165 loc) · 5.23 KB
/
subscribe.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package main
import (
. "backend/common"
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/mailerlite/mailerlite-go"
"log"
"net/http"
"net/mail"
"strings"
)
func main() {
lambda.Start(handleSubscribe)
}
// handleSubscribe is called when the Lambda receivers a request.
// nil errors are returned because I want return custom http errors as opposed to Lambda's default 500.
func handleSubscribe(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
origin := req.Headers["origin"]
if !InitSuccess() {
return GenerateResponse(origin, http.StatusInternalServerError, "Something went wrong"), nil
}
status, msg := processSubscribeRequest(ctx, req.Body)
return GenerateResponse(origin, status, msg), nil
}
func processSubscribeRequest(ctx context.Context, body string) (int, string) {
data, msg, err := validateForm(body)
if msg != "" || err != nil {
log.Println("Failed to validate request body",
"error: ", fmt.Sprintf("%v", err),
"message: ", msg)
return http.StatusBadRequest, msg
}
err = validateCaptcha(ctx, data.Captcha)
if err != nil {
log.Println("Failed to validate captcha",
"error: ", err.Error(),
)
return http.StatusBadRequest, "Unable to complete subscription"
}
err = subscribe(ctx, data.Email, data.Tags)
if err != nil {
log.Println(
"Subscription request failed",
"error: ", err.Error(),
)
return http.StatusBadGateway, "Something went wrong"
}
return http.StatusCreated, "Successfully created"
}
// subscribe forwards the request to the mail client to subscribe the user
func subscribe(ctx context.Context, email string, tags []string) error {
allGroups, _, err := MailClient.Group.List(ctx, &mailerlite.ListGroupOptions{})
if err != nil {
return err
}
var groups []string
// Filter out groups with same name as supported tags
for _, group := range allGroups.Data {
for _, tag := range tags {
if strings.EqualFold(group.Name, tag) {
groups = append(groups, group.ID)
}
}
}
u := "https://connect.mailerlite.com/api/subscribers"
subscriber := map[string]interface{}{"email": email, "groups": groups, "status": "unconfirmed"}
reqBody := new(bytes.Buffer)
err = json.NewEncoder(reqBody).Encode(subscriber)
if err != nil {
return err
}
req, err := http.NewRequest(http.MethodPost, u, reqBody)
if err != nil {
return err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", MailClient.APIKey()))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if err == nil && (res.StatusCode == http.StatusOK || res.StatusCode == http.StatusCreated) {
return nil
}
return fmt.Errorf("subscription request failed. status code: %v, error: %v", res.StatusCode, err)
}
// validateCaptcha ensures this is not a spam request
func validateCaptcha(ctx context.Context, captcha string) error {
data := fmt.Sprintf("secret=%v&response=%v", AppConfig.TurnstileSecret, captcha)
u := "https://challenges.cloudflare.com/turnstile/v0/siteverify"
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, strings.NewReader(data))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
res, err := HttpClient.Do(req)
defer res.Body.Close()
var t turnstile
err = json.NewDecoder(res.Body).Decode(&t)
if err != nil {
return err
}
if t.Success && t.Hostname == AppConfig.TurnstileHostname {
return nil
}
return fmt.Errorf("invalid response: %+v\n", t)
}
// validateForm confirms that the request body contains the required data in the valid formats.
func validateForm(body string) (requestData, string, error) {
var data requestData
err := json.Unmarshal([]byte(body), &data)
if err != nil {
return requestData{}, "invalid request body", err
}
address, err := mail.ParseAddress(data.Email)
if err != nil {
return requestData{}, "invalid email", err
}
if strings.TrimSpace(data.Captcha) == "" {
return requestData{}, "captcha is required", nil
}
if len(data.Tags) > 2 {
return requestData{}, "invalid tags", nil
}
data.Email = address.Address
data.Tags = cleanTags(data.Tags)
return data, "", nil
}
// cleanTags ensures the tags in the request are valid. Also, adds default tags
func cleanTags(rawTags []string) []string {
var tapsMap = make(map[string]bool, 0) // Use a map to prevent duplicates
for _, tag := range rawTags {
trimmed := strings.ToLower(strings.TrimSpace(tag))
// Only take the tag if it's valid
if trimmed == Photography || trimmed == Programming {
tapsMap[trimmed] = true
}
}
var tags = []string{Blog} // Every subscriber belongs to the "blog" tag
// Convert the map to a list
for v := range tapsMap {
tags = append(tags, v)
}
// If tags wasn't sent in the request, add all supported tags
if len(tags) == 1 {
tags = append(tags, Photography, Programming)
}
return tags
}
type requestData struct {
Email string `json:"email"`
Captcha string `json:"captcha"`
Tags []string `json:"tags"`
}
type turnstile struct {
Success bool `json:"success"`
Hostname string `json:"hostname"`
Action string `json:"action"`
}