-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
264 lines (242 loc) · 6.63 KB
/
server.js
File metadata and controls
264 lines (242 loc) · 6.63 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
/**
* Created by austin on 7/20/16.
*/
// Load the config files. Keep the passwords in the private.config.json
const config = require('./config.json');
const privateConfig = require('./private.config.json');
// Data Models
const NDA = require('./models/NDA');
const PI = require('./models/PI');
const Project = require('./models/Project');
const Company = require('./models/Company');
const User = require('./models/User');
// Files / emails
const fs = require('fs');
const htmlToDocx = require('html-docx-js');
const nodemailer = require('nodemailer');
const emailTemplater = require('./email-templates/email-templates');
// Server
const bodyParser = require('body-parser');
const morgan = require('morgan');
const cors = require('cors');
const express = require('express');
const app = express();
// Documentation
const swagger = require('swagger-jsdoc');
const swaggerDef = {
info: {
title: 'Contracts-Go Api',
description: 'The Contracts-Go Api',
version: '1.0.0',
},
host: `${config.basePath}:${config.port}`,
};
const swaggerOpts = {
swaggerDefinition: swaggerDef,
apis: ['./server.js', './models/*.js'],
};
const swaggerSpec = swagger(swaggerOpts);
app.set('env', config.env);
// Middleware for the API
// Stores urlencoded and application/json into the request's body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Allow Cross Origin Requests
app.use(cors());
// ROUTES
// Serve swagger docs the way you like (Recommendation: swagger-tools)
app.get('/api-docs.json', (req, res) => {
res.send(swaggerSpec);
});
// Logs http requests made to server
if (app.get('env') === 'production') {
const logFile = fs.createWriteStream('./access.log', { flags: 'a' });
app.use(morgan('combined', { stream: logFile }));
} else {
app.use(morgan('dev'));
}
// Setup the e-mail-er client
const smtpConfig = {
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: privateConfig.mail.username,
pass: privateConfig.mail.password,
},
};
const emailTransporter = nodemailer.createTransport(smtpConfig);
// Create the tmp directory to store the ndas for emailing
if (!fs.existsSync(`${__dirname}/tmp`)) {
fs.mkdirSync(`${__dirname}/tmp`);
}
/**
* @see http://nodemailer.com/2-0-0-beta/setup-smtp/
* @param mail
*/
function sendMail(mail) {
return emailTransporter.sendMail({
from: privateConfig.mail.username,
to: mail.to,
cc: mail.cc,
subject: mail.subject,
html: mail.html,
attachments: mail.attachments,
});
}
/**
* @swagger
* parameter:
* generateBody:
* name: generateBody
* description: Body for the generate request.
* in: body
* required: true
* schema:
* type: object
*
*/
/**
* @swagger
* /generate:
* post:
* description: Generate and email a NDA Document
* produces:
* - application/json
* parameters:
* - name: company
* description: Company involved.
* in: body
* required: true
* schema:
* $ref: '#/definitions/Company'
* - name: pi
* description: PI involved.
* in: body
* required: true
* schema:
* $ref: '#/definitions/PI'
* - name: emailTo
* description: The contact/admin to email the generated document to.
* in: body
* required: false
* schema:
* $ref: '#/definitions/User'
* responses:
* 200:
* description: Document created
*/
app.post('/generate', (req, res, next) => {
const data = req.body;
let nda;
let date;
// Data section
// Defaults to today
if (data.date) {
date = new Date(data.date);
} else {
date = new Date();
}
// Create the NDA
try {
const ndaType = data.type;
const pi = new PI(data.pi.name, data.pi.title, data.pi.email);
const company = new Company(
data.company.type,
data.company.name,
data.company.state,
data.company.location,
data.company.contact
);
const project = new Project(data.project.industry, data.project.description);
// Fill the nda
nda = new NDA(ndaType, pi, company, project, date);
} catch (err) {
// Object Creation Errors
if (err instanceof TypeError) {
// If the problem is missing data in the request, mark as a BAD REQUEST
err.status = 400;
if (app.get('env') !== 'production') {
console.log(err);
}
}
throw err;
}
const ndaText = nda.generateHTML();
// Email Section
if (data.emailTo) {
const admin = new User(data.emailTo.name, data.emailTo.email);
// Create the nda page
const wordBuffer = htmlToDocx.asBlob(ndaText);
const newFileName = `${__dirname}/tmp/nda-${(new Date()).toISOString()}.docx`;
// Create a .docx temporary file
const docFile = fs.createWriteStream(newFileName);
docFile.once('open', () => {
docFile.write(wordBuffer);
docFile.end();
});
// Event handlers
docFile.on('error', (error) => {
console.log(error);
});
docFile.on('close', () => {
sendMail({
to: admin.email,
subject: `New NDA Request from ${data.pi.name}`,
cc: data.pi.email,
html: emailTemplater['new-nda']({
company: nda.company,
pi: nda.pi,
project: nda.project,
nda,
supportEmail: 'contractsgo@gmail.com',
admin,
}),
attachments: [
{
filename: `nda-${data.pi.name}-${(new Date()).toDateString()}.docx`,
content: fs.createReadStream(docFile.path),
},
],
}).then(() => {
// Success. Delete the file
console.log('Sent email');
fs.unlinkSync(docFile.path);
res.status(201).send({ nda: ndaText });
}).catch((error) => {
// Error. Log The error and Delete the file
console.log(`Error sending email: ${error}`);
fs.unlinkSync(docFile.path);
throw error; // Sends error to handler
});
});
} else {
res.status(201).send({ nda: ndaText });
}
});
// Error handling must be put at the end (?)
if (app.get('env') === 'production') {
// PRODUCTION
// Error handler
app.use((err, req, res, next) => {
res.status(err.status || 500).send({
message: err.message,
error: {}, // Don't send the stack back
});
});
} else {
// DEVELOPMENT
// Error handler
app.use((err, req, res, next) => {
res.status(err.status || 500).send({
message: err.message,
error: err.stack,
});
});
}
// Runs the app
const server = app.listen(config.port, () => {
console.log(`Running on port ${config.port}`);
});
// Exported for unit testing and others
module.exports = server;