@feardread/fear 1.2.1 → 2.0.1

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/FEAR.js CHANGED
@@ -1,10 +1,13 @@
1
1
  const path = require("path");
2
2
  const fs = require("fs");
3
3
  const express = require("express");
4
+ const session = require('express-session');
4
5
  const compression = require("compression");
5
6
  const cookieParser = require("cookie-parser");
6
7
  const fileUpload = require("express-fileupload");
7
8
  const cors = require("cors");
9
+ const MongoStore = require('connect-mongo');
10
+ const passport = require('passport');
8
11
 
9
12
  module.exports = FEAR = (() => {
10
13
  // Private constants
@@ -14,7 +17,7 @@ module.exports = FEAR = (() => {
14
17
  const AGENT_ROUTE_PATH = '/fear/api/agent';
15
18
 
16
19
  // Constructor function
17
- const FEAR = function() {
20
+ const FEAR = function (config) {
18
21
  this.app = express();
19
22
  this.Router = express.Router;
20
23
  this.server = null;
@@ -29,100 +32,67 @@ module.exports = FEAR = (() => {
29
32
  this.logo = null;
30
33
  this.origins = [];
31
34
  this.corsConfig = null;
35
+ this.stripe = null;
36
+ this.paypal = null;
37
+ this.passport = null;
38
+ this.mailer = null;
39
+
32
40
 
33
- // Initialize
34
41
  this.setupEnvironment();
35
42
  this.setupDependencies();
43
+ if (this.env.ADD_PAYMENTS) this.setupProcessors();
44
+ this.setupMailer();
36
45
  this.setupMiddleware();
37
46
  this.corsConfig = this.getCorsConfig();
38
47
  this.setupRoutes();
39
48
  };
40
49
 
41
- // Consolidated prototype
50
+
42
51
  FEAR.prototype = {
43
52
  constructor: FEAR,
44
-
45
- /**
46
- * Get AI Agent service instance
47
- */
48
- getAiAgent() {
49
- return this.agentService;
53
+ getStripe() {
54
+ return this.stripe;
55
+ },
56
+ getPassport() {
57
+ return this.passport;
50
58
  },
51
-
52
- /**
53
- * Clear global FearRouter
54
- */
55
59
  clearGlobal() {
56
60
  delete global.FearRouter;
57
61
  return this;
58
62
  },
59
-
60
- /**
61
- * Get Express app instance
62
- */
63
63
  getApp() {
64
64
  return this.app;
65
65
  },
66
-
67
- /**
68
- * Get logger instance
69
- */
70
66
  getLogger() {
71
67
  return this.logger;
72
68
  },
73
-
74
- /**
75
- * Get database instance
76
- */
77
69
  getDatabase() {
78
70
  return this.db;
79
71
  },
80
-
81
- /**
82
- * Get environment configuration
83
- */
84
72
  getEnvironment() {
85
73
  return this.env;
86
74
  },
87
-
88
- /**
89
- * Get cloud service instance
90
- */
91
75
  getCloud() {
92
76
  return this.cloud;
93
77
  },
94
-
95
- /**
96
- * Get Express Router
97
- */
98
78
  getRouter() {
99
79
  return this.Router;
100
80
  },
101
-
102
- /**
103
- * Get validator instance
104
- */
105
81
  getValidator() {
106
82
  return this.validator;
107
83
  },
108
-
109
- /**
110
- * Get handler instance
111
- */
112
84
  getHandler() {
113
85
  return this.handler;
114
86
  },
115
-
116
- /**
117
- * Get CORS configuration
118
- */
87
+ getPaypal() {
88
+ return this.paypal;
89
+ },
90
+ getMailer() {
91
+ return this.mailer;
92
+ },
119
93
  getCorsConfigValue() {
120
94
  return this.corsConfig;
121
95
  },
122
-
123
- /**
124
- * Setup environment variables from .env file
125
- */
126
96
  setupEnvironment() {
127
97
  const envResult = require("dotenv").config({ path: ".env" });
128
98
 
@@ -138,6 +108,7 @@ module.exports = FEAR = (() => {
138
108
  */
139
109
  setupDependencies() {
140
110
  this.logger = require("./libs/logger");
111
+ this.passport = require('./libs/passport');
141
112
  this.morgan = require("./libs/logger/morgan");
142
113
  this.cloud = require("./libs/cloud");
143
114
  this.db = require("./libs/db");
@@ -147,29 +118,66 @@ module.exports = FEAR = (() => {
147
118
  this.origins = this.getAllowedOrigins();
148
119
  },
149
120
 
121
+ setupProcessors() {
122
+ const StripeHandler = require("./libs/stripe");
123
+ const PayPal = require('./libs/paypal');
124
+
125
+ if ( !this.env.PAYPAL_CLIENT_ID|| !this.env.STRIPE_API_KEY ) {
126
+ this.logger.warn('Missing environment values in .env file')
127
+ }
128
+
129
+ this.stripe = new StripeHandler(this);
130
+ this.paypal = new PayPal(this);
131
+ },
132
+
150
133
  /**
151
134
  * Setup Express middleware
152
135
  */
153
136
  setupMiddleware() {
154
137
  this.app.set("PORT", this.env.NODE_PORT || DEFAULT_PORT);
155
-
156
- this.app.use(this.morgan);
157
138
  this.app.use(express.json({ limit: DEFAULT_JSON_LIMIT }));
139
+ this.app.use(express.urlencoded({ extended: true }));
140
+ this.app.use(session({
141
+ secret: process.env.SESSION_SECRET,
142
+ resave: false,
143
+ saveUninitialized: false,
144
+ //store: MongoStore.create({
145
+ //mongoUrl: process.env.DB_LINK,
146
+ //touchAfter: 24 * 3600 // lazy session update (24 hours)
147
+ //}),
148
+ cookie: {
149
+ maxAge: 1000 * 60 * 60 * 24 * 7, // 1 week
150
+ httpOnly: true,
151
+ secure: process.env.NODE_ENV === 'production' // HTTPS only in production
152
+ }
153
+ }));
154
+ this.app.use(this.morgan);
158
155
  this.app.use(compression());
159
156
  this.app.use(fileUpload());
160
157
  this.app.use(cookieParser());
158
+ this.app.use(passport.initialize());
159
+ this.app.use(passport.session());
161
160
 
162
- // Request logging middleware
161
+ require('./libs/passport');
163
162
  this.app.use((req, res, next) => {
164
163
  this.logger.info(`FEAR API Query :: ${req.url}`);
165
- res.locals.user = req.user;
164
+ res.locals.user = req.user || null;
166
165
  next();
167
166
  });
168
167
  },
169
168
 
170
- /**
171
- * Parse allowed origins from environment
172
- */
169
+ setupMailer() {
170
+ const mailService = (this.env.NODE_ENV === 'production') ? 'mailgun' : 'google';
171
+ const mailinfo = require('./libs/emailer/info');
172
+ const smtp = require('./libs/emailer/smtp')
173
+
174
+ mailinfo.service = mailService;
175
+ this.mailinfo = mailinfo;
176
+ if ( !this.mailer ) {
177
+ this.mailer = new smtp(this);
178
+ }
179
+ },
180
+
173
181
  getAllowedOrigins() {
174
182
  if (!this.env.ALLOWED_ORIGINS) return [];
175
183
 
@@ -179,9 +187,6 @@ module.exports = FEAR = (() => {
179
187
  .filter(origin => origin.length > 0);
180
188
  },
181
189
 
182
- /**
183
- * Get CORS configuration object
184
- */
185
190
  getCorsConfig() {
186
191
  return {
187
192
  credentials: true,
@@ -198,9 +203,6 @@ module.exports = FEAR = (() => {
198
203
  };
199
204
  },
200
205
 
201
- /**
202
- * Auto-load routes from routes directory
203
- */
204
206
  setupRoutes() {
205
207
  const routesDir = path.join(__dirname, "routes");
206
208
 
@@ -230,9 +232,6 @@ module.exports = FEAR = (() => {
230
232
  }
231
233
  },
232
234
 
233
- /**
234
- * Register a single router
235
- */
236
235
  useRouter(router, routePath = DEFAULT_ROUTE_PATH, corsOptions = null) {
237
236
  if (!router || typeof router !== 'function') {
238
237
  throw new Error('Router must be a valid Express router instance');
@@ -253,9 +252,6 @@ module.exports = FEAR = (() => {
253
252
  return this;
254
253
  },
255
254
 
256
- /**
257
- * Register multiple routers
258
- */
259
255
  useRouters(routers) {
260
256
  if (!Array.isArray(routers)) {
261
257
  throw new Error('Routers must be an array');
@@ -274,9 +270,6 @@ module.exports = FEAR = (() => {
274
270
  return this;
275
271
  },
276
272
 
277
- /**
278
- * Create a new router with FEAR utilities attached
279
- */
280
273
  createRouter() {
281
274
  const router = express.Router();
282
275
 
@@ -287,14 +280,13 @@ module.exports = FEAR = (() => {
287
280
  router.getHandler = () => this.handler;
288
281
  router.getValidator = () => this.validator;
289
282
  router.getAiAgent = () => this.agentService;
283
+ router.getStripe = () => this.stripe;
284
+ router.getPaypal = () => this.paypal;
290
285
  //router.getAgentWebInterface = () => this.agentWebInterface;
291
286
 
292
287
  return router;
293
288
  },
294
289
 
295
- /**
296
- * Get list of registered routers
297
- */
298
290
  getRegisteredRouters() {
299
291
  return this.registeredRouters.map(info => ({
300
292
  path: info.path,
@@ -302,9 +294,6 @@ module.exports = FEAR = (() => {
302
294
  }));
303
295
  },
304
296
 
305
- /**
306
- * Start the HTTP server
307
- */
308
297
  start(port = null) {
309
298
  const serverPort = port || this.app.get("PORT") || DEFAULT_PORT;
310
299
 
@@ -314,22 +303,19 @@ module.exports = FEAR = (() => {
314
303
  this.logger.error(`Failed to start server on port ${serverPort}:`, err);
315
304
  return reject(err);
316
305
  }
317
-
306
+
318
307
  this.logger.info(`FEAR server started on port ${serverPort}`);
319
-
308
+
320
309
  // Log agent interface status
321
310
  if (this.agentWebInterface) {
322
311
  this.logger.info(`Agent Web Interface available at ${AGENT_ROUTE_PATH}`);
323
312
  }
324
-
313
+
325
314
  resolve(this.server);
326
315
  });
327
316
  });
328
317
  },
329
318
 
330
- /**
331
- * Gracefully shutdown the server
332
- */
333
319
  shutdown() {
334
320
  this.logger.info('Initiating graceful shutdown...');
335
321
 
@@ -347,7 +333,7 @@ module.exports = FEAR = (() => {
347
333
  }
348
334
 
349
335
  // Shutdown agent web interface
350
- const agentShutdown = this.agentWebInterface &&
336
+ const agentShutdown = this.agentWebInterface &&
351
337
  typeof this.agentWebInterface.shutdown === 'function' ?
352
338
  this.agentWebInterface.shutdown() :
353
339
  Promise.resolve();
@@ -369,9 +355,6 @@ module.exports = FEAR = (() => {
369
355
  });
370
356
  },
371
357
 
372
- /**
373
- * Close database connections
374
- */
375
358
  closeDatabase() {
376
359
  return new Promise((resolve, reject) => {
377
360
  if (this.db && typeof this.db.disconnect === 'function') {
@@ -387,9 +370,6 @@ module.exports = FEAR = (() => {
387
370
  });
388
371
  },
389
372
 
390
- /**
391
- * Set FEAR utilities as global
392
- */
393
373
  setAsGlobal() {
394
374
  global.FearRouter = {
395
375
  createRouter: () => this.createRouter(),
@@ -397,8 +377,8 @@ module.exports = FEAR = (() => {
397
377
  getDatabase: () => this.db,
398
378
  getEnvironment: () => this.env,
399
379
  getCloud: () => this.cloud,
400
- getAiAgent: () => this.agentService,
401
- getAgentWebInterface: () => this.agentWebInterface
380
+ getStripe: () => this.stripe,
381
+ initProcessors: this.setupProcessors
402
382
  };
403
383
  return this;
404
384
  }
@@ -407,9 +387,6 @@ module.exports = FEAR = (() => {
407
387
  return FEAR;
408
388
  })();
409
389
 
410
- /**
411
- * Factory function to create new FEAR instance
412
- */
413
390
  exports.FearFactory = () => {
414
391
  return new FEAR();
415
392
  };