-
Notifications
You must be signed in to change notification settings - Fork 779
Expand file tree
/
Copy pathmail-service.js
More file actions
233 lines (192 loc) · 4.93 KB
/
mail-service.js
File metadata and controls
233 lines (192 loc) · 4.93 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
'use strict';
/**
* Dependencies
*/
const {Client} = require('@sendgrid/client');
const {classes: {Mail}} = require('@sendgrid/helpers');
/**
* Mail service class
*/
class MailService {
/**
* Constructor
*/
constructor() {
// Set client, initialize substitution wrappers and secret rules filter.
this.setClient(new Client());
this.setSubstitutionWrappers('{{', '}}');
this.secretRules = [];
}
/**
* Set client
*/
setClient(client) {
this.client = client;
return this;
}
/**
* SendGrid API key passthrough for convenience.
*/
setApiKey(apiKey) {
this.client.setApiKey(apiKey);
return this;
}
/**
* Twilio Email Auth passthrough for convenience.
*/
setTwilioEmailAuth(username, password) {
this.client.setTwilioEmailAuth(username, password);
}
/**
* Set client timeout
*/
setTimeout(timeout) {
if (typeof timeout === 'undefined') {
return;
}
this.client.setDefaultRequest('timeout', timeout);
}
/**
* Set substitution wrappers
*/
setSubstitutionWrappers(left, right) {
if (typeof left === 'undefined' || typeof right === 'undefined') {
throw new Error('Must provide both left and right side wrappers');
}
if (!Array.isArray(this.substitutionWrappers)) {
this.substitutionWrappers = [];
}
this.substitutionWrappers[0] = left;
this.substitutionWrappers[1] = right;
return this;
}
/**
* Set secret rules for filtering the e-mail content
*/
setSecretRules(rules) {
if (!(rules instanceof Array)) {
rules = [rules];
}
const tmpRules = rules.map(function (rule) {
const ruleType = typeof rule;
if (ruleType === 'string') {
return {
pattern: new RegExp(rule),
};
} else if (ruleType === 'object') {
// normalize rule object
if (rule instanceof RegExp) {
rule = {
pattern: rule,
};
} else if (rule.hasOwnProperty('pattern')
&& (typeof rule.pattern === 'string')
) {
rule.pattern = new RegExp(rule.pattern);
}
try {
// test if rule.pattern is a valid regex
rule.pattern.test('');
return rule;
} catch (err) {
// continue regardless of error
}
}
});
this.secretRules = tmpRules.filter(function (val) {
return val;
});
}
/**
* Check if the e-mail is safe to be sent
*/
filterSecrets(body) {
if ((typeof body === 'object') && !body.hasOwnProperty('content')) {
return;
}
const self = this;
body.content.forEach(function (data) {
self.secretRules.forEach(function (rule) {
if (rule.hasOwnProperty('pattern')
&& !rule.pattern.test(data.value)
) {
return;
}
let message = `The pattern '${rule.pattern}'`;
if (rule.name) {
message += `identified by '${rule.name}'`;
}
message += ' was found in the Mail content!';
throw new Error(message);
});
});
}
/**
* Send email
*/
send(data, isMultiple = false, cb) {
//Callback as second parameter
if (typeof isMultiple === 'function') {
cb = isMultiple;
isMultiple = false;
}
//Array? Send in parallel
if (Array.isArray(data)) {
//Create promise
const promise = Promise.all(data.map(item => {
return this.send(item, isMultiple);
}));
//Execute callback if provided
if (cb) {
promise
.then(result => cb(null, result))
.catch(error => cb(error, null));
}
//Return promise
return promise;
}
//Send mail
try {
// copy object to avoid mutating original
const args = { ...data };
//Append multiple flag to data if not set
if (typeof data.isMultiple === 'undefined') {
args.isMultiple = isMultiple;
}
//Append global substitution wrappers if not set in data
if (typeof data.substitutionWrappers === 'undefined') {
args.substitutionWrappers = this.substitutionWrappers;
}
//Create Mail instance from data and get JSON body for request
const mail = Mail.create(args);
const body = mail.toJSON();
//Filters the Mail body to avoid sensitive content leakage
this.filterSecrets(body);
//Create request
const request = {
method: 'POST',
url: '/v3/mail/send',
headers: mail.headers,
body,
};
//Send
return this.client.request(request, cb);
} catch (error) {
//Pass to callback if provided
if (cb) {
// eslint-disable-next-line callback-return
cb(error, null);
}
//Reject promise
return Promise.reject(error);
}
}
/**
* Send multiple emails (shortcut)
*/
sendMultiple(data, cb) {
return this.send(data, true, cb);
}
}
//Export class
module.exports = MailService;