-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.php
729 lines (529 loc) · 18.9 KB
/
index.php
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
<?php
require 'vendor/autoload.php';
require 'code/getLoginEmail.php';
require 'code/helper.php';
use Aws\Common\Aws;
use Aws\Ses\SesClient;
use Aws\DynamoDb\DynamoDbClient;
// Set timezone
date_default_timezone_set("UTC");
// Let's the system know this is in the dev environment
$dev = true;
// Prepare Slim PHP app
$app = new \Slim\Slim(array(
'templates.path' => 'templates',
'debug' => $dev
));
function logError($e, $errorType) {
// Get AWS DynamoDB Client
$dbClient = DynamoDBClient::factory(array(
'region' => 'us-west-2'
));
// Make insert into errors table in database
$errorDate = new DateTime();
$dbClient->putItem(array(
'TableName' => 'errors',
'Item' => array(
'errorId' => array('S' => uniqid()), // Primary Key
'errorDate' => array('N' => $errorDate->getTimestamp()), // Range Key
'errorType' => array('S' => $errorType),
'message' => array('S' => $e->getMessage()),
'code' => array('N' => $e->getCode()),
'fileName' => array('S' => $e->getFile()),
'line' => array('N' => $e->getLine())
)
));
echo json_encode(array('message' => 'error'));
}
function myPHPExceptionHandler($e) {
logError($e, 'PHPError');
}
set_exception_handler('myPHPExceptionHandler');
$app->error(function (\Exception $e) use ($app) {
logError($e, 'SlimError');
});
if ($dev === false) {
$secureProtocol = false;
$httpHost = filter_input(INPUT_SERVER, "HTTP_HOST");
$requestURI = filter_input(INPUT_SERVER, "REQUEST_URI");
$https = filter_input(INPUT_SERVER, "HTTPS");
$serverPort = filter_input(INPUT_SERVER, "SERVER_PORT");
$proto = filter_input(INPUT_SERVER, "HTTP_X_FORWARDED_PROTO");
if (substr($httpHost, 0, 4) === 'www.') {
header('Location: https://' . substr($httpHost, 4) . $requestURI);
exit();
}
if (!empty($https) && $https !== 'off' || $serverPort == 443) {
$secureProtocol = true;
} else if (!empty($proto) && $proto === "https") {
$secureProtocol = true;
}
$hasPHPAtEnd = strrpos($requestURI, ".php");
if ($hasPHPAtEnd !== false) {
$requestURI = str_replace($requestURI, ".php", "");
header('Location: https://' . $httpHost . $requestURI);
exit();
} else if ($secureProtocol === false) {
header('Location: https://' . $httpHost . $requestURI);
exit();
}
}
function isValid ($app) {
// The old token should be sent in request header
$token = $app->request->headers->get('X-Authorization');
$app->response->headers->set('Content-Type', 'application/json');
// If the user had a token in their local storage, refresh it and send the new one back.
if (isset($token) && $token !== 'invalid') {
// Get email, expiration timestamp, and signature from old token
$oldToken = explode(':', $token);
$email = $oldToken[0];
$expirationTimestamp = $oldToken[1];
$givenSignature = $oldToken[2];
// Setup dates to check if token is expired
$currentDate = new DateTime();
$expirationDate = new DateTime();
$expirationDate->setTimestamp(intval($expirationTimestamp));
// Setup expected signature for purposes of comparison.
$rawToken = $email . ':' . $expirationTimestamp;
$expectedSignature = hash_hmac('ripemd160', $rawToken, getenv('notellosecret'));
if ($currentDate >= $expirationDate) {
// The token is expired
$app->response->setStatus(403);
$app->response->setBody(json_encode(array('message' => 'Forbidden')));
} else if (md5($givenSignature) === md5($expectedSignature)) {
// All is well and we can finally refresh the auth token
$newRawToken = $email . ':' . strtotime('+7 days');
$newSignature = hash_hmac('ripemd160', $newRawToken, getenv('notellosecret'));
$newAuthToken = $newRawToken . ':' . $newSignature;
$app->response->headers->set('X-Authorization', $newAuthToken);
return true;
} else {
// The token is invalid and has probably been tampered with
$app->response->setBody(json_encode(array('token' => 'InvalidToken')));
}
} else {
$app->response->setStatus(403);
$app->response->setBody(json_encode(array('message' => 'Forbidden')));
}
}
$app->get('/', function () use ($app) {
// Render index view
$app->render('index.html');
});
$app->get('/error', function () use ($app) {
$app->render('error.html');
});
$app->get('/404', function () use ($app) {
$app->render('404.html');
});
$app->notFound(function () use ($app) {
$app->render('404.html');
});
$app->get('/assuresign', function () use ($app) {
// Render index view
$app->render('assuresign.html');
});
$app->get('/api/usernotes', function () use ($app) {
if (isValid($app)) {
$token = $app->request->headers->get('X-Authorization');
$oldToken = explode(':', $token);
$email = $oldToken[0];
// Get AWS DynamoDB Client
$dbClient = DynamoDBClient::factory(array(
'region' => 'us-west-2'
));
// Query user notes from database
$result = $dbClient->getItem(array(
'ConsistentRead' => true,
'TableName' => 'usernotes',
'Key' => array(
'email' => array('S' => $email)
)
));
$userNotes = $result['Item']['usernotes']['S'];
$app->response->setBody(json_encode(array('userNotes' => $userNotes)));
}
});
function hydrateId ($userNotes) {
if (isset($userNotes)) {
foreach ($userNotes as $userNoteKey => $userNoteValue) {
if (isset($userNoteValue['itemType']) && $userNoteValue['itemType'] === 'notebook' && !isset($userNoteValue['notebookId'])) {
$userNotes[$userNoteKey]['notebookId'] = uniqid();
$userNotes[$userNoteKey]['notes'] = hydrateId($userNoteValue['notes']);
}
if (isset($userNoteValue['itemType']) && $userNoteValue['itemType'] === 'box' && !isset($userNoteValue['boxId'])) {
$userNotes[$userNoteKey]['boxId'] = uniqid();
}
if (isset($userNoteValue['itemType']) && $userNoteValue['itemType'] === 'note' && !isset($userNoteValue['noteId'])) {
$userNotes[$userNoteKey]['noteId'] = uniqid();
}
}
unset($userNoteValue);
} else {
$userNotes = array();
}
return $userNotes;
}
$app->put('/api/usernotes', function () use ($app) {
if (isValid($app)) {
$token = $app->request->headers->get('X-Authorization');
$oldToken = explode(':', $token);
$email = $oldToken[0];
$userNotes = hydrateId($app->request->put('usernotes'));
$append = $app->request->put('append');
// Get AWS DynamoDB Client
$dbClient = DynamoDBClient::factory(array(
'region' => 'us-west-2'
));
if (isset($append) && $append === 'true') {
// Query user notes from database
$result = $dbClient->getItem(array(
'ConsistentRead' => true,
'TableName' => 'usernotes',
'Key' => array(
'email' => array('S' => $email)
)
));
$existingUserNotes = json_decode($result['Item']['usernotes']['S']);
if ($existingUserNotes === null) {
$existingUserNotes = array();
}
$userNotes = array_merge($existingUserNotes, $userNotes);
}
$userNotesEncoded = json_encode($userNotes);
// Make update or insert to user notes in database
$dbClient->putItem(array(
'TableName' => 'usernotes',
'Item' => array(
'email' => array('S' => $email), // Primary Key
'usernotes' => array('S' => $userNotesEncoded)
)
));
$app->response->setBody(json_encode(array('userNotes' => $userNotes)));
}
});
$app->put('/api/selected/:noteId', function ($noteId) use ($app) {
if (isValid($app)) {
$token = $app->request->headers->get('X-Authorization');
$oldToken = explode(':', $token);
$email = $oldToken[0];
// Get AWS DynamoDB Client
$dbClient = DynamoDBClient::factory(array(
'region' => 'us-west-2',
));
// Make update or insert to selected note in database
$dbClient->putItem(array(
'TableName' => 'selected',
'Item' => array(
'email' => array('S' => $email), // Primary Key
'selected' => array('S' => $noteId)
)
));
$app->response->setBody(json_encode(array('message' => 'Successful')));
}
});
$app->get('/api/selected', function () use ($app) {
if (isValid($app)) {
$token = $app->request->headers->get('X-Authorization');
$oldToken = explode(':', $token);
$email = $oldToken[0];
// Get AWS DynamoDB Client
$dbClient = DynamoDBClient::factory(array(
'region' => 'us-west-2'
));
// Query usernotes from database
$result = $dbClient->getItem(array(
'ConsistentRead' => true,
'TableName' => 'selected',
'Key' => array(
'email' => array('S' => $email) // Primary Key
)
));
$noteId = '';
if (isset($result['Item']['selected'])) {
$noteId = Helper::NAToBlank($result['Item']['selected']['S']);
}
$app->response->setBody(json_encode(array(
'noteId' => $noteId
)));
}
});
$app->get('/api/note/:noteId', function ($noteId) use ($app) {
if (isValid($app)) {
// Get AWS DynamoDB Client
$dbClient = DynamoDBClient::factory(array(
'region' => 'us-west-2'
));
// Query notes from database
$result = $dbClient->getItem(array(
'ConsistentRead' => true,
'TableName' => 'notes',
'Key' => array(
'noteId' => array('S' => $noteId) // Primary Key
)
));
$noteText = Helper::NAToBlank($result['Item']['noteText']['S']);
$noteTitle = Helper::NAToBlank($result['Item']['noteTitle']['S']);
$app->response->setBody(json_encode(array(
'noteId' => $noteId,
'noteTitle' => $noteTitle,
'noteText' => $noteText
)));
}
});
$app->post('/api/note', function () use ($app) {
if (isValid($app)) {
$noteTitle = $app->request->post('noteTitle');
$noteText = $app->request->post('noteText');
$noteId = $app->request->post('noteId');
// Get AWS DynamoDB Client
$dbClient = DynamoDBClient::factory(array(
'region' => 'us-west-2'
));
// Make insert into user notes in database
$dbClient->putItem(array(
'TableName' => 'notes',
'Item' => array(
'noteId' => array('S' => $noteId), // Primary Key
'noteTitle' => array('S' => Helper::blankToNA($noteTitle)),
'noteText' => array('S' => Helper::blankToNA($noteText))
)
));
$app->response->setBody(json_encode(array(
'noteId' => $noteId,
'noteTitle' => $noteTitle,
'noteText' => $noteText
)));
}
});
// Bulk insert notes
$app->post('/api/notes', function () use ($app) {
if (isValid($app)) {
$notes = $app->request->post('notes');
$putRequestArray = array();
// Get AWS DynamoDB Client
$dbClient = DynamoDBClient::factory(array(
'region' => 'us-west-2'
));
foreach ($notes as &$note) {
if (isset($note['noteId'])) {
$putRequestArray = array_merge_recursive($putRequestArray, array(
array (
'PutRequest' => array(
'Item' => array(
'noteId' => array('S' => Helper::blankToNA($note['noteId'])),
'noteTitle' => array('S' => Helper::blankToNA($note['noteTitle'])),
'noteText' => array('S' => Helper::blankToNA($note['noteText']))
)
)
)
));
}
}
unset($note);
// Make bulk insert into user notes in database
$dbClient->batchWriteItem(array(
'RequestItems' => array(
'notes' => $putRequestArray
)
));
$app->response->setBody(json_encode(array('message' => 'Successful')));
}
});
$app->put('/api/note/:noteId', function ($noteId) use ($app) {
if (isValid($app)) {
$noteTitle = $app->request->put('noteTitle');
$noteText = $app->request->put('noteText');
// Get AWS DynamoDB Client
$dbClient = DynamoDBClient::factory(array(
'region' => 'us-west-2'
));
// Make insert into user notes in database
$dbClient->putItem(array(
'TableName' => 'notes',
'Item' => array(
'noteId' => array('S' => $noteId), // Primary Key
'noteTitle' => array('S' => Helper::blankToNA($noteTitle)),
'noteText' => array('S' => Helper::blankToNA($noteText))
)
));
$app->response->setBody(json_encode(array(
'noteId' => $noteId,
'noteTitle' => $noteTitle,
'noteText' => $noteText
)));
}
});
$app->delete('/api/note/:noteId', function ($noteId) use ($app) {
if (isValid($app)) {
$token = $app->request->headers->get('X-Authorization');
$oldToken = explode(':', $token);
$email = $oldToken[0];
// Get AWS DynamoDB Client
$dbClient = DynamoDBClient::factory(array(
'region' => 'us-west-2'
));
// Make insert into user notes in database
$dbClient->deleteItem(array(
'TableName' => 'notes',
'Key' => array(
'noteId' => array('S' => $noteId) // Primary Key
)
));
$result = $dbClient->getItem(array(
'ConsistentRead' => true,
'TableName' => 'selected',
'Key' => array(
'email' => array('S' => $email) // Primary Key
)
));
$selectedNoteId = '';
if (isset($result['Item']['selected'])) {
$selectedNoteId = Helper::NAToBlank($result['Item']['selected']['S']);
}
if ($selectedNoteId === $noteId) {
$dbClient->deleteItem(array(
'TableName' => 'selected',
'Key' => array(
'email' => array('S' => $email) // Primary Key
)
));
}
$app->response->setBody(json_encode(array('message' => 'Successful')));
}
});
$app->get('/api/token', function () use ($app) {
// The old token should be sent in request header
$token = $app->request->headers->get('X-Authorization');
$app->response->headers->set('Content-Type', 'application/json');
// If the user had a token in their local storage, refresh it and send the new one back.
if (isset($token) && $token !== 'invalid') {
// Get email, expiration timestamp, and signature from old token
$oldToken = explode(':', $token);
$email = $oldToken[0];
$expirationTimestamp = $oldToken[1];
$givenSignature = $oldToken[2];
// Setup dates to check if token is expired
$currentDate = new DateTime();
$expirationDate = new DateTime();
$expirationDate->setTimestamp(intval($expirationTimestamp));
// Setup expected signature for purposes of comparison.
$rawToken = $email . ':' . $expirationTimestamp;
$expectedSignature = hash_hmac('ripemd160', $rawToken, getenv('notellosecret'));
if ($currentDate >= $expirationDate) {
// The token is expired
$app->response->setBody(json_encode(array('token' => 'InvalidToken')));
} else if (md5($givenSignature) === md5($expectedSignature)) {
// All is well and we can finally refresh the auth token
$newRawToken = $email . ':' . strtotime('+7 days');
$newSignature = hash_hmac('ripemd160', $newRawToken, getenv('notellosecret'));
$newAuthToken = $newRawToken . ':' . $newSignature;
$app->response->setBody(json_encode(array('token' => $newAuthToken)));
} else {
// The token is invalid and has probably been tampered with
$app->response->setBody(json_encode(array('token' => 'InvalidToken')));
}
} else {
// User didn't supply a token to be refreshed so this is either an invalid request or
// they just opened the appication.
$app->response->setBody(json_encode(array('token' => 'InvalidToken')));
}
});
$app->post('/api/login', function () use ($app) {
$app->response->headers->set('Content-Type', 'application/json');
$email = $app->request->post('email');
// Establish AWS Clients
$sesClient = SesClient::factory(array(
'region' => 'us-west-2'
));
$tokenId = Helper::GUID();
$msg = array();
$msg['Source'] = '"Notello"<noreply@notello.com>';
//ToAddresses must be an array
$msg['Destination']['ToAddresses'][] = $email;
$msg['Message']['Subject']['Data'] = "Notello login email";
$msg['Message']['Subject']['Charset'] = "UTF-8";
$msg['Message']['Body']['Text']['Data'] = getLoginTextEmail($email, $tokenId);
$msg['Message']['Body']['Text']['Charset'] = "UTF-8";
$msg['Message']['Body']['Html']['Data'] = getLoginHTMLEmail($email, $tokenId);
$msg['Message']['Body']['Html']['Charset'] = "UTF-8";
try {
$result = $sesClient->sendEmail($msg);
//save the MessageId which can be used to track the request
$msg_id = $result->get('MessageId');
//view sample output
echo json_encode(true);
} catch (Exception $e) {
//An error happened and the email did not get sent
echo($e->getMessage());
}
});
$app->get('/authenticate', function () use ($app) {
// Get tokenId from query string which is most likely given from login email
$tokenId = $app->request->get('token');
// Get rid of any left over tempAuthTokens.
$app->deleteCookie('tempAuthToken');
if (isset($tokenId)) {
// Get AWS DynamoDB Client
$dbClient = DynamoDBClient::factory(array(
'region' => 'us-west-2'
));
// Query token in Database
$result = $dbClient->getItem(array(
'ConsistentRead' => true,
'TableName' => 'tokens',
'Key' => array(
'tokenId' => array('S' => $tokenId)
)
));
// Get email from query result
$email = $result['Item']['email']['S'];
// If the email is not there, the token has been deleted or is just invalid
if (isset($email)) {
// Get inserted date from query result for comparison purposes
$insertedDateTimeStamp = $result['Item']['insertedDate']['N'];
$insertedDate = DateTime::createFromFormat( 'U', $insertedDateTimeStamp);
$currentTime = new DateTime();
// Delete token from database regardless of whether it's expired or not.
// Query each token for the given email
$scan = $dbClient->getIterator('Query', array(
'TableName' => 'tokens',
'IndexName' => 'email-index',
'KeyConditions' => array(
'email' => array(
'AttributeValueList' => array(
array('S' => $email)
),
'ComparisonOperator' => 'EQ'
)
)
)
);
// Delete each item for the given email
foreach ($scan as $item) {
$dbClient->deleteItem(array(
'TableName' => 'tokens',
'Key' => array(
'tokenId' => array('S' => $item['tokenId']['S'])
)
)
);
}
// If the token is over 1 hour old then it is considered invalid and we don't authenticate the user
if (date_diff($insertedDate, $currentTime)->h > 1) {
$app->setCookie('tempAuthToken', 'expired', '5 minutes', '/', 'notello.com', true);
} else {
$rawToken = $email . ':' . strtotime('+7 days');
$signature = hash_hmac('ripemd160', $rawToken, getenv('notellosecret'));
$authToken = $rawToken . ':' . $signature;
$app->setCookie('tempAuthToken', $authToken, '5 minutes', '/', 'notello.com', true);
}
} else {
// Invalid or deleted token
$app->setCookie('tempAuthToken', 'invalid', '5 minutes', '/', 'notello.com', true);
}
}
$app->response->redirect('/', 303);
});
// Run app
$app->run();