-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.php
472 lines (368 loc) · 13.1 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
<?php
ini_set("date.timezone", "Asia/Kuala_Lumpur");
header('Access-Control-Allow-Origin: *');
//*
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
// Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
// you want to allow, and if so:
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
//*/
require_once 'vendor/autoload.php';
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
include_once("salt_pepper.php");
include_once("database_class.php");
//load environment variable - jwt secret key
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();
//jwt secret key in case dotenv not working in apache
//$jwtSecretKey = "jwt_secret_key";
function getDatabase() {
$dbhost="den1.mysql2.gear.host";
$dbuser="webtechdb";
$dbpass="webtechdb!";
$dbname="webtechdb";
$db = new Database($dbhost, $dbuser, $dbpass, $dbname);
return $db;
}
use Slim\App;
use Slim\Middleware\TokenAuthentication;
use Firebase\JWT\JWT;
function getLoginTokenPayload($request, $response) {
$token_array = $request->getHeader('HTTP_AUTHORIZATION');
$token = substr($token_array[0], 7);
//decode the token
try
{
$tokenDecoded = JWT::decode(
$token,
getenv('JWT_SECRET'),
array('HS256')
);
//in case dotenv not working
/*
$tokenDecoded = JWT::decode(
$token,
$GLOBALS['jwtSecretKey'],
array('HS256')
);
*/
}
catch(Exception $e)
{
$data = Array(
"jwt_status" => "token_invalid"
);
return $response->withJson($data, 401)
->withHeader('Content-tye', 'application/json');
}
return $tokenDecoded->login;
}
$config = [
'settings' => [
'displayErrorDetails' => true
]
];
$app = new App($config);
$authenticator = function($request, TokenAuthentication $tokenAuth){
/**
* Try find authorization token via header, parameters, cookie or attribute
* If token not found, return response with status 401 (unauthorized)
*/
$token = $tokenAuth->findToken($request); //from header
try {
$tokenDecoded = JWT::decode($token, getenv('JWT_SECRET'), array('HS256'));
//in case dotenv not working
//$tokenDecoded = JWT::decode($token, $GLOBALS['jwtSecretKey'], array('HS256'));
}
catch(Exception $e) {
throw new \app\UnauthorizedException('Invalid Token');
}
};
/**
* Add token authentication middleware
*/
$app->add(new TokenAuthentication([
'path' => '/', //secure route - need token
'passthrough' => [ //public route, no token needed
'/ping',
'/token',
'/uuid',
'/hello',
'/calc',
'/registration',
'/checkemail',
'/auth',
'/users'
],
'authenticator' => $authenticator
]));
/**
* Public route example
*/
$app->get('/ping', function($request, $response){
$output = ['msg' => 'RESTful API works, active and online!'];
return $response->withJson($output, 200, JSON_PRETTY_PRINT);
});
$app->get('/uuid', function($request, $response) {
try {
// Generate a version 1 (time-based) UUID object
//$uuid1 = Uuid::uuid1();
//echo $uuid1->toString() . "\n"; // i.e. e4eaaaf2-d142-11e1-b3e4-080027620cdd
// Generate a version 3 (name-based and hashed with MD5) UUID object
$uuid3 = Uuid::uuid3(Uuid::NAMESPACE_DNS, 'php.net');
echo $uuid3->toString() . "<br />"; // i.e. 11a38b9a-b3da-360f-9353-a5a725514269
// Generate a version 4 (random) UUID object
$uuid4 = Uuid::uuid4();
echo $uuid4->toString() . "<br />"; // i.e. 25769c6c-d34d-4bfe-ba98-e0ee856f3e7a
// Generate a version 5 (name-based and hashed with SHA1) UUID object
$uuid5 = Uuid::uuid5(Uuid::NAMESPACE_DNS, 'php.net');
echo $uuid5->toString() . "\n"; // i.e. c4a760a8-dbcf-5254-a0d9-6a4474bd1b62
} catch (UnsatisfiedDependencyException $e) {
// Some dependency was not met. Either the method cannot be called on a
// 32-bit system, or it can, but it relies on Moontoast\Math to be present.
echo 'Caught exception: ' . $e->getMessage() . "\n";
}
});
//generate token
//OAUTH2 token will not need this route
$app->get('/token', function($request, $response){
//create JWT token
$date = date_create();
$jwtIAT = date_timestamp_get($date);
$jwtExp = $jwtIAT + (20 * 60); //expire after 20 minutes
$jwtToken = array(
"iss" => "rbk.net", //client key
"iat" => $jwtIAT, //issued at time
"exp" => $jwtExp, //expire
"role" => "member",
"email" => "[email protected]"
);
$token = JWT::encode($jwtToken, getenv('JWT_SECRET'));
//in case dotenv not working
//$token = JWT::encode($jwtToken, $GLOBALS['jwtSecretKey']);
$data = array(
'session' => true,
'token' => $token
);
return $response->withJson($data, 200)
->withHeader('Content-type', 'application/json');
});
//route with jwt token needed
$app->get('/jwtroute', function($request, $response){
$email = getEmailTokenPayload($request, $response);
$data = array(
'msg' => 'JWT Token authentication works!',
'email' => $email
);
return $response->withJson($data, 200, JSON_PRETTY_PRINT);
});
//public route with 1 parameter
$app->get('/hello/[{name}]', function($request, $response, $args){
$name = $args['name'];
$msg = "Hello $name, welcome to RESTFul world";
$data = array(
'msg' => $msg
);
return $response->withJson($data, 200, JSON_PRETTY_PRINT);
});
//public route with more than one parameters
$app->get('/calc[/{num1}/{num2}]', function($request, $response, $args){
$num1 = $args['num1'];
$num2 = $args['num2'];
$total = $num1 + $num2;
$msg = "$num1 + $num2 = $total";
$data = array(
'msg' => $msg
);
return $response->withJson($data, 200, JSON_PRETTY_PRINT);
});
/**
* Public route /registration for member registration
*/
$app->post('/registration', function($request, $response){
$json = json_decode($request->getBody());
$name = $json->name;
$login = $json->login;
$email = $json->email;
$clearpassword = $json->password;
//insert user
$db = getDatabase();
$dbs = $db->insertUser($login, $clearpassword, $name, $email);
$db->close();
$data = array(
"insertstatus" => $dbs->status,
"error" => $dbs->error
);
return $response->withJson($data, 200)
->withHeader('Content-type', 'application/json');
});
/**
* Public route /checkemail/:email for checking email availability
* in member registration
*/
$app->get('/checkemail/[{email}]', function($request, $response, $args){
$email = $args['email'];
$db = getDatabase();
$status = $db->checkemail($email);
$db->close();
$data = array();
if ($status) {
$data = array(
'exist' => true
);
} else {
$data = array(
"exist" => false
);
}
return $response->withJson($data, 200)
->withHeader('Content-type', 'application/json');
});
/**
* Public route /auth for creds authentication
*/
$app->post('/auth', function($request, $response){
//extract form data - email and password
$json = json_decode($request->getBody());
$login = $json->login;
$clearpassword = $json->password;
//do db authentication
$db = getDatabase();
$data = $db->authenticateUser($login);
$db->close();
//status -1 -> user not found
//status 0 -> wrong password
//status 1 -> login success
$returndata = array(
);
//user not found
if ($data === NULL) {
$returndata = array(
'status' => -1
);
}
//user found
else {
//now verify password hash - one way mdf hash using salt-peper
if (pepper($clearpassword, $data->passwordhash)) {
//correct password
//create JWT token
$date = date_create();
$jwtIAT = date_timestamp_get($date);
$jwtExp = $jwtIAT + (60 * 60 * 12); //expire after 12 hours
$jwtToken = array(
"iss" => "mycontacts.net", //token issuer
"iat" => $jwtIAT, //issued at time
"exp" => $jwtExp, //expire
"role" => "member",
"login" => $data->login
);
$token = JWT::encode($jwtToken, getenv('JWT_SECRET'));
$returndata = array(
'status' => 1,
'token' => $token,
'login' => $data->login
);
} else {
//wrong password
$returndata = array(
'status' => 0
);
}
}
return $response->withJson($returndata, 200)
->withHeader('Content-type', 'application/json');
});
//POST - INSERT CONTACT - secure route - need token
$app->post('/contacts', function($request, $response){
$ownerlogin = getLoginTokenPayload($request, $response);
//form data
$json = json_decode($request->getBody());
$name = $json->name;
$email = $json->email;
$mobileno = $json->mobileno;
$db = getDatabase();
$dbs = $db->insertContact($name, $email, $mobileno, $ownerlogin);
$db->close();
$data = array(
"insertstatus" => $dbs->status,
"error" => $dbs->error
);
return $response->withJson($data, 200)
->withHeader('Content-type', 'application/json');
});
//GET - ALL USERS
$app->get('/users', function($request, $response){
$db = getDatabase();
$data = $db->getAllUsers();
$db->close();
return $response->withJson($data, 200)
->withHeader('Content-type', 'application/json');
});
//GET - ALL CONTACTS
$app->get('/contacts', function($request, $response){
$ownerlogin = getLoginTokenPayload($request, $response);
$db = getDatabase();
$data = $db->getAllContactsViaLogin($ownerlogin);
$db->close();
return $response->withJson($data, 200)
->withHeader('Content-type', 'application/json');
});
//GET - SINGLE CONTACT VIA ID
$app->get('/contacts/[{id}]', function($request, $response, $args){
//get owner login - to prevent rolling no hacking
$ownerlogin = getLoginTokenPayload($request, $response);
$id = $args['id'];
$db = getDatabase();
$data = $db->getContactViaId($id, $ownerlogin);
$db->close();
return $response->withJson($data, 200)
->withHeader('Content-type', 'application/json');
});
//PUT - UPDATE SINGLE CONTACT VIA ID
$app->put('/contacts/[{id}]', function($request, $response, $args){
$id = $args['id'];
//form data
$json = json_decode($request->getBody());
$name = $json->name;
$email = $json->email;
$mobileno = $json->mobileno;
$db = getDatabase();
$dbs = $db->updateContactViaId($id, $name, $email, $mobileno);
$db->close();
$data = Array(
"updatestatus" => $dbs->status,
"error" => $dbs->error
);
return $response->withJson($data, 200)
->withHeader('Content-type', 'application/json');
});
//DELETE - SINGLE CONTACT VIA ID
$app->delete('/contacts/[{id}]', function($request, $response, $args){
$id = $args['id'];
$db = getDatabase();
$dbs = $db->deleteContactViaId($id);
$db->close();
$data = Array(
"deletestatus" => $dbs->status,
"error" => $dbs->error
);
return $response->withJson($data, 200)
->withHeader('Content-type', 'application/json');
});
$app->run();