-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
332 lines (305 loc) · 12.9 KB
/
index.js
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// require('dotenv').config({ path: './dev.env' });
require('dotenv').config();
let express = require('express');
let app = express();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
let ParseServer = require('parse-server').ParseServer;
let ParseDashboard = require('parse-dashboard');
let path = require('path');
let moment = require('moment');
let Parse = require('parse/node');
const resolve = require('path').resolve;
const bodyParser = require('body-parser'); // Parse incoming request bodies
let GCSAdapter = require('@parse/gcs-files-adapter');
let mailgun = require('mailgun-js')({apiKey: process.env.ADAPTER_API_KEY, domain: process.env.ADAPTER_DOMAIN, host: 'api.eu.mailgun.net'});
const cors = require('cors');
// Parse lib init
Parse.initialize(process.env.APP_ID, null, process.env.MASTER_KEY);
Parse.masterKey = process.env.MASTER_KEY;
Parse.serverURL = process.env.SERVER_URL;
// Configuration Server
app.use(bodyParser.json({ type: 'application/json' }));
app.use(bodyParser.urlencoded({ extended: true }));
moment().format();
let databaseUri = process.env.DATABASE_URI;
if (!databaseUri) {
console.log('DATABASE_URI not specified, falling back to localhost.');
} else {
console.log('DB URI: ' + databaseUri);
}
let options = { allowInsecureHTTP: true };
let dashboard = new ParseDashboard({
"apps": [{
"serverURL": process.env.SERVER_URL,
"appId": process.env.APP_ID,
"masterKey": process.env.MASTER_KEY,
"appName": process.env.APP_NAME,
"iconName": "logo.png",
"supportedPushLocales": ["fr"]
}],
"iconsFolder": "icons",
"users": [{
"user": process.env.ADMIN_USER,
"pass": process.env.ADMIN_PASSWORD
}]
}, options);
let gcsOptions = {
"projectId": "weeclik-1517332083996",
"keyFilename": resolve(__dirname, "WeeClik-813d8719632d.json"),
"bucket": "weeclik-1517332083996.appspot.com",
"bucketPrefix": 'baas_files/',
"directAccess": false
}
let gcsAdapter = new GCSAdapter(gcsOptions);
let api = new ParseServer({
databaseURI: databaseUri || 'mongodb://localhost:27017/weeclik',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID,
masterKey: process.env.MASTER_KEY,
filesAdapter: gcsAdapter,
serverURL: process.env.SERVER_URL,
publicServerURL: process.env.PUBLIC_URL,
appName: process.env.APP_NAME,
maxUploadSize: process.env.MAX_UPLOAD_SIZE || "1024mb", // 1024 MB = 1 Go
allowClientClassCreation: true,
// Enable email verification
// try to use this (avantage langue) // "@ngti/parse-server-mailgun": "^2.4.18",
verifyUserEmails: process.env.VERIFY_USER_EMAILS || true,
emailAdapter: {
module: 'parse-server-mailgun',
options: {
// The address that your emails come from
fromAddress: 'Herrick de l\'équipe Weeclik <[email protected]>',
// Your domain from mailgun.com
domain: process.env.ADAPTER_DOMAIN,
// Mailgun host (default: 'api.mailgun.net').
// When using the EU region, the host should be set to 'api.eu.mailgun.net'
host: 'api.eu.mailgun.net',
// Your API key from mailgun.com
apiKey: process.env.ADAPTER_API_KEY,
// The template section
templates: {
passwordResetEmail: {
subject: 'Mot de passe oublié ?',
pathPlainText: resolve(__dirname, 'email_templates/password_reset/password_reset_email.txt'),
pathHtml: resolve(__dirname, 'email_templates/password_reset/password_reset_email.html'),
callback: (user) => { return {
name: user.get('name')
}}
// Now you can use {{name}} in your templates
},
verificationEmail: {
subject: 'Bienvenue dans la famille Weeclik',
pathPlainText: resolve(__dirname, 'email_templates/verification_email/verification_email.txt'),
pathHtml: resolve(__dirname, 'email_templates/verification_email/verification_email.html'),
callback: (user) => { return {
name: user.get('name')
}}
// Now you can use {{name}} in your templates
},
customEmailAlert: {
subject: 'Message urgent',
pathPlainText: resolve(__dirname, 'email_templates/custom_email/custom_email.txt'),
pathHtml: resolve(__dirname, 'email_templates/custom_email/custom_email.html'),
callback: (user) => { return {
name: user.get('name')
}}
// Now you can use {{name}} in your templates
}
}
}
}
});
// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));
app.get('/apple-app-site-association', (req, res) => {
res.status(200).sendFile(path.join(__dirname, 'apple-app-site-association'));
});
// Serve the Parse API on the /parse URL prefix
let mountPath = process.env.PARSE_MOUNT;
app.use(mountPath, api);
// make the Parse Dashboard available at /dashboard
app.use('/dashboard', dashboard);
// Allow all cors origin
app.use(cors());
let port = process.env.PORT || 1337;
let httpServer = require('http').createServer(app);
httpServer.listen(port, () => { console.log('Running weeclik server on port ' + port); });
// Import routes
require('./routes/stripe')(app);
// Cron tasks (repetitive tasks)
require('./cron/cron')(app);
app.post('/send-error-mail', (req, res) => {
console.log(req.body);
if (req.body.content_message) {
const data = {
from: 'iOS APP <[email protected]>',
to: '[email protected]',
subject: 'Error in iOS App',
text: req.body.content_message
};
mailgun.messages().send(data, (error, body) => {
if (error) {
return error
} else {
return res.status(200).send({
success: 'true',
message: 'Message envoyé avec succès',
});
}
console.log(body);
});
} else {
return res.status(422).send({
success: 'false',
message: 'Missing parameter : content_message is undefined'
})
}
});
// Match the raw body to content type application/json
// app.post('/webhook', (request, response) => {
// let event;
// try {event = request.body;}
// catch (err) {response.status(400).send(`Webhook Error: ${err.message}`);}
// console.log(event)
// // Handle the event
// switch (event.type) {
// case 'payment_intent.succeeded':
// const paymentIntent = event.data.object;
// response.json({received: true, method : event.data.object});
// break;
// case 'payment_method.attached':
// response.json({received: true, method : event.data.object});
// break;
// case 'payment_intent.created':
// response.json({received: true, method : event.data.object});
// break;
// case 'charge.succeeded':
// response.json({received: true, method : event.data.object});
// break;
// default:
// // Unexpected event type
// console.log('Stripe event not handled by server')
// console.log(event.type)
// return response.status(400).end();
// }
// });
app.post("/publish-commerce", async (req, res) => {
console.log("/publish-commerce commerce endpoint");
const commerceId = req.body.commerceId;
const checkoutSessionId = req.body.checkoutSessionId;
const userId = req.body.userId;
console.log("User "+ userId +" called checkoutSessionId: "+ checkoutSessionId + " for commerce: " + commerceId);
if (commerceId && checkoutSessionId && userId) {
var query = new Parse.Query(Parse.Object.extend("StripeCheckoutSessions"));
query.equalTo("sessionId", checkoutSessionId);
const result = await query.find();
if (result === undefined || result.length === 0) {
var queryR = new Parse.Query(Parse.Object.extend("Commerce"));
queryR.get(commerceId).then( async (commerce) => {
var sessions = commerce.get("stripeCheckoutSession");
// Set empty value if null/undefined
if (sessions === undefined) { commerce.set("stripeCheckoutSession", []); }
if (sessions === undefined || !sessions.includes(checkoutSessionId)) {
// Everything is ok continue with commerce publish
try {
const session = await stripe.checkout.sessions.retrieve(`${checkoutSessionId}`);
if (session.object === 'checkout.session') {
// Check this for result of payment (enum: paid || unpaid || no_payment_required)
if (session.payment_status === 'paid') {
// Save checkout session id to prevent fraud
const StripeSessions = Parse.Object.extend("StripeCheckoutSessions");
const sessionObject = new StripeSessions();
sessionObject.set("sessionId", checkoutSessionId);
sessionObject.set("commerceId", commerceId);
sessionObject.set("commerce", commerce);
const acl = new Parse.ACL();
acl.setPublicReadAccess(true);
acl.setRoleWriteAccess("admin", true);
acl.setWriteAccess(userId, true);
sessionObject.setACL(acl);
sessionObject.save(null, {useMasterKey: true}).then((_) =>{
// Update commerce data
var aYearFromNow = new Date();
aYearFromNow.setFullYear(aYearFromNow.getFullYear() + 1);
commerce.set("endedSubscription", aYearFromNow);
commerce.set("statutCommerce", 1);
commerce.set("brouillon", false);
commerce.addUnique("stripeCheckoutSession", checkoutSessionId);
commerce.save(null, {useMasterKey: true}).then((_) => {
return res.status(200).send({ message: 'Publishing of commerce: '+ commerceId + 'has been done successfully' });
}, (savingError) => {
return res.status(402).send({ error: 'Updating of commerce did fail. Original error => '+ savingError.message });
});
}, (sessionError) => {
return res.status(403).send({ error: 'Error while saving the session object. Original error => '+ sessionError });
});
} else {
res.status(403).json({ error: `Checkout session status: ${session.payment_status}, publishing not allowed for commerce: ${commerceId}`});
}
} else {
res.status(402).json({ error: "Invalid chackout session id provided, not returning a session object"});
}
} catch (error) {
res.status(400).json({ error: error});
}
} else {
// Stripe Checkout Session already exists in database
return res.status(403).send({ error: 'Stripe Checkout Session already exists in database'});
}
}, (commerceError) => {
return res.status(403).send({ error: 'Commerce not found. Original error => '+ commerceError.message });
});
} else {
return res.status(403).send({ error: 'Stripe Checkout Session Id already exists in database'});
}
} else {
res.status(400).json({ error: "The request was unacceptable, due to missing a required parameter."});
}
});
app.post("/share", (req, res) => {
console.log("/share commerce endpoint");
console.log("User: "+ req.body.userId + " is sharing commerce: " + req.body.commerceId);
const commerceId = req.body.commerceId;
const userId = req.body.userId;
if (commerceId) {
var query = new Parse.Query(Parse.Object.extend("Commerce"));
query.get(commerceId).then((commerce) => {
commerce.increment("nombrePartages");
commerce.save(null, {useMasterKey: true}).then((commerceSaved) => {
// Fetch user
if (userId) {
var userQuery = new Parse.Query(Parse.User);
userQuery.get(userId).then((user) => {
// TODO: check if values are nil
var shares = user.get("mes_partages");
if (shares === undefined || shares === null || typeof shares === 'undefined') {
// Date is null
user.set("mes_partages", []);
user.set("mes_partages_dates", []);
} else {
// Data already exists
user.add("mes_partages", commerce.id);
user.add("mes_partages_dates", new Date());
}
user.save(null, {useMasterKey: true}).then((user) => {
return res.status(200).send({ message: 'Sharing of commerce: '+ commerceId + 'has been done successfully by user: '+ userId });
}, (errorSavingUser) => {
return res.status(402).send({ error: 'Updating of user did fail. Original error => '+ errorSavingUser.message });
});
}, (userError) => {
return res.status(404).send({ error: 'User not found. Original error => '+ userError.message });
});
} else {
return res.status(200).send({ message: 'Sharing of commerce: '+ commerceId + 'has been done successfully' });
}
}, (savingError) => {
return res.status(401).send({ error: 'Updating of commerce did fail. Original error => '+ savingError.message });
});
}, (commerceError) => {
return res.status(403).send({ error: 'Commerce not found. Original error => '+ commerceError.message });
});
} else {
return res.status(400).send({ error: 'missing commerce id parameter' });
}
});