-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb.js
424 lines (390 loc) · 10 KB
/
web.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
var express = require('express'),
stylus = require('stylus'),
nib = require('nib'),
url = require('url'),
db = require('./db'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
fs = require('fs');
//Use the env port when specified
var port = process.env.OPENSHIFT_NODEJS_PORT || process.env.PORT || 8000;
var ip = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var app = express();
app.enable('trust proxy');
app.use(express.logger());
app.use(express.compress());
app.use(express.bodyParser());
//extend compile function for stylus to use nib
function compile(str, path) {
return stylus(str)
.set('filename', path)
.set('compress', true)
.use(nib());
}
//setup stylus
app.use(stylus.middleware(
{
src: __dirname + '/style',
dest: __dirname + '/public',
compile: compile
}
));
//setup jade
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
//turn on static file hosting for stylesheets and javascript
// may turn this off later and open files manually to reduce
// disk io
app.use(express.static(__dirname + '/public'));
app.use(express.cookieParser());
app.use(express.session({secret : 'r=q%JryR]=us7|@oYL}"~5>T_#rWge;B'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
//Set up the authentication strategy, in this case, just see if
// the passwords match because we are already sending hashed
// passwords over https
passport.use(new LocalStrategy(
function(username, password, done) {
db.get('users',{ username: username },
function (err, res) {
if (err) { return done(err,false); }
if (res.length == 0) {return done(null,false);}
var user = res[0];
if(user.password == password)
return done(null,user);
else
return done(null,false);
});
}));
passport.serializeUser(
function(user,done) {
done(null,user._id);
});
passport.deserializeUser(
function(id,done) {
db.get('users',{_id : db.ObjectID(id)},
function(err,results) {
if(results.length > 0) {
done(err,results[0]);
}
else {
done(err,null);
}
});
});
function start() {
//use https
app.all('*',
function(req,res,next) {
if(req.protocol == 'https' || ip == '127.0.0.1') {
next();
}
else {
res.redirect('https://' + req.get('host') + req.url);
}
});
//homepage
app.get('/',
function(req,res) {
res.render('index',
{title : 'APIDocs', user : req.user});
});
//authentication
//login page
app.get('/login',
function (req,res) {
res.render('login',
{title : 'APIDocs - Login', user : req.user});
});
//authenticate a user
app.post('/login', passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login' }));
//log the user out
app.get('/logout',
function(req,res) {
req.logout();
res.redirect('/');
});
//create a new user
app.post('/account',
function (req,res) {
db.get('users',{username : req.body.username},
function(err,results) {
if(results.length > 0) {
res.status(403);
res.render('msg', {title : 'APIDocs - Account', user : req.user,
status : '403', message : 'An account with that username already exists.'});
}
else {
var user = new Object();
user.username = req.body.username;
user.password = req.body.password;
db.put('users',user,
function (err) {
if(err) {
res.status(500);
res.render('msg', {title : 'APIDocs - Account', user : req.user,
status : '500', message : 'The server experienced an error creating your account.'});
}
else {
res.status(201);
res.render('msg', {title : 'APIDocs - Account', user : req.user,
status : '201', message : 'Account created successfully!'});
}
});
}
});
});
//respond to a request "req" for an API for which the database contains "results"
function respondWithApi(err, results, req, res) {
console.log(results);
if(results.length > 0) {
if(typeof req.query.json != 'undefined') {
res.writeHead(200,'OK', {'Content-Type' : 'application/json'});
res.end(JSON.stringify(results[0]));
}
else {
res.render('api',{api : results[0],
title : 'APIDocs - ' + results[0].fullName,
user : req.user});
}
}
//404
else {
res.status(404);
res.render('msg',
{title : 'APIDocs - 404', user : req.user, status : '404', message : 'API not found.'});
}
}
//get a dummy root api, which has all language roots as children
app.get("/api",
function (req, res) {
db.get('api', {path : ''},
function(err, results) {
var api =
{
name : 'APIDocs',
path : '',
type : 'Collection',
children : results.map(function(api) {return api.name}),
attr : []
};
respondWithApi(err, [api], req, res);
});
});
//get an existing api
app.get("/api/*",
function (req,res) {
var apiFullName = req.params[0]
console.log(apiFullName);
db.get('api',{fullName : apiFullName}, function(error, results) {
respondWithApi(error, results, req, res);
});
});
app.get('/upload',
function(req,res) {
db.get('api',{path : ''},
function(err,results) {
res.render('upload',{title : 'APIDocs - Upload',
user : req.user,
roots : results});
});
});
//
function validAPI(api,root) {
if(typeof api == 'undefined' ||
typeof api.name == 'undefined' ||
typeof api.path == 'undefined' ||
typeof api.type == 'undefined') {
return false;
}
if(!api.fullName) {
if(api.path != '') {
api.fullName = api.path + '/' + api.name;
}
else {
api.fullName = api.name;
}
}
if(!api.children) {
api.children = [];
}
if(!api.attr) {
api.attr = [];
}
if(root != '') {
if(api.path == '') {
api.path = root;
api.fullName = root + '/' + api.fullName;
}
else {
api.path = root + '/' + api.path;
api.fullName = root + '/' + api.fullName;
}
}
return true;
}
//upload a single api elem
function uploadAPI(api,user,done) {
db.get('api',{fullName : api.fullName},
function(err,results) {
if(results.length > 0 &&
results[0].user_id &&
!results[0].user_id.equals(user._id)) { //can't create same name
done("Permission Denied");
}
else {
if(results.length == 0 && api.path != '') {
db.get('api', {fullName : api.path},
function(err,results) {
if(results.length == 0) {
done("No parent exists");
}
else if(results[0].user_id && !results[0].user_id.equals(user._id)) {
done("Permission Denied");
}
else {
if(!api.user_id)
api.user_id = user._id;
db.update('api',
{fullName : api.fullName},
api,
function(err) {
if(err) {
console.log(err);
done(err);
}
else {
updateParents(api,done);
}
});
}
});
}
if(typeof api.user_id == 'undefined')
api.user_id = user._id;
db.update('api',
{fullName : api.fullName},
api,
function(err) {
if(err) {
console.log(err);
done(err);
}
else {
updateParents(api,done);
}
});
}
});
}
//upload a list of api elems
function uploadAPIs(apis,user,done) {
function uploadAPIsHelper(toLoad,loaded,index) {
if(apis.length == 0) {
done(false);
}
else if(index == toLoad.length) {
if(loaded == 0) {
done("Could not load one or more elements");
}
else {
uploadAPIsHelper(toLoad,0,0);
}
}
else {
uploadAPI(toLoad[index],user,
function (err) {
if(err) {
console.log(err);
uploadAPIsHelper(toLoad,loaded,index + 1);
}
else {
toLoad.splice(index,1);
uploadAPIsHelper(toLoad,loaded + 1,index);
}
});
}
}
uploadAPIsHelper(apis,0,0);
}
//create a new api
app.post('/upload',
function(req,res) {
fs.readFile(req.files.api.path,
function(err,data) {
var valid = true;
var input;
try {
input = JSON.parse(data);
}
catch(e) {
valid = false;
}
if(!valid) {
res.status(400);
res.render('uploaded',
{title : 'APIDocs - Uploaded',
user : req.user,
error : "Malformed File"});
}
else {
if(input.every(function(api) {return validAPI(api,req.body.root);})) {
uploadAPIs(input,req.user,
function(err) {
res.status(err ? 403 : 201);
res.render('uploaded',
{title : 'APIDocs - Uploaded',
user: req.user,
error : err});
});
}
else {
res.status(400);
res.render('uploaded',
{title : 'APIDocs - Uploaded',
user: req.user,
error : 'Malformed API Elem format'});
}
}
});
});
// After an apis are successfully added to the database, updates their
// parents to recognize their children. Will not re-add a child.
function updateParents(api, done) {
db.update('api', {fullName: api.path}, {$addToSet: {children: api.name}},done);
}
//delete an existing api
app.del('/api/*',
function(req,res) {
var apiFullName = req.url.substring(5,req.url.length);
db.del({fullName : apiFullName});
});
//search for apis with matching name
app.get('/search',
function(req,res) {
console.log(req.query.search);
db.get('api', {name : {$regex : ".*" + req.query.search + ".*", $options : 'i'}},
function(err,results) {
console.log(results);
res.render('search',
{title : 'APIDocs - Search Results',
user : req.user,
results : results});
});
});
//404 for everything else
app.all('*',
function(req, res, next){
res.status(404);
res.render('msg',
{title : 'APIDocs - 404', user : req.user, status : '404', message : 'Page not found.'});
});
//start the web server
app.listen(port,ip,
function () {
console.log('Listening on port ' + port);
});
}
exports.start = start