-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
237 lines (202 loc) · 6.4 KB
/
server.go
File metadata and controls
237 lines (202 loc) · 6.4 KB
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package main
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
log "github.com/Sirupsen/logrus"
"github.com/gorilla/mux"
emailLib "github.com/jordan-wright/email"
_ "github.com/lib/pq"
)
const (
contentType = "Content-Type"
jsonContentType = "application/json; charset=UTF-8"
)
func NewServer(httpAddr string, db *sql.DB, emailPool *emailLib.Pool) *http.Server {
// TODO - Add logging middleware
// TODO - Add secure headers middleware
r := mux.NewRouter()
r.HandleFunc("/api/v1/email", CreateEmailAccountHandler(db)).Methods("POST")
r.HandleFunc("/api/v1/email/{id}/send", SendEmailHandler(db, emailPool)).Methods("POST")
r.HandleFunc("/api/v1/email/bulksend", SendBulkEmailHandler(db, emailPool)).Methods("POST")
http.Handle("/", r)
return &http.Server{
Addr: httpAddr,
Handler: r,
}
}
func readReqBody(r *http.Request) ([]byte, error) {
defer r.Body.Close()
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
log.Errorf("Error occurred when reading r.Body: %s", err)
return nil, err
}
return body, nil
}
type ErrorResponse struct {
Error string `json:"error"`
}
// Custom version of http.Error to support json error messages
func ErrorRespond(w http.ResponseWriter, errMsg string, code int) {
resp := &ErrorResponse{Error: errMsg}
w.Header().Set(contentType, jsonContentType)
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(code)
if err := json.NewEncoder(w).Encode(resp); err != nil {
log.Errorf("Error occurred when marshalling response: %s", err)
}
}
type CreateEmailAccountResponse struct {
Id string `json:"id"`
}
func CreateEmailAccountHandler(db *sql.DB) func(w http.ResponseWriter, req *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
newAccount := &EmailAccount{}
body, err := readReqBody(r)
if err != nil {
ErrorRespond(w, err.Error(), http.StatusBadRequest)
return
}
if err := json.Unmarshal(body, newAccount); err != nil {
log.Errorf("Error occurred when unmarshalling data: %s", err)
ErrorRespond(w, err.Error(), http.StatusBadRequest)
return
}
err = newAccount.Save(db)
if err != nil {
ErrorRespond(w, err.Error(), http.StatusInternalServerError)
return
}
resp := &CreateEmailAccountResponse{
Id: newAccount.Id,
}
w.Header().Set(contentType, jsonContentType)
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(resp); err != nil {
log.Errorf("Error occurred when marshalling response: %s", err)
return
}
}
}
type SendEmailRequest struct {
EmailData EmailData `json:"email_data"`
SecureOnly bool `json:"secure_only,omitempty"`
}
func (ser *SendEmailRequest) Validate() error {
if ser == nil {
return fmt.Errorf("Got nil *SendEmailRequest!")
}
if ser.EmailData.Body == "" {
return fmt.Errorf("Email cannot have an empty body!")
}
if ser.EmailData.From == "" {
return fmt.Errorf("Email cannot have an empty 'from' address!")
}
return nil
}
func SendEmailHandler(db *sql.DB, emailPool *emailLib.Pool) func(w http.ResponseWriter, req *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
sendEmailReq := &SendEmailRequest{}
body, err := readReqBody(r)
if err != nil {
ErrorRespond(w, err.Error(), http.StatusBadRequest)
return
}
if err := json.Unmarshal(body, sendEmailReq); err != nil {
log.Errorf("Error occurred when unmarshalling data: %s", err)
ErrorRespond(w, err.Error(), http.StatusBadRequest)
return
}
if err = sendEmailReq.Validate(); err != nil {
log.Errorf("Invalid SendEmailRequest: %s", err)
ErrorRespond(w, err.Error(), http.StatusBadRequest)
return
}
// TODO - support returning 500 as well
emailAccount, err := GetEmailAccount(db, id)
if err != nil {
ErrorRespond(w, err.Error(), http.StatusNotFound)
return
}
if sendEmailReq.SecureOnly && !emailAccount.HasPubKey() {
errStr := fmt.Sprintf("Failed SecureOnly Email to %s - no pub key", emailAccount.Id)
log.Warn(errStr)
ErrorRespond(w, errStr, http.StatusBadRequest)
return
}
err = emailAccount.Send(sendEmailReq.EmailData, emailPool)
if err != nil {
log.Errorf("Error sending email: %v", err)
ErrorRespond(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
}
type SendBulkEmailRequest struct {
Ids []string `json:"ids,omitempty"`
Emails []string `json:"emails,omitempty"`
EmailData EmailData `json:"email_data"`
SecureOnly bool `json:"secure_only,omitempty"`
}
func (bulkReq *SendBulkEmailRequest) Validate() error {
if len(bulkReq.Ids) != 0 && len(bulkReq.Emails) != 0 {
return errors.New("Request body includes both emails and ids, parameters that are mutually exclusive")
}
return nil
}
type SendBulkEmailResponse struct {
FailedIds []string `json:"failed_emails"`
}
func SendBulkEmailHandler(db *sql.DB, emailPool *emailLib.Pool) func(w http.ResponseWriter, req *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
sendBulkEmailReq := &SendBulkEmailRequest{}
body, err := readReqBody(r)
if err != nil {
ErrorRespond(w, err.Error(), http.StatusBadRequest)
return
}
if err := json.Unmarshal(body, sendBulkEmailReq); err != nil {
log.Errorf("Error occurred when unmarshalling data: %s", err)
ErrorRespond(w, err.Error(), http.StatusBadRequest)
return
}
err = sendBulkEmailReq.Validate()
if err != nil {
ErrorRespond(w, err.Error(), http.StatusBadRequest)
return
}
emailAccounts := []*EmailAccount{}
if len(sendBulkEmailReq.Ids) > 0 {
// TODO - If SecureOnly is true, should filter out in db query
// TODO - support returning 500 as well
emailAccounts, err = GetEmailAccounts(db, sendBulkEmailReq.Ids)
if err != nil {
ErrorRespond(w, err.Error(), http.StatusNotFound)
return
}
} else if len(sendBulkEmailReq.Emails) > 0 {
for _, email := range sendBulkEmailReq.Emails {
emailAccounts = append(emailAccounts, &EmailAccount{Email: email})
}
}
failedIds := SendBulkEmail(emailAccounts, sendBulkEmailReq, emailPool)
if len(failedIds) == 0 {
w.WriteHeader(http.StatusNoContent)
} else {
w.Header().Set(contentType, jsonContentType)
w.WriteHeader(http.StatusCreated)
resp := &SendBulkEmailResponse{FailedIds: failedIds}
if err := json.NewEncoder(w).Encode(resp); err != nil {
log.Errorf("Error occurred when marshalling response: %s", err)
return
}
}
}
}