backend-manager 3.2.2 → 3.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "backend-manager",
3
- "version": "3.2.2",
3
+ "version": "3.2.4",
4
4
  "description": "Quick tools for developing Firebase functions",
5
5
  "main": "src/manager/index.js",
6
6
  "bin": {
@@ -55,7 +55,7 @@
55
55
  "moment": "^2.30.1",
56
56
  "nanoid": "^3.3.7",
57
57
  "node-fetch": "^2.7.0",
58
- "node-powertools": "^1.1.2",
58
+ "node-powertools": "^1.2.0",
59
59
  "npm-api": "^1.0.1",
60
60
  "paypal-server-api": "^1.0.3",
61
61
  "pushid": "^1.0.0",
@@ -70,4 +70,4 @@
70
70
  "wonderful-log": "^1.0.5",
71
71
  "yargs": "^17.7.2"
72
72
  }
73
- }
73
+ }
@@ -33,7 +33,6 @@ Module.prototype.main = function () {
33
33
  assistant.log('UUID Generated', payload.data.payload, result);
34
34
 
35
35
  return resolve({data: {uuid: result}});
36
-
37
36
  });
38
37
 
39
38
  };
@@ -0,0 +1,26 @@
1
+ const uuid = require('uuid');
2
+
3
+ function Module() {
4
+
5
+ }
6
+
7
+ Module.prototype.main = function () {
8
+ const self = this;
9
+ const Manager = self.Manager;
10
+ const Api = self.Api;
11
+ const assistant = self.assistant;
12
+ const payload = self.payload;
13
+
14
+ return new Promise(async function(resolve, reject) {
15
+
16
+ payload.data.payload.url = payload.data.payload.url || 'https://itwcreativeworks.com'
17
+
18
+ assistant.log('Redirecting', payload.data.payload.url);
19
+
20
+ return resolve({redirect: payload.data.payload.url});
21
+ });
22
+
23
+ };
24
+
25
+
26
+ module.exports = Module;
@@ -108,11 +108,14 @@ Module.prototype.main = function() {
108
108
  })
109
109
  }
110
110
 
111
+ // Fix status
111
112
  self.payload.response.status = _fixStatus(self.payload.response.status);
112
113
 
114
+ // Set status
113
115
  res.status(self.payload.response.status)
114
116
 
115
- if (self.payload.response.status >= 200 && self.payload.response.status < 300) {
117
+ // Send response
118
+ if (self.payload.response.status >= 200 && self.payload.response.status < 399) {
116
119
  self.assistant.log(`Finished ${resolved.command} (status=${self.payload.response.status})`, self.payload, JSON.stringify(self.payload))
117
120
 
118
121
  if (self.payload.response.redirect) {
@@ -124,7 +127,6 @@ Module.prototype.main = function() {
124
127
  }
125
128
  } else {
126
129
  self.assistant.error(`Error executing ${resolved.command} @ ${resolved.path} (status=${self.payload.response.status}):`, self.payload.response.error)
127
- // return res.send(self.payload.response.error.message);
128
130
  res.send(`${self.payload.response.error}`)
129
131
  return reject(self.payload.response.error);
130
132
  }
@@ -402,6 +402,19 @@ BackendAssistant.prototype.errorify = function (e, options) {
402
402
 
403
403
  BackendAssistant.prototype.errorManager = BackendAssistant.prototype.errorify;
404
404
 
405
+ BackendAssistant.prototype.redirect = function(response, options) {
406
+ const self = this;
407
+ const res = self.ref.res;
408
+
409
+ // Set options
410
+ options = options || {};
411
+ options.code = typeof options.code === 'undefined'
412
+ ? 302
413
+ : options.code;
414
+
415
+ return self.respond(response, options);
416
+ }
417
+
405
418
  BackendAssistant.prototype.respond = function(response, options) {
406
419
  const self = this;
407
420
  const res = self.ref.res;
@@ -428,19 +441,33 @@ BackendAssistant.prototype.respond = function(response, options) {
428
441
  // Attach properties
429
442
  _attachHeaderProperties(self, options);
430
443
 
431
- // Log the error
432
- if (options.log) {
433
- self.log(`Responding with ${options.code} code:`, JSON.stringify(response));
434
- }
435
-
436
444
  // Send response
437
445
  res.status(options.code);
438
446
 
447
+ function _log(text) {
448
+ if (options.log) {
449
+ self.log(`${text} (${options.code}):`, JSON.stringify(response));
450
+ }
451
+ }
452
+
453
+ // Redirect
454
+ const isRedirect = isBetween(options.code, 300, 399);
455
+ if (isRedirect) {
456
+ // Log
457
+ _log(`Redirecting`);
458
+
459
+ // Send
460
+ return res.redirect(response);
461
+ }
462
+
463
+ // Log
464
+ _log(`Sending response`);
465
+
439
466
  // If it is an object, send as json
440
467
  if (response && typeof response === 'object') {
441
- res.json(response);
468
+ return res.json(response);
442
469
  } else {
443
- res.send(response);
470
+ return res.send(response);
444
471
  }
445
472
  }
446
473
 
@@ -76,7 +76,7 @@ Middleware.prototype.run = function (library, options) {
76
76
  try {
77
77
  assistant.settings = Manager.Settings().resolve(assistant, options.schema, assistant.request.data);
78
78
  } catch (e) {
79
- return assistant.errorify(`Unable to resolve settings @ (${options.schema}): ${e.message}`, {sentry: true, send: true, log: true});
79
+ return assistant.errorify(`Unable to resolve schema @ (${options.schema}): ${e.message}`, {sentry: true, send: true, log: true});
80
80
  }
81
81
  }
82
82
 
@@ -167,8 +167,7 @@ Manager.prototype.init = function (exporter, options) {
167
167
 
168
168
  // Setup options features
169
169
  if (self.options.initialize) {
170
- // console.log('Initializing:', self.project);
171
- // console.log('----process.env.GOOGLE_APPLICATION_CREDENTIALS', process.env.GOOGLE_APPLICATION_CREDENTIALS);
170
+ // Initialize Firebase
172
171
  try {
173
172
  // console.log('---process.env.GOOGLE_APPLICATION_CREDENTIALS', process.env.GOOGLE_APPLICATION_CREDENTIALS);
174
173
  if (process.env.GOOGLE_APPLICATION_CREDENTIALS) {
@@ -190,6 +189,20 @@ Manager.prototype.init = function (exporter, options) {
190
189
  } catch (e) {
191
190
  self.assistant.error('Failed to call .initializeApp()', e);
192
191
  }
192
+
193
+ // Update firebase settings
194
+ try {
195
+ // Update project config
196
+ self.libraries.admin.auth().projectConfigManager().updateProjectConfig({
197
+ emailPrivacyConfig: {
198
+ enableImprovedEmailPrivacy: true,
199
+ },
200
+ });
201
+ } catch (e) {
202
+ self.assistant.error('Failed to call .updateProjectConfig()', e);
203
+ } finally {
204
+
205
+ }
193
206
  // admin.firestore().settings({/* your settings... */ timestampsInSnapshots: true})
194
207
  }
195
208
 
@@ -199,9 +212,7 @@ Manager.prototype.init = function (exporter, options) {
199
212
  self.libraries.functions
200
213
  .runWith({memory: '256MB', timeoutSeconds: 60})
201
214
  // TODO: Replace this with new API
202
- .https.onRequest(async (req, res) => {
203
- return self._process((new (require(`${core}/actions/api.js`))()).init(self, { req: req, res: res, }))
204
- });
215
+ .https.onRequest(async (req, res) => self._process((new (require(`${core}/actions/api.js`))()).init(self, { req: req, res: res, })));
205
216
 
206
217
  if (options.setupFunctionsLegacy) {
207
218
  exporter.bm_signUpHandler =
@@ -378,51 +389,39 @@ Manager.prototype.init = function (exporter, options) {
378
389
  self.libraries.functions
379
390
  .runWith({memory: '256MB', timeoutSeconds: 60})
380
391
  .auth.user()
381
- .beforeCreate(async (user, context) => {
382
- return self._process((new (require(`${core}/events/auth/before-create.js`))()).init(self, { user: user, context: context}))
383
- });
392
+ .beforeCreate(async (user, context) => self._process((new (require(`${core}/events/auth/before-create.js`))(), {middleware: false}).init(self, { user: user, context: context})));
384
393
 
385
394
  exporter.bm_authBeforeSignIn =
386
395
  self.libraries.functions
387
396
  .runWith({memory: '256MB', timeoutSeconds: 60})
388
397
  .auth.user()
389
- .beforeSignIn(async (user, context) => {
390
- return self._process((new (require(`${core}/events/auth/before-signin.js`))()).init(self, { user: user, context: context}))
391
- });
398
+ .beforeSignIn(async (user, context) => self._process((new (require(`${core}/events/auth/before-signin.js`))(), {middleware: false}).init(self, { user: user, context: context})));
392
399
  }
393
400
 
394
401
  exporter.bm_authOnCreate =
395
402
  self.libraries.functions
396
403
  .runWith({memory: '256MB', timeoutSeconds: 60})
397
404
  .auth.user()
398
- .onCreate(async (user, context) => {
399
- return self._process((new (require(`${core}/events/auth/on-create.js`))()).init(self, { user: user, context: context}))
400
- });
405
+ .onCreate(async (user, context) => self._process((new (require(`${core}/events/auth/on-create.js`))(), {middleware: false}).init(self, { user: user, context: context})));
401
406
 
402
407
  exporter.bm_authOnDelete =
403
408
  self.libraries.functions
404
409
  .runWith({memory: '256MB', timeoutSeconds: 60})
405
410
  .auth.user()
406
- .onDelete(async (user, context) => {
407
- return self._process((new (require(`${core}/events/auth/on-delete.js`))()).init(self, { user: user, context: context}))
408
- });
411
+ .onDelete(async (user, context) => self._process((new (require(`${core}/events/auth/on-delete.js`))(), {middleware: false}).init(self, { user: user, context: context})));
409
412
 
410
413
  exporter.bm_subOnWrite =
411
414
  self.libraries.functions
412
415
  .runWith({memory: '256MB', timeoutSeconds: 60})
413
416
  .firestore.document('notifications/subscriptions/all/{token}')
414
- .onWrite(async (change, context) => {
415
- return self._process((new (require(`${core}/events/firestore/on-subscription.js`))()).init(self, { change: change, context: context, }))
416
- });
417
+ .onWrite(async (change, context) => self._process((new (require(`${core}/events/firestore/on-subscription.js`))(), {middleware: false}).init(self, { change: change, context: context, })));
417
418
 
418
419
  // Cron
419
420
  exporter.bm_cronDaily =
420
421
  self.libraries.functions
421
422
  .runWith({ memory: '256MB', timeoutSeconds: 120 })
422
423
  .pubsub.schedule('every 24 hours')
423
- .onRun(async (context) => {
424
- return self._process((new (require(`${core}/cron/daily.js`))()).init(self, { context: context, }))
425
- });
424
+ .onRun(async (context) => self._process((new (require(`${core}/cron/daily.js`))(), {middleware: false}).init(self, { context: context, })));
426
425
  }
427
426
 
428
427
  // Set dotenv
@@ -453,14 +452,14 @@ Manager.prototype.init = function (exporter, options) {
453
452
  };
454
453
 
455
454
  // HELPERS
456
- Manager.prototype._process = function (mod) {
455
+ Manager.prototype._process = function (mod, options) {
457
456
  const self = this;
458
- const name = mod.assistant.meta.name;
459
- const hook = self.handlers && self.handlers[name];
460
- const req = mod.req;
461
- const res = mod.res;
462
457
 
463
458
  return new Promise(async function(resolve, reject) {
459
+ const name = mod.assistant.meta.name;
460
+ const hook = self.handlers && self.handlers[name];
461
+ const req = mod.req;
462
+ const res = mod.res;
464
463
  let error;
465
464
 
466
465
  function _reject(e, log) {
@@ -1,414 +0,0 @@
1
- let fetch;
2
- const _ = require('lodash');
3
-
4
- let Module = {
5
- init: async function (Manager, data) {
6
- this.Manager = Manager;
7
- this.libraries = Manager.libraries;
8
- this.assistant = Manager.Assistant({req: data.req, res: data.res})
9
- this.req = data.req;
10
- this.res = data.res;
11
-
12
- return this;
13
- },
14
- main: async function() {
15
- let self = this;
16
- let libraries = self.libraries;
17
- let assistant = self.assistant;
18
- let req = self.req;
19
- let res = self.res;
20
-
21
- let response = {
22
- status: 200,
23
- data: {},
24
- };
25
-
26
- return libraries.cors(req, res, async () => {
27
- let user = await assistant.authenticate();
28
-
29
- const command = assistant.request.data.command;
30
- const payload = {
31
- response: response,
32
- data: assistant.request.data,
33
- user: user,
34
- }
35
-
36
- self.assistant.log('Executing', command)
37
-
38
- function _errorLog(e) {
39
- self.assistant.error(e)
40
- }
41
-
42
- // Actions
43
- // General
44
- if (command === 'general:payment-processor' || command === 'payment-processor') { // rename: general:payment-processor
45
- await self.general_paymentProcessor(payload).catch(e => _errorLog);
46
- // } else if (command === 'general:generate-uuid') {
47
- // await self.general_generateUUID(payload).catch(e => _errorLog);
48
-
49
- // User
50
- } if (command === 'user:create-custom-token' || command === 'create-custom-token') { // rename: user:create-custom-token
51
- await self.user_createCustomToken(payload).catch(e => _errorLog);
52
- } else if (command === 'user:delete' || command === 'delete-user') { // rename: user:delete
53
- await self.user_delete(payload).catch(e => _errorLog);
54
- } else if (command === 'user:sign-out-all-sessions' || command === 'sign-out-all-sessions') { // rename: user:sign-out-all-sessions
55
- await self.user_signOutAllSessions(payload).catch(e => _errorLog);
56
- } else if (command === 'user:get-subscription-info' || command === 'get-user-subscription-info') { // rename: user:get-subscription-info
57
- await self.user_getSubscriptionInfo(payload).catch(e => _errorLog);
58
- // } else if (command === 'user:sign-up') {
59
- // await self.user_signUp(payload).catch(e => _errorLog);
60
-
61
- // Handler
62
- } else if (command === 'handler:create-post') {
63
- console.log('---------AAAAA');
64
- await self.handler_createPost().init(payload).main().catch(e => _errorLog);
65
- console.log('---------BBBBB');
66
- await self.handler_createPost().init(payload).main().catch(e => _errorLog);
67
-
68
- // Admin
69
- // } else if (command === 'admin:create-post') {
70
- // await self.admin_createPost(payload).catch(e => _errorLog);
71
- // } else if (command === 'admin:get-stats') {
72
- // await self.admin_getStats(payload).catch(e => _errorLog);
73
- // } else if (command === 'admin:send-notification') {
74
- // await self.admin_sendNotification(payload).catch(e => _errorLog);
75
- } else if (command === 'admin:firestore-read' || command === 'firestore-read') {
76
- await self.admin_firestoreRead(payload).catch(e => _errorLog);
77
- } else if (command === 'admin:firestore-write' || command === 'firestore-write') {
78
- await self.admin_firestoreWrite(payload).catch(e => _errorLog);
79
- // } else if (command === 'admin:firestore-query') {
80
- // await self.admin_query(payload).catch(e => _errorLog);
81
-
82
- // End
83
- } else {
84
- response.status = 401;
85
- response.error = new Error(`Improper command supplied: ${command}`);
86
- }
87
-
88
- self.assistant.log('Api payload', {object: payload, string: JSON.stringify(payload)})
89
-
90
- if (response.status === 200) {
91
- return res.status(response.status).json(response.data);
92
- } else {
93
- return res.status(response.status).send(response.error.message);
94
- }
95
- });
96
- },
97
-
98
- // General
99
- general_paymentProcessor: async function (payload) {
100
- const self = this;
101
-
102
- return new Promise(async function(resolve, reject) {
103
- const productId = _.get(payload, 'data.payload.payload.details.productIdGlobal');
104
- if (!productId) {
105
- return reject(new Error('No productId'))
106
- }
107
- const processorPath = `${process.cwd()}/payment-processors/${productId}.js`
108
- let processor;
109
- // console.log('---processorPath', processorPath);
110
- try {
111
- processor = new (require(processorPath));
112
- processor.Manager = self.Manager;
113
- } catch (e) {
114
- self.assistant.error('Error loading processor', processorPath, e)
115
- return resolve()
116
- }
117
-
118
- await processor.process(payload.data.payload)
119
- .then(result => {
120
- payload.response.data = result;
121
- return resolve(result);
122
- })
123
- .catch(e => {
124
- self.Manager.libraries.sentry.captureException(e);
125
- console.error(`Payment processor @ "${processorPath}" failed`, e);
126
- return reject(e);
127
- })
128
- });
129
- },
130
- general_generateUUID: async function (payload) {
131
- const self = this;
132
-
133
- return new Promise(async function(resolve, reject) {
134
-
135
- });
136
- },
137
-
138
- // User
139
- user_createCustomToken: async function (payload) {
140
- const self = this;
141
-
142
- return new Promise(async function(resolve, reject) {
143
- if (payload.user.authenticated || payload.user.roles.admin) {
144
- await self.libraries.admin.auth().createCustomToken(payload.user.auth.uid)
145
- .then(token => {
146
- payload.response.data.token = token;
147
- return resolve(payload);
148
- })
149
- .catch(e => {
150
- payload.response.status = 401;
151
- payload.response.error = new Error(`Failed to create custom token: ${e}`);
152
- return reject(payload.response.error);
153
- })
154
- } else {
155
- payload.response.status = 401;
156
- payload.response.error = new Error('User not authenticated.');
157
- return reject(payload.response.error);
158
- }
159
- });
160
- },
161
- user_delete: async function (payload) {
162
- const self = this;
163
-
164
- return new Promise(async function(resolve, reject) {
165
- if (payload.user.authenticated || payload.user.roles.admin) {
166
- // const planExpireDate = new Date(_.get(payload.user, 'plan.expires.timestamp', 0));
167
- // if (planExpireDate >= new Date()) {
168
- // payload.response.status = 401;
169
- // payload.response.error = new Error(`Failed to delete user: There is an active paid subscription on this account. Please cancel it first and then try deleting the account again.`);
170
- // return reject(payload.response.error);
171
- // }
172
- const isPlanActive = _.get(payload.user, 'plan.payment.active', null);
173
- if (isPlanActive === true) {
174
- payload.response.status = 401;
175
- payload.response.error = new Error(`Failed to delete user: There is an active paid subscription on this account. Please cancel it first and then try deleting the account again.`);
176
- return reject(payload.response.error);
177
- }
178
-
179
- await self.libraries.admin.auth().deleteUser(payload.user.auth.uid)
180
- .then(() => {
181
- return resolve(payload);
182
- })
183
- .catch(e => {
184
- payload.response.status = 401;
185
- payload.response.error = new Error(`Failed to delete user: ${e}`);
186
- return reject(payload.response.error);
187
- })
188
- } else {
189
- payload.response.status = 401;
190
- payload.response.error = new Error('User not authenticated.');
191
- return reject(payload.response.error);
192
- }
193
- });
194
- },
195
- user_signOutAllSessions: async function (payload) {
196
- const self = this;
197
- const powertools = self.Manager.require('node-powertools')
198
- return new Promise(async function(resolve, reject) {
199
- const uid = _.get(payload.user, 'auth.uid', null);
200
-
201
- if (payload.user.authenticated || payload.user.roles.admin && uid) {
202
- await self.libraries.admin.database().ref(`gatherings/online`)
203
- .orderByChild('uid')
204
- .equalTo(uid)
205
- .once('value')
206
- .then(async snap => {
207
- const data = snap.val();
208
- const keys = Object.keys(data || {});
209
- for (var i = 0; i < keys.length; i++) {
210
- const key = keys[i];
211
- self.assistant.log(`Signing out: ${key}`);
212
- await self.libraries.admin.database().ref(`gatherings/online/${key}/command`).set('signout').catch(e => self.assistant.error(`Failed to signout ${key}`, e))
213
- await powertools.wait(3000);
214
- await self.libraries.admin.database().ref(`gatherings/online/${key}`).remove().catch(e => self.assistant.error(`Failed to delete ${key}`, e))
215
- }
216
- })
217
- .catch(e => {
218
- console.error('Gathering query error', e);
219
- })
220
-
221
- await self.libraries.admin
222
- .auth()
223
- .revokeRefreshTokens(uid)
224
- .then(() => {
225
- self.assistant.log('Signed user out of all sessions', payload.user.auth.uid)
226
- payload.data = {message: `Successfully signed ${payload.user.auth.uid} out of all sessions`}
227
- return resolve(payload.data);
228
- })
229
- .catch(e => {
230
- payload.response.status = 500;
231
- payload.response.error = e;
232
- })
233
-
234
- if (payload.response.status >= 200 && payload.response.status < 300) {
235
- return resolve(payload.response.data);
236
- } else {
237
- return reject(payload.response.error);
238
- }
239
- } else {
240
- payload.response.status = 401;
241
- payload.response.error = new Error('User not authenticated.');
242
- return reject(payload.response.error);
243
- }
244
-
245
- });
246
- },
247
- user_getSubscriptionInfo: async function (payload) {
248
- const self = this;
249
- const uid = _.get(payload, 'data.payload.uid', null)
250
-
251
- return new Promise(async function(resolve, reject) {
252
- // console.log('----payload.data', payload.data);
253
-
254
- if (!uid) {
255
- payload.response.status = 401;
256
- payload.response.error = new Error(`Improper uid supplied: ${uid}`);
257
- return reject(payload);
258
- }
259
-
260
- await self.libraries.admin.firestore().doc(`users/${uid}`)
261
- .get()
262
- .then(doc => {
263
- const data = doc.data();
264
- if (!data) {
265
- payload.response.status = 401;
266
- payload.response.error = new Error(`Cannot find user with uid: ${uid}`);
267
- return reject(payload.response.data);
268
- } else {
269
- payload.response.data = {
270
- plan: {
271
- id: data.plan.id,
272
- payment: {
273
- active: data.plan.payment.active,
274
- },
275
- }
276
- }
277
- return resolve(payload.response.data);
278
- }
279
-
280
- })
281
- .catch(e => {
282
- payload.response.status = 500;
283
- payload.response.error = e;
284
- return reject(payload);
285
- })
286
- //
287
- //
288
- // const isPlanActive = _.get(payload.user, 'plan.payment.active', null);
289
- // if (isPlanActive === true) {
290
- // payload.response.status = 401;
291
- // payload.response.error = new Error(`Failed to delete user: There is an active paid subscription on this account. Please cancel it first and then try deleting the account again.`);
292
- // return reject(payload.response.error);
293
- // }
294
- //
295
- // await self.libraries.admin.auth().deleteUser(payload.user.auth.uid)
296
- // .then(() => {
297
- // return resolve(payload);
298
- // })
299
- // .catch(e => {
300
- // payload.response.status = 401;
301
- // payload.response.error = new Error(`Failed to delete user: ${e}`);
302
- // return reject(payload.response.error);
303
- // })
304
- });
305
- },
306
- user_signUp: async function (payload) {
307
- const self = this;
308
-
309
- return new Promise(async function(resolve, reject) {
310
-
311
- });
312
- },
313
-
314
- // Handler
315
- handler_createPost: require('./api/handler/create-post.js'),
316
-
317
- // Admin
318
- admin_createPost: require('./api/admin/create-post.js'),
319
- admin_getStats: async function (payload) {
320
- const self = this;
321
-
322
- return new Promise(async function(resolve, reject) {
323
-
324
- });
325
- },
326
- admin_sendNotification: async function (payload) {
327
- const self = this;
328
-
329
- return new Promise(async function(resolve, reject) {
330
-
331
- });
332
- },
333
- admin_firestoreRead: async function (payload) {
334
- const self = this;
335
-
336
- return new Promise(async function(resolve, reject) {
337
- if (payload.user.authenticated || payload.user.roles.admin) {
338
-
339
- // console.log('---payload.data.payload', payload.data.payload);
340
-
341
- payload.data.payload.path = `${payload.data.payload.path || ''}`;
342
- payload.data.payload.document = payload.data.payload.document || {};
343
- payload.data.payload.options = payload.data.payload.options || { merge: true };
344
-
345
-
346
- if (!payload.data.payload.path) {
347
- payload.response.status = 401;
348
- payload.response.error = new Error('Path parameter required');
349
- return reject(payload);
350
- } else {
351
- await self.libraries.admin.firestore().doc(payload.data.payload.path)
352
- .get()
353
- .then(doc => {
354
- payload.response.data = doc.data();
355
- return resolve(payload.response.data);
356
- })
357
- .catch(e => {
358
- payload.response.status = 500;
359
- payload.response.error = e;
360
- return reject(payload);
361
- })
362
- }
363
-
364
- } else {
365
- payload.response.status = 401;
366
- payload.response.error = new Error('User not authenticated.');
367
- return reject(payload.response.error);
368
- }
369
- });
370
- },
371
- admin_firestoreWrite: async function (payload) {
372
- const self = this;
373
-
374
- return new Promise(async function(resolve, reject) {
375
- if (payload.user.authenticated || payload.user.roles.admin) {
376
-
377
- payload.data.payload.path = `${payload.data.payload.path || ''}`;
378
- payload.data.payload.document = payload.data.payload.document || {};
379
- payload.data.payload.options = payload.data.payload.options || { merge: true };
380
-
381
- if (!payload.data.payload.path) {
382
- payload.response.status = 401;
383
- payload.response.error = new Error('Path parameter required');
384
- return reject(payload);
385
- } else {
386
- await self.libraries.admin.firestore().doc(payload.data.payload.path)
387
- .set(payload.data.payload.document, payload.data.payload.options)
388
- .then(r => {
389
- return resolve(payload);
390
- })
391
- .catch(e => {
392
- payload.response.status = 500;
393
- payload.response.error = e;
394
- return reject(payload);
395
- })
396
- }
397
-
398
- } else {
399
- payload.response.status = 401;
400
- payload.response.error = new Error('User not authenticated.');
401
- return reject(payload.response.error);
402
- }
403
- });
404
- },
405
- admin_query: async function (payload) {
406
- const self = this;
407
-
408
- return new Promise(async function(resolve, reject) {
409
-
410
- });
411
- },
412
-
413
- }
414
- module.exports = Module;
@@ -1,54 +0,0 @@
1
- let fetch;
2
- const _ = require('lodash');
3
-
4
- let Module = {
5
- init: async function (Manager, data) {
6
- this.Manager = Manager;
7
- this.libraries = Manager.libraries;
8
- this.assistant = Manager.Assistant({req: data.req, res: data.res})
9
- this.req = data.req;
10
- this.res = data.res;
11
-
12
- return this;
13
- },
14
- main: async function() {
15
- let self = this;
16
- let libraries = self.libraries;
17
- let assistant = self.assistant;
18
- let req = self.req;
19
- let res = self.res;
20
-
21
- let response = {
22
- status: 200,
23
- data: {},
24
- };
25
-
26
- let user = await assistant.authenticate();
27
-
28
- return libraries.cors(req, res, async () => {
29
- if (!user.authenticated) {
30
- response.status = 401;
31
- response.error = new Error('User not authenticated.');
32
- } else {
33
- await libraries.admin.auth().deleteUser(user.auth.uid)
34
- .then(function() {
35
- response.status = 200;
36
- response.data = {success: true};
37
- })
38
- .catch(function(e) {
39
- response.status = 500;
40
- response.error = e;
41
- });
42
- }
43
-
44
- // assistant.log(assistant.request.data, response);
45
-
46
- if (response.status === 200) {
47
- return res.status(response.status).json(response.data);
48
- } else {
49
- return res.status(response.status).send(response.error.message);
50
- }
51
- });
52
- },
53
- }
54
- module.exports = Module;