-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
600 lines (479 loc) · 20.7 KB
/
index.js
File metadata and controls
600 lines (479 loc) · 20.7 KB
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
var express = require('express');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var multer = require('multer');
var app = express();
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
//configure ==========
require('./config/passport')(passport); // pass passport for configuration
app.use('/uploads', express.static(__dirname +'/uploads'));
app.set('views', './views');
app.set('view engine', 'ejs');
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json('application/json'));
app.use(bodyParser.urlencoded( {extended: true }));
//make sure to add the validator after the body parser!!
app.use(expressValidator());
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:8100');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
app.use(allowCrossDomain);
var postgres = require('./lib/postgres');
var photos = require('./lib/models/photo');
var votes = require('./lib/models/votes');
var challenges = require('./lib/models/challenge');
// required for passport
app.use(session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// Create the express router object for Photos
var photoRouter = express.Router();
console.log ("photoRouter is set");
// A GET to the root of a resource returns a list of that resource
photoRouter.get('/', function(req, res){
res.header("Access-Control-Allow-Origin", "http://localhost:8100");//set cross domain so localhost:8100 can access clouie.ca
res.header("Access-Control-Allow-Headers", "X-Requested-With");//make it so allow headers with x request. Without it we get similar error: "XMLHttpRequest cannot load http://...
var page = parseInt(req.query.page, 10);
if (isNaN(page) || page < 1){
page = 1;
}
var limit = parseInt(req.query.limit, 10);
if (isNaN(limit)){
limit = 20;
} else if (limit > 50){
limit = 50;
} else if (limit < 1) {
limit = 1;
}
var sql = 'SELECT count(1) FROM photo';
postgres.client.query(sql, function(err, result) {
if (err) {
console.error(err);
res.statusCode = 500;
return res.json({
errors: ['Could not retrieve photos']
});
}
var count = parseInt(result.rows[0].count, 10);
var offset = (page - 1) * limit; //page - 1 * the limit so when we are on
// page two the offset is 11.
sql = 'SELECT photo.*, COUNT(votes.*) AS votecount FROM photo LEFT JOIN votes ON photo.id = votes.p_id GROUP BY photo.id OFFSET $1 LIMIT $2';
postgres.client.query(sql, [offset, limit], function (err, result) {
if (err) {
console.error(err);
console.log(err);
res.statusCode = 500;
return res.json({
errors: ['Could not retrieve photos']
});
}
return res.json(result.rows);
});
});
});
// A POST to the root of a resource should create a new object
photoRouter.post('/', multer({
dest: './uploads/',
rename: function(field, filename){
filename = filename.replace(/\W+/g, '-').toLowerCase();
return filename + '_' + Date.now();
},
limits: {
files: 1,
fileSize: 2 * 1024 * 1024
}
}), photos.validatePhoto, function(req, res) {
console.log("Post to /photo is happening");
var sql = 'INSERT INTO photo (description, filepath, album_id, u_id, c_id) VALUES ($1, $2, $3, $4, $5) RETURNING id';
var data = [
req.body.description,
req.files.photo.path,
req.body.album_id,
req.user.id,
req.body.c_id
];
//multer appends the field name (photo)
console.log(data);
postgres.client.query(sql, data, function(err, result){
if (err) {
console.error(err);
res.statusCode = 500;
return res.json({
errors: ['Failed to create photo']
});
}
//consoles the id number we are at
console.log('Insert result:', result.rows);
// what does the client want if they have succeeded
var photoId = result.rows[0].id;
var sql = 'SELECT * FROM photo WHERE id = $1';
postgres.client.query(sql, [ photoId ], function(err, result){
if (err){
console.error(err);
res.statusCode=500;
return res.json({ errors: ['Could not retrieve photo after it was created'] });
}
res.statusCode= 201;
console.log('Select result', result); // check to make sure i'm sending back an object
res.json(result.rows[0]);
});
});
});
// We specify a param in our path for the GET of a specific object
photoRouter.get('/:id([0-9]+)', photos.challengePhotos, function(req, res) {
res.header("Access-Control-Allow-Origin", "http://localhost:8100");//set cross domain so localhost:8100 can access clouie.ca
res.header("Access-Control-Allow-Headers", "X-Requested-With");//make it so allow headers with x request. Without it we get similar error: "XMLHttpRequest cannot load http://...
res.json(req.photo);
});
// Similar to the GET on an object, to update it we can PATCH
photoRouter.patch('/:id', function(req, res) { });
// Delete a specific object
//photoRouter.delete('/:id', lookupPhoto, function(req, res) { });
// Attach the routers for their respective paths
app.use('/photo', photoRouter);
var uploadRouter = express.Router();
uploadRouter.get('/', function(req, res) {
res.header("Access-Control-Allow-Origin", "http://localhost:8100");//set cross domain so localhost:8100 can access clouie.ca
res.header("Access-Control-Allow-Headers", "X-Requested-With");//make it so allow headers with x request. Without it we get similar error: "XMLHttpRequest cannot load http://...
res.render('form');
});
app.use('/upload', uploadRouter);
////////////////////////////////Creating the Challenge Table////////////////////////////////////////
var challengeRouter = express.Router();
console.log ("challengeRouter is set");
// A GET to the root of a resource returns a list of that resource
challengeRouter.get('/', function(req, res){
res.header("Access-Control-Allow-Origin", "http://localhost:8100");//set cross domain so localhost:8100 can access clouie.ca
res.header("Access-Control-Allow-Headers", "X-Requested-With");//make it so allow headers with x request. Without it we get similar error: "XMLHttpRequest cannot load http://...
var page = parseInt(req.query.page, 10);
if (isNaN(page) || page < 1){
page = 1;
}
var limit = parseInt(req.query.limit, 10);
if (isNaN(limit)){
limit = 20;
} else if (limit > 50){
limit = 50;
} else if (limit < 1) {
limit = 1;
}
var sql = 'SELECT count(1) FROM challenge';
postgres.client.query(sql, function(err, result) {
if (err) {
console.error(err);
res.statusCode = 500;
return res.json({
errors: ['Could not retrieve challenges!']
});
}
var count = parseInt(result.rows[0].count, 10);
var offset = (page - 1) * limit; //page - 1 * the limit so when we are on
// page two the offset is 11.
sql = 'SELECT challenge.*, users.name as username FROM challenge, users WHERE challenge.u_id = users.u_id AND date_end > now() OFFSET $1 LIMIT $2';
postgres.client.query(sql, [offset, limit], function (err, result) {
if (err) {
console.error(err);
res.statusCode = 500;
return res.json({
errors: ['Could not retrieve photos']
});
}
return res.json(result.rows);
});
});
});
// A POST to the root of a resource should create a new object
challengeRouter.post('/', multer({
dest: './uploads/',
rename: function(field, filename){
console.log(filename);
filename = filename.replace(/\W+/g, '-').toLowerCase();
return filename + '_' + Date.now();
},
limits: {
files: 1,
fileSize: 2 * 1024 * 1024
}
}), photos.validatePhoto, function(req, res) {
res.header("Access-Control-Allow-Origin", "http://localhost:8100");//set cross domain so localhost:8100 can access clouie.ca
res.header("Access-Control-Allow-Headers", "X-Requested-With");//make it
console.log("Post to /challenge is happening");
var sql = 'INSERT INTO challenge (name, filepath, description, created_on, u_id, date_end) VALUES ($1, $2, $3, now(), $4, now()+interval \'7 days\') RETURNING c_id';
var data = [
req.body.name,
req.files.photo.path,
req.body.description,
req.user.id
];
//multer appends the field name (photo)
console.log(data);
postgres.client.query(sql, data, function(err, result){
if (err) {
console.error(err);
res.statusCode = 500;
return res.json({
errors: ['Failed to create challenge']
});
}
//consoles the id number we are at
console.log('Insert result:', result.rows);
// what does the client want if they have succeeded
var challengeId = result.rows[0].c_id;
var sql = 'SELECT * FROM challenge WHERE c_id = $1';
console.log(challengeId);
postgres.client.query(sql, [ challengeId ], function(err, result){
if (err){
console.error(err);
res.statusCode=500;
return res.json({ errors: ['Could not retrieve photo after it was created'] });
}
res.statusCode= 201;
console.log('Select result', result); // check to make sure i'm sending back an object
res.json(result.rows[0]);
});
});
});
// We specify a param in our path for the GET of a specific object
challengeRouter.get('/:id([0-9]+)', challenges.lookupChallenge, function(req, res) {
res.header("Access-Control-Allow-Origin", "http://localhost:8100");//set cross domain so localhost:8100 can access clouie.ca
res.header("Access-Control-Allow-Headers", "X-Requested-With");//make it so allow headers with x request. Without it we get similar error: "XMLHttpRequest cannot load http://...
res.json(req.challenge);
});
// Similar to the GET on an object, to update it we can PATCH
challengeRouter.patch('/:id', function(req, res) {
res.header("Access-Control-Allow-Origin", "http://localhost:8100");//set cross domain so localhost:8100 can access clouie.ca
res.header("Access-Control-Allow-Headers", "X-Requested-With");//make it so allow headers with x request. Without it we get similar error: "XMLHttpRequest cannot load http://...
});
// Delete a specific object
//photoRouter.delete('/:id', lookupPhoto, function(req, res) { });
// Attach the routers for their respective paths
app.use('/challenge', challengeRouter);
/////////////////////////////////////input form for challenge table /////////////////////
var inputRouter = express.Router();
inputRouter.get('/', function(req, res) {
res.header("Access-Control-Allow-Origin", "http://localhost:8100");//set cross domain so localhost:8100 can access clouie.ca
res.header("Access-Control-Allow-Headers", "X-Requested-With");//make it so allow headers with x request. Without it we get similar error: "XMLHttpRequest cannot load http://...
res.render('input');
});
app.use('/input', inputRouter);
//////////////////////////////accepted_challenge Table//////////////////
var acceptRouter = express.Router();
console.log ("acceptRouter is set");
// A GET to the root of a resource returns a list of that resource
acceptRouter.get('/', function(req, res) {
res.header("Access-Control-Allow-Origin", "http://localhost:8100");//set cross domain so localhost:8100 can access clouie.ca
res.header("Access-Control-Allow-Headers", "X-Requested-With");//make it so allow headers with x request. Without it we get similar error: "XMLHttpRequest cannot load http://...
var page = parseInt(req.query.page, 10);
if (isNaN(page) || page < 1) {
page = 1;
}
var limit = parseInt(req.query.limit, 10);
if (isNaN(limit)) {
limit = 20;
} else if (limit > 50) {
limit = 50;
} else if (limit < 1) {
limit = 1;
}
var sql = 'SELECT count(1) FROM accepted_challenge';
postgres.client.query(sql, function (err, result) {
if (err) {
console.error(err);
res.statusCode = 500;
return res.json({
errors: ['Could not retrieve accepted challenges!']
});
}
var count = parseInt(result.rows[0].count, 10);
var offset = (page - 1) * limit; //page - 1 * the limit so when we are on
// page two the offset is 11.
var sql = 'SELECT accepted_challenge.*, challenge.description as challenge FROM accepted_challenge, challenge WHERE accepted_challenge.c_id = challenge.c_id AND accepted_challenge.u_id = $3 OFFSET $1 LIMIT $2';
postgres.client.query(sql, [offset, limit, req.user.id], function (err, result) {
if (err) {
console.error(err);
res.statusCode = 500;
return res.json({
errors: ['Could not retrieve accepted challenges']
});
}
return res.json(result.rows);
});
});
});
// A POST to the root of a resource should create a new object
acceptRouter.post('/', function(req, res) {
res.header("Access-Control-Allow-Origin", "http://localhost:8100");//set cross domain so localhost:8100 can access clouie.ca
res.header("Access-Control-Allow-Headers", "X-Requested-With");//make it so allow headers with x request. Without it we get similar error: "XMLHttpRequest cannot load http://...
console.log("the request is in post accepted", req.user);
//console.log("the request is in post accepted 2", req.user.id);
console.log("Post to /accepted is happening");
var sql = 'INSERT INTO accepted_challenge (u_id, c_id) VALUES ($1, $2) RETURNING id';
var data = [
req.user.id,
req.body.c_id
];
console.log(data);
postgres.client.query(sql, data, function (err, result) {
if (err) {
console.error(err);
res.statusCode = 500;
return res.json({
errors: ['Failed to create challenge']
});
}
//consoles the id number we are at
console.log('Insert result:', result.rows);
});
});
//delete a challenge from the table... i dont want to delete i want to deactivate.
app.use('/accepted', acceptRouter);
//////////////////////////////votes Table//////////////////
var voteRouter = express.Router();
console.log ("voteRouter is set");
// A GET to the root of a resource returns a list of that resource
voteRouter.get('/', function(req, res) {
res.header("Access-Control-Allow-Origin", "http://localhost:8100");//set cross domain so localhost:8100 can access clouie.ca
res.header("Access-Control-Allow-Headers", "X-Requested-With");//make it so allow headers with x request. Without it we get similar error: "XMLHttpRequest cannot load http://...
var page = parseInt(req.query.page, 10);
if (isNaN(page) || page < 1) {
page = 1;
}
var limit = parseInt(req.query.limit, 10);
if (isNaN(limit)) {
limit = 20;
} else if (limit > 50) {
limit = 50;
} else if (limit < 1) {
limit = 1;
}
var sql = 'SELECT count(1) FROM votes';
postgres.client.query(sql, function (err, result) {
if (err) {
console.error(err);
res.statusCode = 500;
return res.json({
errors: ['Could not retrieve votes challenges!']
});
}
var count = parseInt(result.rows[0].count, 10);
var offset = (page - 1) * limit; //page - 1 * the limit so when we are on
// page two the offset is 11.
//var sql = 'SELECT accepted_challenge.*, challenge.name as challenge FROM accepted_challenge, challenge WHERE accepted_challenge.c_id = challenge.c_id AND accepted_challenge.u_id = $3 OFFSET $1 LIMIT $2';
var sql = 'SELECT votes.*, photo.c_id as c_id FROM votes, photo WHERE votes.p_id = photo.id AND votes.u_id = $3 OFFSET $1 LIMIT $2';
postgres.client.query(sql, [offset, limit, req.user.id], function (err, result) {
if (err) {
console.error(err);
res.statusCode = 500;
return res.json({
errors: ['Could not retrieve votes']
});
}
return res.json(result.rows);
});
});
});
// A POST to the root of a resource should create a new object
voteRouter.post('/', function(req, res) {
res.header("Access-Control-Allow-Origin", "http://localhost:8100");//set cross domain so localhost:8100 can access clouie.ca
res.header("Access-Control-Allow-Headers", "X-Requested-With");//make it so allow headers with x request. Without it we get similar error: "XMLHttpRequest cannot load http://...
console.log("the request is in post accepted", req.user);
//console.log("the request is in post accepted 2", req.user.id);
console.log("Post to /votes is happening");
var sql = 'INSERT INTO votes (u_id, p_id, vote) VALUES ($1, $2, $3) RETURNING v_id';
var data = [
req.user.id,
req.body.p_id,
true
];
console.log(data);
postgres.client.query(sql, data, function (err, result) {
if (err) {
console.error(err);
res.statusCode = 500;
return res.json({
errors: ['Failed to create vote']
});
}
//consoles the id number we are at
console.log('Insert result:', result.rows);
});
});
voteRouter.get('/:id([0-9]+)', votes.lookupPhoto, function(req, res) {
console.log('getting vote/id');
res.header("Access-Control-Allow-Origin", "http://localhost:8100");//set cross domain so localhost:8100 can access clouie.ca
res.header("Access-Control-Allow-Headers", "X-Requested-With");//make it so allow headers with x request. Without it we get similar error: "XMLHttpRequest cannot load http://...
res.json(req.vote);
});
app.use('/vote', voteRouter);
///////////////////////////////////user data/////////////////////////////
var userRouter = express.Router();
console.log ("userRouter is set");
// A GET to the root of a resource returns a list of that resource
userRouter.get('/', function(req, res){
res.header("Access-Control-Allow-Origin", "http://localhost:8100");//set cross domain so localhost:8100 can access clouie.ca
res.header("Access-Control-Allow-Headers", "X-Requested-With");//make it so allow headers with x request. Without it we get similar error: "XMLHttpRequest cannot load http://...
var page = parseInt(req.query.page, 10);
if (isNaN(page) || page < 1){
page = 1;
}
var limit = parseInt(req.query.limit, 10);
if (isNaN(limit)){
limit = 10;
} else if (limit > 50){
limit = 50;
} else if (limit < 1) {
limit = 1;
}
var sql = 'SELECT count(1) FROM users';
postgres.client.query(sql, function(err, result) {
if (err) {
console.error(err);
res.statusCode = 500;
return res.json({
errors: ['Could not retrieve photos']
});
}
var count = parseInt(result.rows[0].count, 10);
var offset = (page - 1) * limit; //page - 1 * the limit so when we are on
// page two the offset is 11.
sql = 'SELECT * FROM users OFFSET $1 LIMIT $2';
postgres.client.query(sql, [offset, limit], function (err, result) {
if (err) {
console.error(err);
res.statusCode = 500;
return res.json({
errors: ['Could not retrieve users']
});
}
return res.json(result.rows);
});
});
});
app.use('/users', userRouter);
//var albumRouter = express.Router();
//albumRouter.get('/', function(req, res) { });
//albumRouter.post('/', function(req, res) { });
//albumRouter.get('/:id', function(req, res) { });
//albumRouter.patch('/:id', function(req, res) { });
//albumRouter.delete('/:id', function(req, res) { });
//app.use('/album', albumRouter);
// routes ======================================================================
require('./lib/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
module.exports = app;