-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
605 lines (545 loc) · 21 KB
/
server.js
File metadata and controls
605 lines (545 loc) · 21 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
598
599
600
601
602
603
604
605
const express = require('express');
const hbs = require('hbs');
const fs = require('fs');
const _ = require('lodash');
const cors = require('cors');
var bodyParser = require('body-parser');
const port = process.env.PORT || 3100;
var app = express();
app.set('view engine', 'hbs');
app.use(cors());
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
app.use((req, res, next) => {
var now = new Date().toString();
var log = `${now}: ${req.method} : ${req.url}`;
console.log(log);
fs.appendFile('server.log', log + '\n', (err) => {
if (err)
console.log(' ERROR MESSAGE::111 ', err);
});
next();
});
// app.use((req, res, next) => {
// res.render('mantainance.hbs', {
// message: 'be right back;;',
// page: 'mantainance',
// });
// });
hbs.registerPartials(__dirname + '/views/partials');
hbs.registerHelper('getCurrentYear', () => {
return new Date().getFullYear();
});
hbs.registerHelper('screamIt', (text) => {
return text.toUpperCase();
})
///////////////////////////////////////////////User//////
let UserFakeDB = [
{ username: 'frank', password: 'hello', token: 'frank123' },
{ username: 'truc', password: 'hello', token: '' },
{ username: 'quyen', password: 'hello', token: '' }
];
let authenticate = (req, res, next) => {
console.log('----------------------------------==', req.header('x-authFrank'));
let token = req.header('x-authFrank');
let user = UserFakeDB.filter(x => x.token === token);
if (!user) return res.status(401).send(' authenticate required!!!');
req.user = user;
req.token = token;
next();
};
generateMyAuthToken = function (username) {
var access = 'authFrank';
var token = username + '123';
let index = UserFakeDB.findIndex(u => u.username === username);
UserFakeDB[index].token = token;
return token;
}
removeToken = function (username, token) {
return _.remove(UserFakeDB.filter(u => u == username).map(x => x.tokens), token);
}
////////////////////////////////////////////////////////////////////////////////////////
app.get('/', (req, res) => {
res.render('home.hbs', {
page: 'home page',
message: 'welcome to home page',
currentYear: new Date().getFullYear()
});
});
app.get('/about', (req, res) => {
res.render('about.hbs', {
page: 'About page',
message: ' message about page',
currentYear: new Date().getFullYear()
});
});
app.get('/projects', (req, res) => {
res.render('projects.hbs', {
page: 'projects page',
message: ' message about projects',
currentYear: new Date().getFullYear()
});
});
app.get('/bad', (req, res) => {
res.send({ errorMessage: 'this is a message' });
});
////////////// ng2-fundamental ///////////////////////////////
app.get('/api/events', (req, res) => {
res.send(EVENTS);
});
app.get('/api/events/:id', (req, res) => {
var id = +req.params.id;
var result;
result = EVENTS.find(event => event.id === id);
// if (!result) return res.status(404).send('Id not found');
res.send(result);
});
app.post('/api/events', (req, res) => {
var event = req.body;
if (event.id) {
let index = EVENTS.findIndex(x => x.id == event.id);
EVENTS[index] = event;
res.status(200).send(event);
} else {
event.id = EVENTS.length + 1;
event.sessions = [];
if (event.name) {
EVENTS.push(event);
res.status(200).send(event);
}
}
res.status(400).send('invalid event');
// console.log(' POST /events: ', req.body);
//res.send(JSON.stringify(EVENTS));
});
app.get('/api/sessions/search', (req, res) => {
let search = req.query.search.toLocaleLowerCase();
let results = [];
let matchingSessions = [];
EVENTS.forEach(event => {
matchingSessions = event.sessions.filter(session => session.name.toLocaleLowerCase().indexOf(search) > -1)
matchingSessions = matchingSessions.map((session) => {
session.eventId = event.id;
return session;
})
results = results.concat(matchingSessions)
});
res.send(results);
})
app.post('/api/events/:eventId/sessions/:sessionId/voters/:voter', (req, res) => {
let eventId = req.params.eventId;
let sessionId = req.params.sessionId;
let voter = req.params.voter;
let eventIndex = EVENTS.findIndex(x => x.id == eventId);
let sessionIndex = EVENTS[eventIndex].sessions.findIndex(x => x.id == sessionId);
let voters = EVENTS[eventIndex].sessions[sessionIndex].voters
let voterExist = voters.findIndex(x => x == voter);
console.log('voter exists', voterExist)
if (voterExist == -1) {
voters.push(voter);
}
res.sendStatus(200);
});
app.delete('/api/events/:eventId/sessions/:sessionId/voters/:voter', (req, res) => {
let eventId = req.params.eventId;
let sessionId = req.params.sessionId;
let voter = req.params.voter;
let eventIndex = EVENTS.findIndex(x => x.id == eventId);
let sessionIndex = EVENTS[eventIndex].sessions.findIndex(x => x.id == sessionId);
let voters = EVENTS[eventIndex].sessions[sessionIndex].voters.filter(v => v != voter);
EVENTS[eventIndex].sessions[sessionIndex].voters = voters;
res.sendStatus(200);
});
app.get('/api/currentIdentity', authenticate, (req, res) => {
console.log('api/currentIden ', req.user);
res.send(req.user);
});
app.post('/api/login', (req, res) => {
console.log('api/login', req.body);
let username = req.body.username;
let password = req.body.password;
let user = UserFakeDB.filter(x => x.username === username && x.password === password);
if (user) {
const token = generateMyAuthToken(username);
res.header('x-authFrank', token).send(user);
}
res.status(401).send('wrong..');
});
app.put('/api/users/:username', (req, res) => {
let username = req.params.username;
let index = UserFakeDB.findIndex(x => x.username === username);
UserFakeDB[index].firstName = req.body.firstName;
UserFakeDB[index].lastName = req.body.lastName;
});
app.post('/api/logout', (req, res) => {
let username = req.body.username;
let index = UserFakeDB.findIndex(x => x.username === username);
UserFakeDB[index].token = '';
console.log('logout:', username);
res.header('x-authFrank', '').send(username + ' logged out');
});
///////////////////////////////////////////
app.listen(port, () => {
console.log(`server is up on port: ${port}`);
});
const EVENTS = [
{
id: 1,
name: 'Angular Connect',
date: new Date('9/26/2036'),
time: '10:00 am',
price: 599.99,
imageUrl: '/assets/images/angularconnect-shield.png',
location: {
address: '1057 DT',
city: 'London',
country: 'England'
},
sessions: [
{
id: 1,
name: "Using Angular 4 Pipes",
presenter: "Peter Bacon Darwin",
duration: 1,
level: "Intermediate",
abstract: `Learn all about the new pipes in Angular 4, both
how to write them, and how to get the new AI CLI to write
them for you. Given by the famous PBD, president of Angular
University (formerly Oxford University)`,
voters: ['bradgreen', 'igorminar', 'martinfowler']
},
{
id: 2,
name: "Getting the most out of your dev team",
presenter: "Jeff Cross",
duration: 1,
level: "Intermediate",
abstract: `We all know that our dev teams work hard, but with
the right management they can be even more productive, without
overworking them. In this session I'll show you how to get the
best results from the talent you already have on staff.`,
voters: ['johnpapa', 'bradgreen', 'igorminar', 'martinfowler']
},
{
id: 3,
name: "Angular 4 Performance Metrics",
presenter: "Rob Wormald",
duration: 2,
level: "Advanced",
abstract: `Angular 4 Performance is hot. In this session, we'll see
how Angular gets such great performance by preloading data on
your users devices before they even hit your site using the
new predictive algorithms and thought reading software
built into Angular 4.`,
voters: []
},
{
id: 4,
name: "Angular 5 Look Ahead",
presenter: "Brad Green",
duration: 2,
level: "Advanced",
abstract: `Even though Angular 5 is still 6 years away, we all want
to know all about it so that we can spend endless hours in meetings
debating if we should use Angular 4 or not. This talk will look at
Angular 6 even though no code has yet been written for it. We'll
look at what it might do, and how to convince your manager to
hold off on any new apps until it's released`,
voters: []
},
{
id: 5,
name: "Basics of Angular 4",
presenter: "John Papa",
duration: 2,
level: "Beginner",
abstract: `It's time to learn the basics of Angular 4. This talk
will give you everything you need to know about Angular 4 to
get started with it today and be building UI's for your self
driving cars and butler-bots in no time.`,
voters: ['bradgreen', 'igorminar']
}
]
},
{
id: 2,
name: 'ng-nl',
date: new Date('4/15/2037'),
time: '9:00 am',
price: 950.00,
imageUrl: '/assets/images/ng-nl.png',
onlineUrl: 'http://ng-nl.org/',
sessions: [
{
id: 1,
name: "Testing Angular 4 Workshop",
presenter: "Pascal Precht & Christoph Bergdorf",
duration: 4,
level: "Beginner",
abstract: `In this 6 hour workshop you will learn not only how to test Angular 4,
you will also learn how to make the most of your team's efforts. Other topics
will be convincing your manager that testing is a good idea, and using the new
protractor tool for end to end testing.`,
voters: ['bradgreen', 'igorminar']
},
{
id: 2,
name: "Angular 4 and Firebase",
presenter: "David East",
duration: 3,
level: "Intermediate",
abstract: `In this workshop, David East will show you how to use Angular with the new
ultra-real-time 5D Firebase back end, hosting platform, and wine recommendation engine.`,
voters: ['bradgreen', 'igorminar', 'johnpapa']
},
{
id: 3,
name: "Reading the Angular 4 Source",
presenter: "Patrick Stapleton",
duration: 2,
level: "Intermediate",
abstract: `Angular 4's source code may be over 25 million lines of code, but it's really
a lot easier to read and understand then you may think. Patrick Stapleton will talk
about his secretes for keeping up with the changes, and navigating around the code.`,
voters: ['martinfowler']
},
{
id: 4,
name: "Hail to the Lukas",
presenter: "Lukas Ruebbelke",
duration: 1,
level: "Beginner",
abstract: `In this session, Lukas will present the
secret to being awesome, and how he became the President
of the United States through his amazing programming skills,
showing how you too can be success with just attitude.`,
voters: ['bradgreen']
},
]
},
{
id: 3,
name: 'ng-conf 2037',
date: new Date('5/4/2037'),
time: '9:00 am',
price: 759.00,
imageUrl: '/assets/images/ng-conf.png',
location: {
address: 'The Palatial America Hotel',
city: 'Salt Lake City',
country: 'USA'
},
sessions: [
{
id: 1,
name: "How Elm Powers Angular 4",
presenter: "Murphy Randle",
duration: 2,
level: "Intermediate",
abstract: `We all know that Angular is written in Elm, but did you
know how the source code is really written? In this exciting look
into the internals of Angular 4, we'll see exactly how Elm powers
the framework, and what you can do to take advantage of this knowledge.`,
voters: ['bradgreen', 'martinfowler', 'igorminar']
},
{
id: 2,
name: "Angular and React together",
presenter: "Jamison Dance",
duration: 2,
level: "Intermediate",
abstract: `React v449.6 has just been released. Let's see how to use
this new version with Angular to create even more impressive applications.`,
voters: ['bradgreen', 'martinfowler']
},
{
id: 3,
name: "Redux Woes",
presenter: "Rob Wormald",
duration: 1,
level: "Intermediate",
abstract: `Everyone is using Redux for everything from Angular to React to
Excel macros, but you're still having trouble grasping it? We'll take a look
at how farmers use Redux when harvesting grain as a great introduction to
this game changing technology.`,
voters: ['bradgreen', 'martinfowler', 'johnpapa']
},
{
id: 4,
name: "ng-wat again!!",
presenter: "Shai Reznik",
duration: 1,
level: "Beginner",
abstract: `Let's take a look at some of the stranger pieces of Angular 4,
including neural net nets, Android in Androids, and using pipes with actual pipes.`,
voters: ['bradgreen', 'martinfowler', 'igorminar', 'johnpapa']
},
{
id: 5,
name: "Dressed for Success",
presenter: "Ward Bell",
duration: 2,
level: "Beginner",
abstract: `Being a developer in 2037 is about more than just writing bug-free code.
You also have to look the part. In this amazing expose, Ward will talk you through
how to pick out the right clothes to make your coworkers and boss not only
respect you, but also want to be your buddy.`,
voters: ['bradgreen', 'martinfowler']
},
{
id: 6,
name: "These aren't the directives you're looking for",
presenter: "John Papa",
duration: 2,
level: "Intermediate",
abstract: `Coinciding with the release of Star Wars Episode 18, this talk will show how
to use directives in your Angular 4 development while drawing lessons from the new movie,
featuring all your favorite characters like Han Solo's ghost and Darth Jar Jar.`,
voters: ['bradgreen', 'martinfowler']
},
]
},
{
id: 4,
name: 'UN Angular Summit',
date: new Date('6/10/2037'),
time: '8:00 am',
price: 800.00,
imageUrl: '/assets/images/basic-shield.png',
location: {
address: 'The UN Angular Center',
city: 'New York',
country: 'USA'
},
sessions: [
{
id: 1,
name: "Diversity in Tech",
presenter: "Sir Dave Smith",
duration: 2,
level: "Beginner",
abstract: `Yes, we all work with cyborgs and androids and Martians, but
we probably don't realize that sometimes our internal biases can make it difficult for
these well-designed coworkers to really feel at home coding alongside us. This talk will
look at things we can do to recognize our biases and counteract them.`,
voters: ['bradgreen', 'igorminar']
},
{
id: 2,
name: "World Peace and Angular",
presenter: "US Secretary of State Zach Galifianakis",
duration: 2,
level: "Beginner",
abstract: `Angular has been used in most of the major peace brokering that has
happened in the last decade, but there is still much we can do to remove all
war from the world, and Angular will be a key part of that effort.`,
voters: ['bradgreen', 'igorminar', 'johnpapa']
},
{
id: 3,
name: "Using Angular with Androids",
presenter: "Dan Wahlin",
duration: 3,
level: "Advanced",
abstract: `Androids may do everything for us now, allowing us to spend all day playing
the latest Destiny DLC, but we can still improve the massages they give and the handmade
brie they make using Angular 4. This session will show you how.`,
voters: ['igorminar', 'johnpapa']
},
]
},
{
id: 5,
name: 'ng-vegas',
date: new Date('2/10/2037'),
time: '9:00 am',
price: 400.00,
imageUrl: '/assets/images/ng-vegas.png',
location: {
address: 'The Excalibur',
city: 'Las Vegas',
country: 'USA'
},
sessions: [
{
id: 1,
name: "Gambling with Angular",
presenter: "John Papa",
duration: 1,
level: "Intermediate",
abstract: `No, this talk isn't about slot machines. We all know that
Angular is used in most waiter-bots and coke vending machines, but
did you know that was also used to write the core engine in the majority
of voting machines? This talk will look at how all presidential elections
are now determined by Angular code.`,
voters: ['bradgreen', 'igorminar']
},
{
id: 2,
name: "Angular 4 in 60ish Minutes",
presenter: "Dan Wahlin",
duration: 2,
level: "Beginner",
abstract: `Get the skinny on Angular 4 for anyone new to this great new technology.
Dan Wahlin will show you how you can get started with Angular in 60ish minutes,
guaranteed!`,
voters: ['bradgreen', 'igorminar', 'johnpapa']
}
]
}
]
/////////////////////////////////
/**
* Traverses a javascript object, and deletes all circular values
* @param source object to remove circular references from
* @param censoredMessage optional: what to put instead of censored values
* @param censorTheseItems should be kept null, used in recursion
* @returns {undefined}
*/
function preventCircularJson(source, censoredMessage, censorTheseItems) {
//init recursive value if this is the first call
censorTheseItems = censorTheseItems || [source];
//default if none is specified
censoredMessage = censoredMessage || "CIRCULAR_REFERENCE_REMOVED";
//values that have allready apeared will be placed here:
var recursiveItems = {};
//initaite a censored clone to return back
var ret = {};
//traverse the object:
for (var key in source) {
var value = source[key]
if (typeof value == "object") {
//re-examine all complex children again later:
recursiveItems[key] = value;
} else {
//simple values copied as is
ret[key] = value;
}
}
//create list of values to censor:
var censorChildItems = [];
for (var key in recursiveItems) {
var value = source[key];
//all complex child objects should not apear again in children:
censorChildItems.push(value);
}
//censor all circular values
for (var key in recursiveItems) {
var value = source[key];
var censored = false;
censorTheseItems.forEach(function (item) {
if (item === value) {
censored = true;
}
});
if (censored) {
//change circular values to this
value = censoredMessage;
} else {
//recursion:
value = preventCircularJson(value, censoredMessage, censorChildItems.concat(censorTheseItems));
}
ret[key] = value
}
return ret;
}