-
Notifications
You must be signed in to change notification settings - Fork 677
Expand file tree
/
Copy pathindex.js
More file actions
250 lines (241 loc) · 8.74 KB
/
index.js
File metadata and controls
250 lines (241 loc) · 8.74 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
import dotenv from 'dotenv';
dotenv.config();
import express from 'express';
import cors from 'cors';
import { ParseServer } from 'parse-server';
import path from 'path';
const __dirname = path.resolve();
import http from 'http';
import formData from 'form-data';
import Mailgun from 'mailgun.js';
import { ApiPayloadConverter } from 'parse-server-api-mail-adapter';
import S3Adapter from '@parse/s3-files-adapter';
import FSFilesAdapter from '@parse/fs-files-adapter';
import AWS from 'aws-sdk';
import { app as customRoute } from './cloud/customRoute/customApp.js';
import { exec } from 'child_process';
import { createTransport } from 'nodemailer';
import { appName, cloudServerUrl, smtpenable, smtpsecure, useLocal } from './Utils.js';
import { SSOAuth } from './auth/authadapter.js';
import createContactIndex from './migrationdb/createContactIndex.js';
import { validateSignedLocalUrl } from './cloud/parsefunction/getSignedUrl.js';
import maintenance_mode_message from 'aws-sdk/lib/maintenance_mode_message.js';
let fsAdapter;
maintenance_mode_message.suppress = true;
if (useLocal !== 'true') {
try {
const spacesEndpoint = new AWS.Endpoint(process.env.DO_ENDPOINT);
const s3Options = {
bucket: process.env.DO_SPACE,
baseUrl: process.env.DO_BASEURL,
fileAcl: 'none',
region: process.env.DO_REGION,
directAccess: true,
preserveFileName: true,
presignedUrl: true,
presignedUrlExpires: 900,
s3overrides: {
credentials: {
accessKeyId: process.env.DO_ACCESS_KEY_ID,
secretAccessKey: process.env.DO_SECRET_ACCESS_KEY,
},
endpoint: spacesEndpoint,
},
};
fsAdapter = new S3Adapter(s3Options);
} catch (err) {
console.log('Please provide AWS credintials in env file! Defaulting to local storage.');
fsAdapter = new FSFilesAdapter({
filesSubDirectory: 'files', // optional, defaults to ./files
});
}
} else {
fsAdapter = new FSFilesAdapter({
filesSubDirectory: 'files', // optional, defaults to ./files
});
}
let transporterMail;
let mailgunClient;
let mailgunDomain;
let isMailAdapter = false;
if (smtpenable) {
try {
transporterMail = createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT || 465,
secure: smtpsecure,
auth: {
user: process.env.SMTP_USERNAME ? process.env.SMTP_USERNAME : process.env.SMTP_USER_EMAIL,
pass: process.env.SMTP_PASS,
},
});
await transporterMail.verify();
isMailAdapter = true;
} catch (err) {
isMailAdapter = false;
console.log('Please provide valid SMTP credentials');
}
} else if (process.env.MAILGUN_API_KEY) {
try {
const mailgun = new Mailgun(formData);
mailgunClient = mailgun.client({
username: 'api',
key: process.env.MAILGUN_API_KEY,
});
mailgunDomain = process.env.MAILGUN_DOMAIN;
isMailAdapter = true;
} catch (error) {
isMailAdapter = false;
console.log('Please provide valid Mailgun credentials');
}
}
const mailsender = smtpenable ? process.env.SMTP_USER_EMAIL : process.env.MAILGUN_SENDER;
export const config = {
databaseURI:
process.env.DATABASE_URI || process.env.MONGODB_URI || 'mongodb://localhost:27017/dev',
cloud: function () {
import('./cloud/main.js');
},
appId: process.env.APP_ID || 'opensign',
logLevel: ['error'],
maxLimit: 500,
maxUploadSize: '30mb',
masterKey: process.env.MASTER_KEY, //Add your master key here. Keep it secret!
masterKeyIps: ['0.0.0.0/0', '::/0'], // '::1'
serverURL: cloudServerUrl, // Don't forget to change to https if needed
verifyUserEmails: false,
publicServerURL: process.env.SERVER_URL || cloudServerUrl,
// Your apps name. This will appear in the subject and body of the emails that are sent.
appName: appName,
allowClientClassCreation: false,
allowExpiredAuthDataToken: false,
encodeParseObjectInCloudFunction: true,
...(isMailAdapter === true
? {
emailAdapter: {
module: 'parse-server-api-mail-adapter',
options: {
// The email address from which emails are sent.
sender: appName + ' <' + mailsender + '>',
// The email templates.
templates: {
// The template used by Parse Server to send an email for password
// reset; this is a reserved template name.
passwordResetEmail: {
subjectPath: './files/password_reset_email_subject.txt',
textPath: './files/password_reset_email.txt',
htmlPath: './files/password_reset_email.html',
},
// The template used by Parse Server to send an email for email
// address verification; this is a reserved template name.
verificationEmail: {
subjectPath: './files/verification_email_subject.txt',
textPath: './files/verification_email.txt',
htmlPath: './files/verification_email.html',
},
},
apiCallback: async ({ payload, locale }) => {
if (mailgunClient) {
const mailgunPayload = ApiPayloadConverter.mailgun(payload);
await mailgunClient.messages.create(mailgunDomain, mailgunPayload);
} else if (transporterMail) await transporterMail.sendMail(payload);
},
},
},
}
: {}),
filesAdapter: fsAdapter,
auth: { google: { enabled: true }, sso: SSOAuth },
// for fix Adapter prototype don't match expected prototype
push: { queueOptions: { disablePushWorker: true } },
};
// Client-keys like the javascript key or the .NET key are not necessary with parse-server
// If you wish you require them, you can set them as options in the initialization above:
// javascriptKey, restAPIKey, dotNetKey, clientKey
export const app = express();
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));
app.use(function (req, res, next) {
req.headers['x-real-ip'] = getUserIP(req);
next();
});
function getUserIP(request) {
let forwardedFor = request.headers['x-forwarded-for'];
if (forwardedFor) {
if (forwardedFor.indexOf(',') > -1) {
return forwardedFor.split(',')[0];
} else {
return forwardedFor;
}
} else {
return request.socket.remoteAddress;
}
}
app.use(async function (req, res, next) {
const isFilePath = req.path.includes('files') || false;
if (isFilePath && req.method.toLowerCase() === 'get') {
const serverUrl = new URL(process.env.SERVER_URL);
const origin = serverUrl.pathname === '/api/app' ? serverUrl.origin + '/api' : serverUrl.origin;
const fileUrl = origin + req.originalUrl;
const params = fileUrl?.split('?')?.[1];
if (params) {
const fileRes = await validateSignedLocalUrl(fileUrl);
if (fileRes === 'Unauthorized') {
return res.status(400).json({ message: 'unauthorized' });
}
} else {
return res.status(400).json({ message: 'unauthorized' });
}
next();
} else {
next();
}
});
// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));
// Serve the Parse API on the /parse URL prefix
if (!process.env.TESTING) {
const mountPath = process.env.PARSE_MOUNT || '/app';
try {
const server = new ParseServer(config);
await server.start();
app.use(mountPath, server.app);
} catch (err) {
console.log(err);
process.exit();
}
}
// Mount your custom express app
app.use('/', customRoute);
// Parse Server plays nicely with the rest of your web routes
app.get('/', function (req, res) {
res.status(200).send('opensign-server is running !!!');
});
if (!process.env.TESTING) {
const port = process.env.PORT || 8080;
const httpServer = http.createServer(app);
// Set the Keep-Alive and headers timeout to 100 seconds
httpServer.keepAliveTimeout = 100000; // in milliseconds
httpServer.headersTimeout = 100000; // in milliseconds
httpServer.listen(port, '0.0.0.0', function () {
console.log('opensign-server running on port ' + port + '.');
const isWindows = process.platform === 'win32';
// console.log('isWindows', isWindows);
const migrate = isWindows
? `set APPLICATION_ID=${process.env.APP_ID}&& set SERVER_URL=${cloudServerUrl}&& set MASTER_KEY=${process.env.MASTER_KEY}&& npx parse-dbtool migrate`
: `APPLICATION_ID=${process.env.APP_ID} SERVER_URL=${cloudServerUrl} MASTER_KEY=${process.env.MASTER_KEY} npx parse-dbtool migrate`;
exec(migrate, (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error.message}`);
return;
}
if (stderr) {
console.error(`Error: ${stderr}`);
return;
}
createContactIndex();
console.log(`Command output: ${stdout}`);
});
});
}