forked from jupiter-project/metis-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
243 lines (194 loc) · 8.98 KB
/
server.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
require('appoptics-apm');
const url = require('url');
const kue = require('kue');
const fs = require('fs');
if (process.env.NODE_ENV !== 'production') {
require('dotenv').load();
}
require('babel-register')({
presets: ['react'],
});
// Loads Express and creates app object
const express = require('express');
const app = express();
const port = process.env.PORT || 4000;
const pingTimeout = 9000000;
const pingInterval = 30000;
// Loads job queue modules and variables
const jobs = kue.createQueue({
redis: {
host: process.env.REDIS_HOST || 'localhost',
port: process.env.REDIS_PORT || '6379',
auth: process.env.REDIS_PASSWORD || undefined,
},
});
// Loads path
// const path = require('path');
// Loads Body parser
const bodyParser = require('body-parser');
// Loads react libraries
const React = require('react');
const ReactDOMServer = require('react-dom/server');
// Loads request library
// const request = require('request')
// Loads passport for authentication
const passport = require('passport');
const flash = require('connect-flash');
// Request logger
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
// File and folder finding module
const find = require('find');
const mongoose = require('mongoose');
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for authentication)
app.use(express.urlencoded({ extended: true })) // get information from html forms
app.use((req, res, next) => {
if (req.url !== '/favicon.ico') {
return next();
}
res.status(200);
res.header('Content-Type', 'image/x-icon');
res.header('Cache-Control', 'max-age=4294880896');
res.end();
return null;
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Here is where we load the api routes. We put them here so passport deserializer
// is not called everytime we make an api call to them
require('./config/api.js')(app);
// Sets public directory
app.use(express.static(`${__dirname}/public`));
// required for passport
const sessionSecret = process.env.SESSION_SECRET !== undefined ? process.env.SESSION_SECRET : 'undefined';
const sslOptions = {};
if (process.env.CERTFILE) { // Set the certificate file
sslOptions.cert = fs.readFileSync(`${__dirname}/${process.env.CERTFILE}`);
}
if (process.env.KEYFILE) { // set the key file
sslOptions.key = fs.readFileSync(`${__dirname}/${process.env.KEYFILE}`);
}
// Create a session middleware with the given options.
// @see https://www.npmjs.com/package/express-session
app.use(session({
secret: sessionSecret,
saveUninitialized: true,
resave: false,
store: new RedisStore({
host: process.env.REDIS_HOST || 'localhost',
port: process.env.REDIS_PORT || '6379',
auth_pass: process.env.REDIS_PASSWORD || undefined,
}),
// @see https://stackoverflow.com/questions/16434893/node-express-passport-req-user-undefined
cookie: { secure: (sslOptions.length) }, // use secure cookies if SSL env vars are present
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// If both cert and key files env vars exist use https,
// otherwise use http
const server = Object.keys(sslOptions).length >= 2
? require('https').createServer(sslOptions, app)
: require('http').createServer(app);
// Enables websocket
const socketIO = require('socket.io');
const socketService = require('./services/socketService');
const socketOptions = {
pingTimeout, // pingTimeout value to consider the connection closed
pingInterval, // how many ms before sending a new ping packet
};
const io = socketIO(server, socketOptions);
io.of('/chat').on('connection', socketService.connection.bind(this));
// TODO uncomment this lines once we implemented jupiter listener
const jupiterSocketService = require('./services/jupiterSocketService');
const WebSocket = require('ws');
const jupiterWss = new WebSocket.Server({ noServer: true });
jupiterWss.on('connection', jupiterSocketService.connection.bind(this));
server.on('upgrade', function upgrade(request, socket, head) {
const pathname = url.parse(request.url).pathname;
console.log(pathname);
if (pathname === '/jupiter') {
jupiterWss.handleUpgrade(request, socket, head, (ws) => {
jupiterWss.emit('connection', ws, request);
});
} else {
socket.destroy();
}
});
const logger = require('./utils/logger')(module);
const mongoDBOptions = { useNewUrlParser: true, useFindAndModify: false, useUnifiedTopology: true };
const {
serializeUser, deserializeUser, metisSignup, metisLogin,
} = require('./config/passport');
serializeUser(passport); // pass passport for configuration
deserializeUser(passport); // pass passport for configuration
metisSignup(passport); // pass passport for configuration
metisLogin(passport, jobs, io); // pass passport for configuration
// Sets get routes. Files are converted to react elements
find.fileSync(/\.js$/, `${__dirname}/controllers`).forEach((file) => {
require(file)(app, passport, React, ReactDOMServer, jobs);
});
// Route any invalid routes black to the root page
app.get('/*', (req, res) => {
req.flash('errorMessage', 'Invalid route');
res.redirect('/');
});
// Gravity call to check app account properties
const { gravity } = require('./config/gravity');
gravity.getFundingMonitor()
.then(async (monitorResponse) => {
const { monitors } = monitorResponse;
if (monitors.length === 0) {
logger.info('Funding property not set for app. Setting it now...');
const fundingResponse = await gravity.setFundingProperty({
passphrase: process.env.APP_ACCOUNT,
});
logger.info(`Jupiter response: ${JSON.stringify(fundingResponse)}`);
}
});
// Worker methods
const RegistrationWorker = require('./workers/registration.js');
// const TransferWorker = require('./workers/transfer.js');
const registrationWorker = new RegistrationWorker(jobs, io);
// registrationWorker.reloadActiveWorkers('completeRegistration')
// .catch((error) => { if (error.error) console.log(error.message); });
// const transferWorker = new TransferWorker(jobs);
jobs.process('completeRegistration', (job, done) => {
registrationWorker.checkRegistration(job.data, job.id, done);
});
/* jobs.process('fundAccount', (job, done) => {
transferWorker.fundAccount(job.data, job.id, done);
}); */
mongoose.connect(process.env.URL_DB, mongoDBOptions, (err, resp) => {
if (err) {
throw err;
}
logger.info('Mongo DB Online.');
});
// Tells server to listen to port 4000 when app is initialized
server.listen(port, () => {
logger.info(JSON.stringify(process.memoryUsage()));
logger.info('');
logger.info('_________________________________________________________________');
logger.info(' ▄▄ ▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ');
logger.info('▐░░▌ ▐░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌');
logger.info('▐░▌░▌ ▐░▐░▌▐░█▀▀▀▀▀▀▀▀▀ ▀▀▀▀█░█▀▀▀▀ ▀▀▀▀█░█▀▀▀▀ ▐░█▀▀▀▀▀▀▀▀▀ ');
logger.info('▐░▌▐░▌ ▐░▌▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ');
logger.info('▐░▌ ▐░▐░▌ ▐░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ');
logger.info('▐░▌ ▐░▌ ▐░▌▐░░░░░░░░░░░▌ ▐░▌ ▐░▌ ▐░░░░░░░░░░░▌');
logger.info('▐░▌ ▀ ▐░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌ ▀▀▀▀▀▀▀▀▀█░▌');
logger.info('▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌');
logger.info('▐░▌ ▐░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▄▄▄▄█░█▄▄▄▄ ▄▄▄▄▄▄▄▄▄█░▌');
logger.info('▐░▌ ▐░▌▐░░░░░░░░░░░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌');
logger.info(' ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ');
logger.info('_________________________________________________________________');
logger.info('');
logger.info(`Metis version ${process.env.VERSION} is now running on port ${port} 🎉`);
logger.info(`Jupiter Node running on ${process.env.JUPITERSERVER}`);
});
kue.app.listen(4001, () => {
logger.info('Job queue server running on port 4001');
});