-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnapmail.go
115 lines (98 loc) · 2.59 KB
/
snapmail.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
package signup
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"time"
)
type SnapMail struct {
url string // Service HTTP endpoint
client *http.Client
signingSecret []byte // Secret used to sign the request body
}
type Payload struct {
Email string `json:"email"`
NameFirst string `json:"nameFirst"`
NameLast string `json:"nameLast"`
SessionCohort string `json:"sessionCohort"`
SessionID string `json:"sessionId"`
StartDateTime time.Time `json:"startDateTime,omitempty"`
Mobile string `json:"mobile"`
}
type signupEvent struct {
EventType string `json:"eventType"`
Payload Payload `json:"payload"`
}
type snapMailOption func(*SnapMail)
func NewSnapMail(apiBase string, opts ...snapMailOption) *SnapMail {
endpoint, err := url.Parse(apiBase)
if err != nil {
log.Fatal(fmt.Errorf("SNAP mail URL parse: %v", err))
}
sm := &SnapMail{
client: http.DefaultClient,
url: endpoint.JoinPath("/events").String(),
}
for _, opt := range opts {
opt(sm)
}
return sm
}
func (sm *SnapMail) name() string {
return "SNAP Mailer"
}
// IsRequired returns false because the snapMail webhook data can be retrieved from elsewhere and is not required for most students.
func (sm *SnapMail) isRequired() bool {
return false
}
func (sm *SnapMail) run(ctx context.Context, signup Signup) error {
event := signupEvent{
EventType: "SESSION_SIGNUP",
Payload: Payload{
Email: signup.Email,
NameFirst: signup.NameFirst,
NameLast: signup.NameLast,
SessionID: signup.SessionID,
SessionCohort: signup.Cohort,
StartDateTime: signup.StartDateTime,
Mobile: signup.Cell,
},
}
payload, err := json.Marshal(&event)
if err != nil {
return err
}
signature, err := createSignature(payload, sm.signingSecret)
if err != nil {
return fmt.Errorf("createSignature: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, sm.url, bytes.NewReader(payload))
if err != nil {
return fmt.Errorf("http.NewRequestWithContext: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Signature-256", string(signature))
resp, err := sm.client.Do(req)
if err != nil {
return fmt.Errorf("client.Do: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return handleHTTPError(resp)
}
return nil
}
func WithClient(client *http.Client) snapMailOption {
return func(sm *SnapMail) {
sm.client = client
}
}
func WithSigningSecret(secret string) snapMailOption {
return func(sm *SnapMail) {
sm.signingSecret = []byte(secret)
}
}