forked from sqlpad/sqlpad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
294 lines (236 loc) · 9.54 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
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
#!/usr/bin/env node
var express = require('express');
var router;
var http = require('http');
var path = require('path');
var updateNotifier = require('update-notifier');
var packageJson = require('./package.json');
var app = express();
var react = require('react');
var reactEngine = require('react-engine');
var browserify = require('browserify');
var watchify = require('watchify');
var fs = require('fs');
var engine;
/* Automatic notifier thing that an update is available
============================================================================= */
updateNotifier({pkg: packageJson}).notify();
/* add config to app object
TODO: remove dependency on attaching config values to app object
Turns out node.js cache's the require() of a module
Instead of attaching config to the app object,
just require('./lib/config.js') around the app.
(Sometimes we need config when we don't need the app object)
============================================================================= */
var config = require('./lib/config.js');
if (config.debug) {
console.log("CONFIG:");
console.log(config);
}
app.set('debug', config.debug);
app.set('passphrase', config.passphrase);
app.set('dbPath', config.dbPath);
app.set('port', config.port);
app.set('ip', config.ip);
app.set('baseUrl', config.baseUrl);
if (config.hasOwnProperty('dev')) app.set('dev', true);
if (config.admin) app.set('admin', config.admin);
/* Boostrap app object with stuff
This allows us to pass app around and all the related utility/helper/db
functions and variables go with it.
TODO: move to just requiring needed files directly
============================================================================= */
require('./lib/add-db-to-app.js')(app);
require('./lib/add-cipher-decipher-to-app.js')(app);
require('./lib/add-open-admin-registration-to-app.js')(app);
require('./lib/add-email-domain-whitelist-to-app.js')(app);
/* Express setup
============================================================================= */
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var cookieSession = require('cookie-session');
var morgan = require('morgan');
var passport = require('passport');
var connectFlash = require('connect-flash');
var errorhandler = require('errorhandler');
var reactroutes;
var serverstarted = false;
app.locals.title = 'SqlPad';
app.locals.version = packageJson.version;
if ( config.engine === 'react' ) {
reactroutes = require('./routes/routes.jsx');
router = app;
engine = reactEngine.server.create({
routes:reactroutes,
routesFilePath: path.join(__dirname, 'routes/routes.jsx')
});
app.engine('.jsx', engine);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jsx');
app.set('view', reactEngine.expressView);
} else {
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
router = express.Router();
}
if (process.env.NODE_ENV === 'development') {
// only use in development
app.use(errorhandler());
}
app.use(favicon(__dirname + '/public/images/favicon.ico'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(methodOverride("_method")); // simulate PUT/DELETE via POST in client by <input type="hidden" name="_method" value="put" />
app.use(cookieParser(app.get('passphrase'))); // populates req.cookies with an object
app.use(cookieSession({secret: app.get('passphrase')}));
app.use(connectFlash());
app.use(passport.initialize());
app.use(passport.session());
app.use(config.baseUrl, express.static(path.join(__dirname, 'public')));
if (app.get('dev')) app.use(morgan('dev'));
app.use(function (req, res, next) {
// Boostrap res.locals with any common variables
res.locals.errors = req.flash('error');
res.locals.message = null;
res.locals.navbarConnections = [];
res.locals.debug = null;
res.locals.query = null;
res.locals.queryMenu = false;
res.locals.session = req.session || null;
res.locals.pageTitle = "";
res.locals.openAdminRegistration = app.get('openAdminRegistration');
res.locals.user = req.user;
res.locals.isAuthenticated = req.isAuthenticated();
res.locals.baseUrl = config.baseUrl;
res.locals.engine = config.engine;
// Expose key-value configs as a common variable
var db = app.get('db');
db.config.find({}, function (err, configItems) {
if (err) {
res.send({
success: false,
error: err.toString()
});
} else {
var keyValueConfig = {};
for (var i = 0; i < configItems.length; i++) {
keyValueConfig[configItems[i]['key']] = configItems[i]['value'];
}
res.locals.configItems = JSON.stringify(keyValueConfig);
}
next();
});
});
app.use(function (req, res, next) {
// if not signed in redirect to sign in page
// if (req.isAuthenticated()) {
next();
/*} else if (req._parsedUrl.pathname === config.baseUrl + '/signin' || req._parsedUrl.pathname === config.baseUrl + '/signup' || req._parsedUrl.pathname.indexOf(config.baseUrl + '/auth/') == 0) {
next();
} else if (app.get('openRegistration')) {
// if there are no users whitelisted, direct to signup
res.redirect(config.baseUrl + '/signup');
} else {
res.redirect(config.baseUrl + '/signin');
}*/
});
/* Must Be Admin middleware
Some places are restricted to admins.
This middleware and middleware assignment handles that.
============================================================================= */
function mustBeAdmin (req, res, next) {
if (req.user.admin) {
next();
} else {
throw "You must be an admin to do that";
}
}
app.use('/connections', mustBeAdmin);
app.use('/users', mustBeAdmin);
app.use('/config', mustBeAdmin);
/* Routes begins here
The modules in ./routes/ are just functions that take the app object
and build out the routes.
/ (redirects to queries or connections)
/signup (open to everyone, but you gotta be whitelisted to use it)
/signin (default if not logged in)
/queries (lists queries)
/connections (list/create/update/delete connections)
Generally, I try to follow the standard convention.
But sometimes I don't though:
create → POST /collection
read → GET /collection[/id]
update → PUT /collection/id
delete → DELETE /collection/id
============================================================================= */
require('./routes/oauth.js')(app, passport, router);
require('./routes/homepage.js')(app, router);
require('./routes/onboarding.js')(app, router);
require('./routes/user-admin.js')(app, router);
require('./routes/connections.js')(app, router);
require('./routes/queries.js')(app, router);
require('./routes/run-query.js')(app, router); // ajaxy route used for executing query and getting results
require('./routes/download-results.js')(app, router); // streams cached query results to browser
require('./routes/schema-info.js')(app, router);
require('./routes/configs.js')(app, router);
require('./routes/tags.js')(app, router);
if ( config.engine === 'react' ) {
app.use(config.baseUrl, function(req, res, next) {
res.render(req.url, {});
});
/* Start the Server
============================================================================= */
var b = browserify({
entries: ['./client-js/main-react.js'],
cache: {},
packageCache: {},
plugin: [watchify]/*,
bundleExternal: false,
"browserify-shim":{"codemirror": "global:codemirror"},
libs: {
options: {
shim: {
"codemirror": {
path: './node_modules/codemirror/lib/codemirror.js',
exports: 'global:codemirror'
}
}
}
}*/
});
b.on('update', function(){
b.transform("babelify",{presets: ['es2015', 'react']}).bundle().on("error",function(err){
// print the error (can replace with gulp-util)
console.log(err);
// end this stream
//this.emit('end');
}).pipe(fs.createWriteStream('./public/javascripts/browserified.js'));
});
b.on('bundle',function(){
if ( serverstarted !== true ) {
serverstarted = true;
http.createServer(app).listen(app.get('port'), app.get('ip'), function(){
console.log('\nWelcome to ' + app.locals.title + '!. Visit http://'+(app.get('ip') == '0.0.0.0' ? 'localhost' : app.get('ip')) + ':' + app.get('port') + app.get('baseUrl') + ' to get started');
});
}
});
b.transform("babelify",{
presets: ['es2015', 'react']
}).bundle().on("error",function(err){
// print the error (can replace with gulp-util)
console.log(err);
// end this stream
this.emit('end');
}).pipe(fs.createWriteStream('./public/javascripts/browserified.js'));
//app.use(config.baseUrl, router);
} else {
app.use(config.baseUrl, router);
serverstarted = true;
http.createServer(app).listen(app.get('port'), app.get('ip'), function(){
console.log('\nWelcome to ' + app.locals.title + '!. Visit http://'+(app.get('ip') == '0.0.0.0' ? 'localhost' : app.get('ip')) + ':' + app.get('port') + app.get('baseUrl') + ' to get started');
});
}