api.php (10998B)
1 <?php 2 ############################### 3 # include files from root dir # 4 ############################### 5 $root_1 = realpath($_SERVER["DOCUMENT_ROOT"]); 6 $currentdir = getcwd(); 7 $root_2 = str_replace($root_1, '', $currentdir); 8 $root_3 = explode("/", $root_2); 9 if ($root_3[1] == 'core') { 10 echo $root_3[1]; 11 $root = realpath($_SERVER["DOCUMENT_ROOT"]); 12 }else{ 13 $root = $root_1 . '/' . $root_3[1]; 14 } 15 require_once $root . '/core/api/v1/DbHandler.class.php'; 16 require_once $root . '/core/api/v1/PassHash.class.php'; 17 require_once $root . '/core/libs/Slim/Slim.php'; 18 \Slim\Slim::registerAutoloader(); 19 20 $app = new \Slim\Slim(); 21 22 // User id from db - Global Variable 23 $user_id = NULL; 24 25 /** 26 * Adding Middle Layer to authenticate every request 27 * Checking if the request has valid api key in the 'Authorization' header 28 */ 29 function authenticate(\Slim\Route $route) { 30 // Getting request headers 31 $headers = apache_request_headers(); 32 $response = array(); 33 $app = \Slim\Slim::getInstance(); 34 35 // Verifying Authorization Header 36 if (isset($headers['Authorization'])) { 37 $db = new DbHandler(); 38 39 // get the api key 40 $api_key = $headers['Authorization']; 41 // validating api key 42 if (!$db->isValidApiKey($api_key)) { 43 // api key is not present in users table 44 $response["error"] = true; 45 $response["message"] = "Access Denied. Invalid Api key"; 46 echoRespnse(401, $response); 47 $app->stop(); 48 } else { 49 global $user_id; 50 // get user primary key id 51 $user_id = $db->getUserId($api_key); 52 } 53 } else { 54 // api key is missing in header 55 $response["error"] = true; 56 $response["message"] = "Api key is misssing"; 57 echoRespnse(400, $response); 58 $app->stop(); 59 } 60 } 61 62 /** 63 * ----------- METHODS WITHOUT AUTHENTICATION --------------------------------- 64 */ 65 /** 66 * User Registration 67 * url - /register 68 * method - POST 69 * params - name, email, password 70 */ 71 $app->post('/register', function() use ($app) { 72 // check for required params 73 verifyRequiredParams(array('name', 'email', 'password')); 74 75 $response = array(); 76 77 // reading post params 78 $name = $app->request->post('name'); 79 $email = $app->request->post('email'); 80 $password = $app->request->post('password'); 81 82 // validating email address 83 validateEmail($email); 84 85 $db = new DbHandler(); 86 $res = $db->createUser($name, $email, $password); 87 88 if ($res == USER_CREATED_SUCCESSFULLY) { 89 $response["error"] = false; 90 $response["message"] = "You are successfully registered"; 91 } else if ($res == USER_CREATE_FAILED) { 92 $response["error"] = true; 93 $response["message"] = "Oops! An error occurred while registereing"; 94 } else if ($res == USER_ALREADY_EXISTED) { 95 $response["error"] = true; 96 $response["message"] = "Sorry, this email already existed"; 97 } 98 // echo json response 99 echoRespnse(201, $response); 100 }); 101 102 /** 103 * User Login 104 * url - /login 105 * method - POST 106 * params - email, password 107 */ 108 $app->post('/login', function() use ($app) { 109 // check for required params 110 verifyRequiredParams(array('email', 'password')); 111 112 // reading post params 113 $email = $app->request()->post('email'); 114 $password = $app->request()->post('password'); 115 $response = array(); 116 117 $db = new DbHandler(); 118 // check for correct email and password 119 if ($db->checkLogin($email, $password)) { 120 // get the user by email 121 $user = $db->getUserByEmail($email); 122 123 if ($user != NULL) { 124 $response["error"] = false; 125 $response['name'] = $user['name']; 126 $response['email'] = $user['email']; 127 $response['apiKey'] = $user['api_key']; 128 $response['createdAt'] = $user['created_at']; 129 } else { 130 // unknown error occurred 131 $response['error'] = true; 132 $response['message'] = "An error occurred. Please try again"; 133 } 134 } else { 135 // user credentials are wrong 136 $response['error'] = true; 137 $response['message'] = 'Login failed. Incorrect credentials'; 138 } 139 140 echoRespnse(200, $response); 141 }); 142 143 /** 144 * Listing single task of particual user 145 * method GET 146 * url /posts/:id 147 * Will return 404 if the task doesn't belongs to user 148 */ 149 $app->get('/posts/:id', function($post_id) { 150 global $user_id; 151 $response = array(); 152 $db = new DbHandler(); 153 154 // fetch task 155 $result = $db->getPosts($post_id); 156 157 if ($result != NULL) { 158 $response["error"] = false; 159 $response["id"] = $result["id"]; 160 $response["title"] = $result["title"]; 161 $response["text"] = $result["text"]; 162 $response["author"] = $result["author"]; 163 $response["category"] = $result["category"]; 164 $response["date"] = $result["date"]; 165 echoRespnse(200, $response); 166 } else { 167 $response["error"] = true; 168 $response["message"] = "The requested resource doesn't exists"; 169 echoRespnse(404, $response); 170 } 171 }); 172 173 /** 174 * Listing all posts 175 * method GET 176 * url /posts/ 177 * Will return 404 if the task doesn't belongs to user 178 */ 179 $app->get('/posts/', function() { 180 global $user_id; 181 $response = array(); 182 $db = new DbHandler(); 183 184 // fetch task 185 $result = $db->getPosts(NULL); 186 if ($result != NULL) { 187 $x = 1; 188 $id = 1; 189 while ($x < $result["post_id_clean"]+1){ 190 191 $response["$id"]["error"] = false; 192 $response["$id"]["id"] = $result["$id"]["id"]; 193 $response["$id"]["title"] = $result["$id"]["title"]; 194 $response["$id"]["text"] = $result["$id"]["text"]; 195 $response["$id"]["author"] = $result["$id"]["author"]; 196 $response["$id"]["category"] = $result["$id"]["category"]; 197 $response["$id"]["date"] = $result["$id"]["date"]; 198 $x = $x+1; 199 $id = $id+1; 200 } 201 echoRespnse(200, $response); 202 } else { 203 $response["error"] = true; 204 $response["message"] = "The requested resource doesn't exists"; 205 echoRespnse(404, $response); 206 } 207 }); 208 209 /* 210 * ------------------------ METHODS WITH AUTHENTICATION ------------------------ 211 */ 212 213 214 /** 215 * Creating new Post in db 216 * method POST 217 * params - name 218 * url - /createpost/ 219 */ 220 $app->Post('/createpost', 'authenticate', function() use ($app) { 221 // check for required params 222 verifyRequiredParams(array('task')); 223 224 $response = array(); 225 $task = $app->request->post('task'); 226 227 global $user_id; 228 $db = new DbHandler(); 229 230 // creating new task 231 $task_id = $db->createPost($id, $text, $title, $author, $category); 232 233 if ($task_id != NULL) { 234 $response["error"] = false; 235 $response["message"] = "Post created successfully"; 236 echoRespnse(201, $response); 237 } else { 238 $response["error"] = true; 239 $response["message"] = "Failed to create Post. Please try again"; 240 echoRespnse(200, $response); 241 } 242 }); 243 244 /** 245 * Updating existing Post 246 * method PUT 247 * params task, status 248 * url - /posts/:id 249 */ 250 $app->put('/posts/:id', 'authenticate', function($task_id) use($app) { 251 // check for required params 252 verifyRequiredParams(array('task', 'status')); 253 254 global $user_id; 255 $task = $app->request->put('task'); 256 $status = $app->request->put('status'); 257 258 $db = new DbHandler(); 259 $response = array(); 260 261 // updating task 262 $result = $db->updatePost($user_id, $task_id, $task, $status); 263 if ($result) { 264 // task updated successfully 265 $response["error"] = false; 266 $response["message"] = "Task updated successfully"; 267 } else { 268 // task failed to update 269 $response["error"] = true; 270 $response["message"] = "Task failed to update. Please try again!"; 271 } 272 echoRespnse(200, $response); 273 }); 274 275 /** 276 * Deleting Posts. Users can delete only their tasks 277 * method DELETE 278 * url /posts 279 */ 280 $app->delete('/posts/:id', 'authenticate', function($task_id) use($app) { 281 global $user_id; 282 283 $db = new DbHandler(); 284 $response = array(); 285 $result = $db->deletePost($user_id, $task_id); 286 if ($result) { 287 // task deleted successfully 288 $response["error"] = false; 289 $response["message"] = "Task deleted succesfully"; 290 } else { 291 // task failed to delete 292 $response["error"] = true; 293 $response["message"] = "Task failed to delete. Please try again!"; 294 } 295 echoRespnse(200, $response); 296 }); 297 298 /** 299 * Verifying required params posted or not 300 */ 301 function verifyRequiredParams($required_fields) { 302 $error = false; 303 $error_fields = ""; 304 $request_params = array(); 305 $request_params = $_REQUEST; 306 // Handling PUT request params 307 if ($_SERVER['REQUEST_METHOD'] == 'PUT') { 308 $app = \Slim\Slim::getInstance(); 309 parse_str($app->request()->getBody(), $request_params); 310 } 311 foreach ($required_fields as $field) { 312 if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) { 313 $error = true; 314 $error_fields .= $field . ', '; 315 } 316 } 317 318 if ($error) { 319 // Required field(s) are missing or empty 320 // echo error json and stop the app 321 $response = array(); 322 $app = \Slim\Slim::getInstance(); 323 $response["error"] = true; 324 $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty'; 325 echoRespnse(400, $response); 326 $app->stop(); 327 } 328 } 329 330 /** 331 * Validating email address 332 */ 333 function validateEmail($email) { 334 $app = \Slim\Slim::getInstance(); 335 if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { 336 $response["error"] = true; 337 $response["message"] = 'Email address is not valid'; 338 echoRespnse(400, $response); 339 $app->stop(); 340 } 341 } 342 343 /** 344 * Echoing json response to client 345 * @param String $status_code Http response code 346 * @param Int $response Json response 347 */ 348 function echoRespnse($status_code, $response) { 349 $app = \Slim\Slim::getInstance(); 350 // Http response code 351 $app->status($status_code); 352 353 // setting response content type to json 354 $app->contentType('application/json'); 355 356 echo json_encode($response); 357 } 358 359 $app->run(); 360 ?>