This repository has been archived by the owner on Oct 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
75 lines (62 loc) · 2.12 KB
/
handler.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
package handler
import (
"context"
"errors"
"fmt"
"net/http"
"net/mail"
"github.com/aws/aws-lambda-go/events"
"github.com/gofor-little/xlambda"
"github.com/gofor-little/xrand"
"github.com/strongishllama/millhouse.dev-cdk/internal/db"
"github.com/strongishllama/millhouse.dev-cdk/internal/recaptcha"
)
var (
RecaptchaSecret string
)
func Handler(ctx context.Context, request *events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) {
data := &RequestData{}
if err := xlambda.UnmarshalAndValidate(request, data); err != nil {
return xlambda.ProxyResponseJSON(http.StatusBadRequest, err, nil)
}
score, err := recaptcha.Verify(ctx, RecaptchaSecret, data.ReCaptchaChallengeToken)
if err != nil {
return xlambda.ProxyResponseJSON(http.StatusInternalServerError, fmt.Errorf("recaptcha verification failed: %w", err), nil)
}
if score <= 0.5 {
return xlambda.ProxyResponseJSON(http.StatusOK, nil, nil)
}
subscription, err := db.GetSubscription(ctx, data.EmailAddress)
if err != nil {
return xlambda.ProxyResponseJSON(http.StatusInternalServerError, fmt.Errorf("failed to check if subscription already exists: %w", err), nil)
}
if subscription != nil {
return xlambda.ProxyResponseJSON(http.StatusOK, nil, nil)
}
id, err := xrand.UUIDV4()
if err != nil {
return nil, fmt.Errorf("failed to generate UUID: %w", err)
}
subscription = &db.Subscription{
ID: id,
EmailAddress: data.EmailAddress,
IsConfirmed: false,
}
if err := subscription.Create(ctx); err != nil {
return xlambda.ProxyResponseJSON(http.StatusInternalServerError, fmt.Errorf("failed to create subscription: %w", err), nil)
}
return xlambda.ProxyResponseJSON(http.StatusOK, nil, nil)
}
type RequestData struct {
EmailAddress string `json:"emailAddress"`
ReCaptchaChallengeToken string `json:"recaptchaChallengeToken"`
}
func (r *RequestData) Validate() error {
if _, err := mail.ParseAddress(r.EmailAddress); err != nil {
return fmt.Errorf("failed to validate EmailAddress: %w", err)
}
if len(r.ReCaptchaChallengeToken) == 0 {
return errors.New("ReCaptchaChallengeToken cannot be empty")
}
return nil
}