Guest User

Untitled

a guest
Sep 13th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 21.46 KB | None | 0 0
  1. <?php
  2.  
  3. require_once '../include/DbHandler.php';
  4. require_once '../include/PassHash.php';
  5. require '.././libs/Slim/Slim.php';
  6.  
  7. \Slim\Slim::registerAutoloader();
  8.  
  9. $app = new \Slim\Slim();
  10.  
  11. // User id from db - Global Variable
  12. $client_id = NULL;
  13.  
  14. /**
  15. * Adding Middle Layer to authenticate every request
  16. * Checking if the request has valid api key in the 'Authorization' header
  17. */
  18. function authenticate(\Slim\Route $route) {
  19. // Getting request headers
  20. $headers = apache_request_headers();
  21. $response = array();
  22. $app = \Slim\Slim::getInstance();
  23.  
  24. // Verifying Authorization Header
  25. if (isset($headers['Authorization'])) {
  26. $db = new DbHandler();
  27.  
  28. // get the api key
  29. $api_key = $headers['Authorization'];
  30. // validating api key
  31. if (!$db->isValidApiKey($api_key)) {
  32. // api key is not present in users table
  33. $response["error"] = true;
  34. $response["message"] = "Access Denied. Invalid Api key";
  35. echoRespnse(401, $response);
  36. $app->stop();
  37. } else {
  38. global $client_id;
  39. // get user primary key id
  40. $client_id = $db->getUserId($api_key);
  41. }
  42. } else {
  43. // api key is missing in header
  44. $response["error"] = true;
  45. $response["message"] = "Api key is misssing";
  46. echoRespnse(400, $response);
  47. $app->stop();
  48. }
  49. }
  50.  
  51. /**
  52. * ----------- METHODS WITHOUT AUTHENTICATION ---------------------------------
  53. */
  54. /**
  55. * Client Registration
  56. * url - /register
  57. * method - POST
  58. * params - name, email, password
  59. */
  60. $app->post('/register', function() use ($app) {
  61. // check for required params
  62. verifyRequiredParams(array('name', 'email', 'password'));
  63.  
  64. $response = array();
  65.  
  66. // reading post params
  67. $name = $app->request->post('name');
  68. $email = $app->request->post('email');
  69. $password = $app->request->post('password');
  70.  
  71. // validating email address
  72. validateEmail($email);
  73.  
  74. $db = new DbHandler();
  75. $res = $db->createClient($name, $email, $password);
  76.  
  77. if ($res == USER_CREATED_SUCCESSFULLY) {
  78. $response["error"] = false;
  79. $response["message"] = "You are successfully registered";
  80. } else if ($res == USER_CREATE_FAILED) {
  81. $response["error"] = true;
  82. $response["message"] = "Oops! An error occurred while registereing";
  83. } else if ($res == USER_ALREADY_EXISTED) {
  84. $response["error"] = true;
  85. $response["message"] = "Sorry, this email already existed";
  86. }
  87. // echo json response
  88. echoRespnse(201, $response);
  89. });
  90.  
  91. /**
  92. * User Login
  93. * url - /login
  94. * method - POST
  95. * params - email, password
  96. */
  97. $app->post('/login', function() use ($app) {
  98. // check for required params
  99. verifyRequiredParams(array('email', 'password'));
  100.  
  101. // reading post params
  102. $email = $app->request()->post('email');
  103. $password = $app->request()->post('password');
  104. $response = array();
  105.  
  106. $db = new DbHandler();
  107. // check for correct email and password
  108. if ($db->checkLogin($email, $password)) {
  109. // get the user by email
  110. $user = $db->getUserByEmail($email);
  111.  
  112. if ($user != NULL) {
  113. $response["error"] = false;
  114. $response['name'] = $user['name'];
  115. $response['email'] = $user['email'];
  116. $response['apiKey'] = $user['api_key'];
  117. $response['createdAt'] = $user['created_at'];
  118. } else {
  119. // unknown error occurred
  120. $response['error'] = true;
  121. $response['message'] = "An error occurred. Please try again";
  122. }
  123. } else {
  124. // user credentials are wrong
  125. $response['error'] = true;
  126. $response['message'] = 'Login failed. Incorrect credentials';
  127. }
  128.  
  129. echoRespnse(200, $response);
  130. });
  131.  
  132. /*
  133. * ------------------------ METHODS WITH AUTHENTICATION ------------------------
  134. */
  135.  
  136. /**
  137. * Listing all tasks of particual user
  138. * method GET
  139. * url /tasks
  140. */
  141. $app->get('/tasks', 'authenticate', function() {
  142. global $client_id;
  143. $response = array();
  144. $db = new DbHandler();
  145.  
  146. // fetching all user tasks
  147. $result = $db->getAllUserTasks($client_id);
  148.  
  149. $response["error"] = false;
  150. $response["tasks"] = array();
  151.  
  152. // looping through result and preparing tasks array
  153. while ($task = $result->fetch_assoc()) {
  154. $tmp = array();
  155. $tmp["id"] = $task["id"];
  156. $tmp["task"] = $task["task"];
  157. $tmp["status"] = $task["status"];
  158. $tmp["createdAt"] = $task["created_at"];
  159. array_push($response["tasks"], $tmp);
  160. }
  161.  
  162. echoRespnse(200, $response);
  163. });
  164.  
  165. /**
  166. * Listing single task of particual user
  167. * method GET
  168. * url /tasks/:id
  169. * Will return 404 if the task doesn't belongs to user
  170. */
  171. $app->get('/tasks/:id', 'authenticate', function($project_id) {
  172. global $client_id;
  173. $response = array();
  174. $db = new DbHandler();
  175.  
  176. // fetch task
  177. $result = $db->getProject($project_id, $client_id);
  178.  
  179. if ($result != NULL) {
  180. $response["error"] = false;
  181. $response["id"] = $result["id"];
  182. $response["name"] = $result["name"];
  183. $response["status"] = $result["status"];
  184. $response["start_date"] = $result["start_date"];
  185. $response["thumbnail"] = $result["thumbnail"];
  186.  
  187. echoRespnse(200, $response);
  188. } else {
  189. $response["error"] = true;
  190. $response["message"] = "The requested resource doesn't exists";
  191. echoRespnse(404, $response);
  192. }
  193. });
  194.  
  195. /**
  196. * Creating new task in db
  197. * method POST
  198. * params - name
  199. * url - /tasks/
  200. */
  201. $app->post('/tasks', 'authenticate', function() use ($app) {
  202. // check for required params
  203. verifyRequiredParams(array('task'));
  204.  
  205. $response = array();
  206. $task = $app->request->post('task');
  207.  
  208. global $client_id;
  209. $db = new DbHandler();
  210.  
  211. // creating new task
  212. $task_id = $db->createTask($client_id, $task);
  213.  
  214. if ($task_id != NULL) {
  215. $response["error"] = false;
  216. $response["message"] = "Task created successfully";
  217. $response["task_id"] = $task_id;
  218. echoRespnse(201, $response);
  219. } else {
  220. $response["error"] = true;
  221. $response["message"] = "Failed to create task. Please try again";
  222. echoRespnse(200, $response);
  223. }
  224. });
  225.  
  226. /**
  227. * Updating existing task
  228. * method PUT
  229. * params task, status
  230. * url - /tasks/:id
  231. */
  232. $app->put('/tasks/:id', 'authenticate', function($task_id) use($app) {
  233. // check for required params
  234. verifyRequiredParams(array('task', 'status'));
  235.  
  236. global $client_id;
  237. $task = $app->request->put('task');
  238. $status = $app->request->put('status');
  239.  
  240. $db = new DbHandler();
  241. $response = array();
  242.  
  243. // updating task
  244. $result = $db->updateTask($client_id, $task_id, $task, $status);
  245. if ($result) {
  246. // task updated successfully
  247. $response["error"] = false;
  248. $response["message"] = "Task updated successfully";
  249. } else {
  250. // task failed to update
  251. $response["error"] = true;
  252. $response["message"] = "Task failed to update. Please try again!";
  253. }
  254. echoRespnse(200, $response);
  255. });
  256.  
  257. /**
  258. * Deleting task. Users can delete only their tasks
  259. * method DELETE
  260. * url /tasks
  261. */
  262. $app->delete('/tasks/:id', 'authenticate', function($task_id) use($app) {
  263. global $client_id;
  264.  
  265. $db = new DbHandler();
  266. $response = array();
  267. $result = $db->deleteTask($client_id, $task_id);
  268. if ($result) {
  269. // task deleted successfully
  270. $response["error"] = false;
  271. $response["message"] = "Task deleted succesfully";
  272. } else {
  273. // task failed to delete
  274. $response["error"] = true;
  275. $response["message"] = "Task failed to delete. Please try again!";
  276. }
  277. echoRespnse(200, $response);
  278. });
  279.  
  280. /**
  281. * Verifying required params posted or not
  282. */
  283. function verifyRequiredParams($required_fields) {
  284. $error = false;
  285. $error_fields = "";
  286. $request_params = array();
  287. $request_params = $_REQUEST;
  288. // Handling PUT request params
  289. if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
  290. $app = \Slim\Slim::getInstance();
  291. parse_str($app->request()->getBody(), $request_params);
  292. }
  293. foreach ($required_fields as $field) {
  294. if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
  295. $error = true;
  296. $error_fields .= $field . ', ';
  297. }
  298. }
  299.  
  300. if ($error) {
  301. // Required field(s) are missing or empty
  302. // echo error json and stop the app
  303. $response = array();
  304. $app = \Slim\Slim::getInstance();
  305. $response["error"] = true;
  306. $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
  307. echoRespnse(400, $response);
  308. $app->stop();
  309. }
  310. }
  311.  
  312. /**
  313. * Validating email address
  314. */
  315. function validateEmail($email) {
  316. $app = \Slim\Slim::getInstance();
  317. if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  318. $response["error"] = true;
  319. $response["message"] = 'Email address is not valid';
  320. echoRespnse(400, $response);
  321. $app->stop();
  322. }
  323. }
  324.  
  325. /**
  326. * Echoing json response to client
  327. * @param String $status_code Http response code
  328. * @param Int $response Json response
  329. */
  330. function echoRespnse($status_code, $response) {
  331. $app = \Slim\Slim::getInstance();
  332. // Http response code
  333. $app->status($status_code);<?php
  334.  
  335. require_once '../include/DbHandler.php';
  336. require_once '../include/PassHash.php';
  337. require '.././libs/Slim/Slim.php';
  338.  
  339. \Slim\Slim::registerAutoloader();
  340.  
  341. $app = new \Slim\Slim();
  342.  
  343. // User id from db - Global Variable
  344. $client_id = NULL;
  345.  
  346. /**
  347. * Adding Middle Layer to authenticate every request
  348. * Checking if the request has valid api key in the 'Authorization' header
  349. */
  350. function authenticate(\Slim\Route $route) {
  351. // Getting request headers
  352. $headers = apache_request_headers();
  353. $response = array();
  354. $app = \Slim\Slim::getInstance();
  355.  
  356. // Verifying Authorization Header
  357. if (isset($headers['Authorization'])) {
  358. $db = new DbHandler();
  359.  
  360. // get the api key
  361. $api_key = $headers['Authorization'];
  362. // validating api key
  363. if (!$db->isValidApiKey($api_key)) {
  364. // api key is not present in users table
  365. $response["error"] = true;
  366. $response["message"] = "Access Denied. Invalid Api key";
  367. echoRespnse(401, $response);
  368. $app->stop();
  369. } else {
  370. global $client_id;
  371. // get user primary key id
  372. $client_id = $db->getUserId($api_key);
  373. }
  374. } else {
  375. // api key is missing in header
  376. $response["error"] = true;
  377. $response["message"] = "Api key is misssing";
  378. echoRespnse(400, $response);
  379. $app->stop();
  380. }
  381. }
  382.  
  383. /**
  384. * ----------- METHODS WITHOUT AUTHENTICATION ---------------------------------
  385. */
  386. /**
  387. * User Registration
  388. * url - /register
  389. * method - POST
  390. * params - name, email, password
  391. */
  392. $app->post('/register', function() use ($app) {
  393. // check for required params
  394. verifyRequiredParams(array('name', 'email', 'password'));
  395.  
  396. $response = array();
  397.  
  398. // reading post params
  399. $name = $app->request->post('name');
  400. $email = $app->request->post('email');
  401. $password = $app->request->post('password');
  402.  
  403. // validating email address
  404. validateEmail($email);
  405.  
  406. $db = new DbHandler();
  407. $res = $db->createUser($name, $email, $password);
  408.  
  409. if ($res == USER_CREATED_SUCCESSFULLY) {
  410. $response["error"] = false;
  411. $response["message"] = "You are successfully registered";
  412. } else if ($res == USER_CREATE_FAILED) {
  413. $response["error"] = true;
  414. $response["message"] = "Oops! An error occurred while registereing";
  415. } else if ($res == USER_ALREADY_EXISTED) {
  416. $response["error"] = true;
  417. $response["message"] = "Sorry, this email already existed";
  418. }
  419. // echo json response
  420. echoRespnse(201, $response);
  421. });
  422.  
  423. /**
  424. * User Login
  425. * url - /login
  426. * method - POST
  427. * params - email, password
  428. */
  429. $app->post('/login', function() use ($app) {
  430. // check for required params
  431. verifyRequiredParams(array('email', 'password'));
  432.  
  433. // reading post params
  434. $email = $app->request()->post('email');
  435. $password = $app->request()->post('password');
  436. $response = array();
  437.  
  438. $db = new DbHandler();
  439. // check for correct email and password
  440. if ($db->checkLogin($email, $password)) {
  441. // get the user by email
  442. $user = $db->getUserByEmail($email);
  443.  
  444. if ($user != NULL) {
  445. $response["error"] = false;
  446. $response['name'] = $user['name'];
  447. $response['email'] = $user['email'];
  448. $response['apiKey'] = $user['api_key'];
  449. $response['createdAt'] = $user['created_at'];
  450. } else {
  451. // unknown error occurred
  452. $response['error'] = true;
  453. $response['message'] = "An error occurred. Please try again";
  454. }
  455. } else {
  456. // user credentials are wrong
  457. $response['error'] = true;
  458. $response['message'] = 'Login failed. Incorrect credentials';
  459. }
  460.  
  461. echoRespnse(200, $response);
  462. });
  463.  
  464. /*
  465. * ------------------------ METHODS WITH AUTHENTICATION ------------------------
  466. */
  467.  
  468. /**
  469. * Listing all tasks of particual user
  470. * method GET
  471. * url /tasks
  472. */
  473. $app->get('/tasks', 'authenticate', function() {
  474. global $client_id;
  475. $response = array();
  476. $db = new DbHandler();
  477.  
  478. // fetching all user tasks
  479. $result = $db->getAllUserTasks($client_id);
  480.  
  481. $response["error"] = false;
  482. $response["tasks"] = array();
  483.  
  484. // looping through result and preparing tasks array
  485. while ($task = $result->fetch_assoc()) {
  486. $tmp = array();
  487. $tmp["id"] = $task["id"];
  488. $tmp["task"] = $task["task"];
  489. $tmp["status"] = $task["status"];
  490. $tmp["createdAt"] = $task["created_at"];
  491. array_push($response["tasks"], $tmp);
  492. }
  493.  
  494. echoRespnse(200, $response);
  495. });
  496.  
  497. /**
  498. * Listing single task of particual user
  499. * method GET
  500. * url /tasks/:id
  501. * Will return 404 if the task doesn't belongs to user
  502. */
  503. $app->get('/tasks/:id', 'authenticate', function($task_id) {
  504. global $client_id;
  505. $response = array();
  506. $db = new DbHandler();
  507.  
  508. // fetch task
  509. $result = $db->getTask($task_id, $client_id);
  510.  
  511. if ($result != NULL) {
  512. $response["error"] = false;
  513. $response["id"] = $result["id"];
  514. $response["task"] = $result["task"];
  515. $response["status"] = $result["status"];
  516. $response["createdAt"] = $result["created_at"];
  517. echoRespnse(200, $response);
  518. } else {
  519. $response["error"] = true;
  520. $response["message"] = "The requested resource doesn't exists";
  521. echoRespnse(404, $response);
  522. }
  523. });
  524.  
  525. /**
  526. * Creating new task in db
  527. * method POST
  528. * params - name
  529. * url - /tasks/
  530. */
  531. $app->post('/tasks', 'authenticate', function() use ($app) {
  532. // check for required params
  533. verifyRequiredParams(array('task'));
  534.  
  535. $response = array();
  536. $task = $app->request->post('task');
  537.  
  538. global $client_id;
  539. $db = new DbHandler();
  540.  
  541. // creating new task
  542. $task_id = $db->createTask($client_id, $task);
  543.  
  544. if ($task_id != NULL) {
  545. $response["error"] = false;
  546. $response["message"] = "Task created successfully";
  547. $response["task_id"] = $task_id;
  548. echoRespnse(201, $response);
  549. } else {
  550. $response["error"] = true;
  551. $response["message"] = "Failed to create task. Please try again";
  552. echoRespnse(200, $response);
  553. }
  554. });
  555.  
  556. /**
  557. * Updating existing task
  558. * method PUT
  559. * params task, status
  560. * url - /tasks/:id
  561. */
  562. $app->put('/tasks/:id', 'authenticate', function($task_id) use($app) {
  563. // check for required params
  564. verifyRequiredParams(array('task', 'status'));
  565.  
  566. global $client_id;
  567. $task = $app->request->put('task');
  568. $status = $app->request->put('status');
  569.  
  570. $db = new DbHandler();
  571. $response = array();
  572.  
  573. // updating task
  574. $result = $db->updateTask($client_id, $task_id, $task, $status);
  575. if ($result) {
  576. // task updated successfully
  577. $response["error"] = false;
  578. $response["message"] = "Task updated successfully";
  579. } else {
  580. // task failed to update
  581. $response["error"] = true;
  582. $response["message"] = "Task failed to update. Please try again!";
  583. }
  584. echoRespnse(200, $response);
  585. });
  586.  
  587. /**
  588. * Deleting task. Users can delete only their tasks
  589. * method DELETE
  590. * url /tasks
  591. */
  592. $app->delete('/tasks/:id', 'authenticate', function($task_id) use($app) {
  593. global $client_id;
  594.  
  595. $db = new DbHandler();
  596. $response = array();
  597. $result = $db->deleteTask($client_id, $task_id);
  598. if ($result) {
  599. // task deleted successfully
  600. $response["error"] = false;
  601. $response["message"] = "Task deleted succesfully";
  602. } else {
  603. // task failed to delete
  604. $response["error"] = true;
  605. $response["message"] = "Task failed to delete. Please try again!";
  606. }
  607. echoRespnse(200, $response);
  608. });
  609.  
  610. /**
  611. * Verifying required params posted or not
  612. */
  613. function verifyRequiredParams($required_fields) {
  614. $error = false;
  615. $error_fields = "";
  616. $request_params = array();
  617. $request_params = $_REQUEST;
  618. // Handling PUT request params
  619. if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
  620. $app = \Slim\Slim::getInstance();
  621. parse_str($app->request()->getBody(), $request_params);
  622. }
  623. foreach ($required_fields as $field) {
  624. if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
  625. $error = true;
  626. $error_fields .= $field . ', ';
  627. }
  628. }
  629.  
  630. if ($error) {
  631. // Required field(s) are missing or empty
  632. // echo error json and stop the app
  633. $response = array();
  634. $app = \Slim\Slim::getInstance();
  635. $response["error"] = true;
  636. $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
  637. echoRespnse(400, $response);
  638. $app->stop();
  639. }
  640. }
  641.  
  642. /**
  643. * Validating email address
  644. */
  645. function validateEmail($email) {
  646. $app = \Slim\Slim::getInstance();
  647. if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  648. $response["error"] = true;
  649. $response["message"] = 'Email address is not valid';
  650. echoRespnse(400, $response);
  651. $app->stop();
  652. }
  653. }
  654.  
  655. /**
  656. * Echoing json response to client
  657. * @param String $status_code Http response code
  658. * @param Int $response Json response
  659. */
  660. function echoRespnse($status_code, $response) {
  661. $app = \Slim\Slim::getInstance();
  662. // Http response code
  663. $app->status($status_code);
  664.  
  665. // setting response content type to json
  666. $app->contentType('application/json');
  667.  
  668. echo json_encode($response);
  669. }
  670.  
  671. $app->run();
  672. ?>
  673.  
  674. // setting response content type to json
  675. $app->contentType('application/json');
  676.  
  677. echo json_encode($response);
  678. }
  679.  
  680. $app->run();
  681. ?>
Add Comment
Please, Sign In to add comment