This repository was archived by the owner on Dec 3, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
212 lines (202 loc) · 7.57 KB
/
api.js
File metadata and controls
212 lines (202 loc) · 7.57 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
'use strict'
var bodyParser = require('body-parser')
var indicative = require('indicative')
var Promise = require('bluebird')
var _ = require('lodash')
var nodemailer = require('nodemailer')
var API_VERSION = 1
/**
* @param app
* @param config
* @param logging
* @param {Repository} SmtpCredentialRepository
* @param {Repository} TemplateRepository
*/
module.exports = function (app, config, logging, SmtpCredentialRepository, TemplateRepository) {
app.enable('trust proxy')
app.use(function (req, res, next) {
res.header('Cache-Control', 'max-age=0, private')
next()
})
var CONTENT_TYPE = 'application/vnd.' + config.get('app') + '.v' + API_VERSION + '+json'
app.use(bodyParser.json({type: CONTENT_TYPE}))
function errorResponse (res, err, status) {
logging.info(err.message, {error: err})
status = status || 500
res.status(status)
.set('Content-Type', CONTENT_TYPE)
.send({
$context: 'https://www.ietf.org/id/draft-ietf-appsawg-http-problem-01.txt',
type: '/error/' + status,
title: err.name,
status: status,
detail: err.message
})
/**
* See https://datatracker.ietf.org/doc/draft-ietf-appsawg-http-problem/
* @param {String} type A URI reference [RFC3986] that identifies the problem type.
* When dereferenced, it is encouraged to provide human-readable documentation for the
* problem type (e.g., using HTML [W3C.REC-html401-19991224]). When this member is not
* present, its value is assumed to be "about:blank".
* @param {String} title A short, human-readable summary of the problem type. It SHOULD NOT change from occurrence
* to occurrence of the problem, except for purposes of localisation.
* @param {Number} status The HTTP status code ([RFC7231], Section 6) generated by the origin server for this
* occurrence of the problem.
* @param {String} detail An human readable explanation specific to this occurrence of the problem.
* @constructor
*/
}
function createValidationErrorResponse (res, errors) {
return errorResponse(res, new Error(_.reduce(errors, function (msg, err) {
msg.push(err.message)
return msg
}, []).join(', ')), 400)
}
function createResource (repo, bodySchema, req, res) {
return Promise.join(
indicative.validate(req.params, {id: 'alpha_numeric'}),
indicative.validate(req.body, bodySchema)
)
.then(function () {
return repo.store(req.params.id, req.body)
.then(function () {
return res.status(201)
.set('Content-Type', CONTENT_TYPE)
.set('Location', req.url)
.send()
})
.catch(function (err) {
return errorResponse(res, err)
})
})
.catch(createValidationErrorResponse.bind(null, res))
}
app.put('/smtp_credentials/:id', createResource.bind(createResource, SmtpCredentialRepository,
{
dsn: ['required', 'regex:^[a-z]+://[^:]+:[^@]+@[^:]+:\\d+$'],
email: 'required|email',
bcc: 'email',
name: 'required'
}))
app.put('/templates/:id', createResource.bind(createResource, TemplateRepository,
{
subject: 'required',
html: 'required'
}))
function listResources (repo, transformer, req, res) {
return repo.list()
.then(function (items) {
return res.status(200)
.set('Content-Type', CONTENT_TYPE)
.send(_.map(items, transformer.bind(transformer, req)))
})
.catch(function (err) {
return errorResponse(res, err)
})
}
app.get('/smtp_credentials', listResources.bind(listResources, SmtpCredentialRepository, function (req, item) {
return {
$context: 'https://jsonld.nametacker.com/SmtpCredentials',
$id: req.url + '/' + item[0],
dsn: item[1].dsn,
email: item[1].email,
name: item[1].name
}
}))
app.get('/templates', listResources.bind(listResources, TemplateRepository, function (req, item) {
return {
$context: 'https://jsonld.nametacker.com/Template',
$id: req.url + '/' + item[0],
subject: item[1].subject,
html: item[1].html
}
}))
// Mail sending
app.post('/send/:transport/:template', function (req, res) {
return Promise.join(
indicative.validate(req.params, {transport: 'alpha_numeric', template: 'alpha_numeric'}),
indicative.validate(req.body, {
to: 'required|email',
name: 'required'
})
)
.then(function () {
return Promise.join(
SmtpCredentialRepository.fetch(req.params.transport),
TemplateRepository.fetch(req.params.template)
)
.spread(function (transport, template) {
if (!transport || !template) {
return res.status(404)
.set('Content-Type', CONTENT_TYPE)
.send()
}
// Try to apply template
var subject
var html
return Promise.try(function () {
subject = _.template(template.subject)(req.body)
html = _.template(template.html)(req.body)
}).then(function () {
return Promise.try(function () {
logging.info('Sending mail to "' + req.body.to + '" template: "' + req.params.template + '" via "' + req.params.transport + '"', req.body)
var headers = {}
headers['X-' + config.get('app')] = 'v' + config.get('version')
var dsn = transport.dsn.match(/^([a-z]+):\/\/([^:]+):([^@]+)@([^:]+):(\d+)$/)
var nodemailerConfig = {
host: dsn[4],
auth: {
user: dsn[2],
pass: dsn[3]
},
port: dsn[5],
secure: dsn[1] === 'ssl'
}
var transporter = nodemailer.createTransport(
nodemailerConfig,
{
from: '"' + transport.name + '" <' + transport.email + '>',
headers: headers
}
)
// Send response
res.status(202)
.set('Content-Type', CONTENT_TYPE)
.send()
// Send mail
Promise.promisifyAll(transporter)
var mailConfig = {
to: '"' + req.body.name + '" <' + req.body.to + '>',
subject: subject,
html: html
}
if (transport.bcc) {
mailConfig.bcc = transport.bcc
}
return transporter.sendMailAsync(mailConfig)
})
.then(function () {
logging.info(
'Successfully send mail to "' + req.body.to +
'" template: "' + req.params.template + '" via "' + req.params.transport + '"',
{body: req.body}
)
})
.catch(function (err) {
logging.error('Failed to send mail to "' + req.body.to + '" template: "' + req.params.template +
'" via "' + req.params.transport + '"',
{
body: req.body,
error: err
}
)
})
})
})
.catch(function (err) {
return errorResponse(res, err, 400)
})
})
.catch(createValidationErrorResponse.bind(null, res))
})
}