· 10 years ago · Sep 13, 2016, 10:30 AM
1<?php
2
3require_once '../include/DbHandler.php';
4require_once '../include/PassHash.php';
5require '.././libs/Slim/Slim.php';
6
7\Slim\Slim::registerAutoloader();
8
9$app = new \Slim\Slim();
10
11// User id from db - Global Variable
12$user_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 */
18function 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 $user_id;
39 // get user primary key id
40 $user_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 * User 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->createUser($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 $user_id;
143 $response = array();
144 $db = new DbHandler();
145
146 // fetching all user tasks
147 $result = $db->getAllUserTasks($user_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($task_id) {
172 global $user_id;
173 $response = array();
174 $db = new DbHandler();
175
176 // fetch task
177 $result = $db->getTask($task_id, $user_id);
178
179 if ($result != NULL) {
180 $response["error"] = false;
181 $response["id"] = $result["id"];
182 $response["task"] = $result["task"];
183 $response["status"] = $result["status"];
184 $response["createdAt"] = $result["created_at"];
185 echoRespnse(200, $response);
186 } else {
187 $response["error"] = true;
188 $response["message"] = "The requested resource doesn't exists";
189 echoRespnse(404, $response);
190 }
191 });
192
193/**
194 * Creating new task in db
195 * method POST
196 * params - name
197 * url - /tasks/
198 */
199$app->post('/tasks', 'authenticate', function() use ($app) {
200 // check for required params
201 verifyRequiredParams(array('task'));
202
203 $response = array();
204 $task = $app->request->post('task');
205
206 global $user_id;
207 $db = new DbHandler();
208
209 // creating new task
210 $task_id = $db->createTask($user_id, $task);
211
212 if ($task_id != NULL) {
213 $response["error"] = false;
214 $response["message"] = "Task created successfully";
215 $response["task_id"] = $task_id;
216 echoRespnse(201, $response);
217 } else {
218 $response["error"] = true;
219 $response["message"] = "Failed to create task. Please try again";
220 echoRespnse(200, $response);
221 }
222 });
223
224/**
225 * Updating existing task
226 * method PUT
227 * params task, status
228 * url - /tasks/:id
229 */
230$app->put('/tasks/:id', 'authenticate', function($task_id) use($app) {
231 // check for required params
232 verifyRequiredParams(array('task', 'status'));
233
234 global $user_id;
235 $task = $app->request->put('task');
236 $status = $app->request->put('status');
237
238 $db = new DbHandler();
239 $response = array();
240
241 // updating task
242 $result = $db->updateTask($user_id, $task_id, $task, $status);
243 if ($result) {
244 // task updated successfully
245 $response["error"] = false;
246 $response["message"] = "Task updated successfully";
247 } else {
248 // task failed to update
249 $response["error"] = true;
250 $response["message"] = "Task failed to update. Please try again!";
251 }
252 echoRespnse(200, $response);
253 });
254
255/**
256 * Deleting task. Users can delete only their tasks
257 * method DELETE
258 * url /tasks
259 */
260$app->delete('/tasks/:id', 'authenticate', function($task_id) use($app) {
261 global $user_id;
262
263 $db = new DbHandler();
264 $response = array();
265 $result = $db->deleteTask($user_id, $task_id);
266 if ($result) {
267 // task deleted successfully
268 $response["error"] = false;
269 $response["message"] = "Task deleted succesfully";
270 } else {
271 // task failed to delete
272 $response["error"] = true;
273 $response["message"] = "Task failed to delete. Please try again!";
274 }
275 echoRespnse(200, $response);
276 });
277
278/**
279 * Verifying required params posted or not
280 */
281function verifyRequiredParams($required_fields) {
282 $error = false;
283 $error_fields = "";
284 $request_params = array();
285 $request_params = $_REQUEST;
286 // Handling PUT request params
287 if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
288 $app = \Slim\Slim::getInstance();
289 parse_str($app->request()->getBody(), $request_params);
290 }
291 foreach ($required_fields as $field) {
292 if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
293 $error = true;
294 $error_fields .= $field . ', ';
295 }
296 }
297
298 if ($error) {
299 // Required field(s) are missing or empty
300 // echo error json and stop the app
301 $response = array();
302 $app = \Slim\Slim::getInstance();
303 $response["error"] = true;
304 $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
305 echoRespnse(400, $response);
306 $app->stop();
307 }
308}
309
310/**
311 * Validating email address
312 */
313function validateEmail($email) {
314 $app = \Slim\Slim::getInstance();
315 if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
316 $response["error"] = true;
317 $response["message"] = 'Email address is not valid';
318 echoRespnse(400, $response);
319 $app->stop();
320 }
321}
322
323/**
324 * Echoing json response to client
325 * @param String $status_code Http response code
326 * @param Int $response Json response
327 */
328function echoRespnse($status_code, $response) {
329 $app = \Slim\Slim::getInstance();
330 // Http response code
331 $app->status($status_code);
332
333 // setting response content type to json
334 $app->contentType('application/json');
335
336 echo json_encode($response);
337}
338
339$app->run();
340?>