· 10 years ago · Sep 13, 2016, 10:28 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$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 */
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 $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 */
283function 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 */
315function 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 */
330function echoRespnse($status_code, $response) {
331 $app = \Slim\Slim::getInstance();
332 // Http response code
333 $app->status($status_code);
334
335 // setting response content type to json
336 $app->contentType('application/json');
337
338 echo json_encode($response);
339 }
340
341 $app->run();
342 ?>