-
Notifications
You must be signed in to change notification settings - Fork 9
/
startup.js
275 lines (221 loc) · 7.79 KB
/
startup.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
/* ====================================
* setup.js
* - connects to teh database and sets up prerequasit
* ====================================
*/
var rek = require('rekuire');
// get nodejs included modules
var http = require('http');
var https = require('https');
var path = require('path');
// get express and it's official middleware
var express = require('express');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var errorhandler = require('errorhandler');
// 3ed party middleware
var flash = require('connect-flash');
var passport = require('passport');
// get our routes
var routes = rek('routes');
var auth = rek('auth.js');
// load the configuration
var Config = rek('config.js');
var async = require('async');
var VError = require('verror');
var DB = rek('db');
var Users = DB.Users;
var Configs = DB.Configs
var gdb = DB.getDb;
var scribe = rek('scribe');
var startup;
module.exports = startup = {};
var template_config = {
name: "",
pairs: [],
signals: {},
pass: ""
};
startup.setupScribe = function() {
// configure logging
scribe.configure(function(){
scribe.set('app', 'RyBot_Trader'); // NOTE Best way learn about these settings is
scribe.set('logPath', global.appdir + '/scribe'); // them out for yourself.
scribe.set('defaultTag', 'DEFAULT_TAG');
scribe.set('divider', ':::');
scribe.set('identation', 5); // Identation before console messages
scribe.set('maxTagLength', 30); // Any tags that have a length greather than
// 30 characters will be ignored
scribe.set('mainUser', process.env.USER); // Username of the account which is running
// the NodeJS server
});
scribe.addLogger("log", true , true, 'green'); // (name, save to file, print to console, tag color
scribe.addLogger("warn", true , true, 'yellow');
scribe.addLogger("error", true , true, 'red');
scribe.addLogger('realtime', true, true, 'underline');
scribe.addLogger('high', true, true, 'magenta');
scribe.addLogger('normal', true, true, 'white');
scribe.addLogger('low', true, true, 'grey');
}
startup.buildApp = function () {
// set up the express server
var app = express();
// all environments
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// development only
if ('development' == app.get('env') && !global.TESTING) {
app.use(scribe.express.logger(function(req, res){ // Express.js access log
return true; // Filter out any Express messages
}));
}
// we want cookies
app.use(cookieParser(Config.cookieSecret));
// we want our cookies to store our session
app.use(expressSession({
cookie: { maxAge: Config.cookieMaxAge },
secret: Config.cookieSecret,
resave: true,
saveUninitialized: true
}));
// we want to be able to use flash messages
app.use(flash());
// set up authentication middleware
app.use(passport.initialize());
app.use(passport.session());
auth.setupAuth();
// parse request bodies
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// let us overide HTTP verbs
app.use(methodOverride());
// development only
if ('development' == app.get('env')) {
app.use(errorhandler());
}
// respond to static paths
app.use(express.static(path.join(__dirname, 'public')));
//add routes
routes.addRoutes(app);
routes.addErrorRoutes(app)
return app;
};
var serverHTTP, serverHTTPS;
startup.run = function(app, callback, dbname) {
startup.prepare( function(err, results){
if (err) {
global.BAD_ERROR = err;
console.error("[Startup]", err.stack);
}
var tasks = [];
if (Config.runHTTPS) {
tasks.push(function(cb){
serverHTTPS = https.createServer(app).listen(Config.serverHTTPSPort, Config.serverIp, function(){
console.log('[Server] HTTPS Express server listening on ' + Config.serverHTTPSIp + ":" + Config.serverPort);
cb(null, true);
});
});
}
if (!Config.HTTPSOnly || !Config.runHTTPS) {
tasks.push(function(cb){
serverHTTP = http.createServer(app).listen(Config.serverPort, Config.serverIp, function(){
console.log('[Server] HTTP Express server listening on ' + Config.serverIp + ":" + Config.serverPort);
cb(null, true);
});
});
}
async.parallel(tasks, function(err, results) {
// all servers running
callback(null, true);
});
}, dbname);
};
startup.stop = function(callback) {
var tasks = [];
if (serverHTTP) {
tasks.push(function(cb){
serverHTTP.close(function () {
console.log("[Server] HTTP Closed out remaining connections.");
cb(null, true);
});
});
}
if (serverHTTPS) {
tasks.push(function(cb){
serverHTTPS.close(function () {
console.log("[Server] HTTPS Closed out remaining connections.");
cb(null, true);
});
});
}
if (tasks.length > 0) {
async.parallel(tasks, function(err, results) {
// Close db connections, etc.
DB.close();
callback(null, true);
});
}
};
startup.configure = function(cb) {
Configs.listConfigs({main: true}, function(err, configs) {
if (err) return cb(err);
if (configs.length < 1) {
global.SETUP = true;
console.warn("[Startup] Setup needed");
} else {
global.CONFIG = configs[0];
global.SETUP = false;
}
return cb(null, global.SETUP);
});
};
startup.ensure_users = function(cb) {
Users.listUsers({}, function(err, users) {
if (err) return cb(err);
if (users.length < 1 && !global.SETUP) {
global.SETUP = true;
}
return cb(null, global.SETUP);
});
};
startup.prepare = function(callback, dbname) {
// Establish connection to db
DB.open(function(err, db) {
if (err) {
var err1 = new VError(err, "Failed to Connect to Database");
return callback(err1);
}
var setup_db = function() {
var tasks = [];
tasks.push(startup.configure);
tasks.push(startup.ensure_users);
async.series(tasks, function(err, results) {
if (err) return callback(err);
return callback(null, results);
});
};
if (Config.dbUser !== "") {
db.authenticate(Config.dbUser, Config.dbPass, {authdb: Config.dbAuthName}, function(err, result) {
var new_err;
if (err) {
new_err= new VError(err, "Failed to Authenticate with Database");
console.error(new_err);
return callback(new_err);
}
if (!result) {
new_err = new VError("Failed to Authenticate with Database");
console.error(new_err);
return callback(new_err);
}
setup_db();
});
} else {
setup_db();
}
}, dbname);
};