rpicms

A CMS for the Raspberry Pi
git clone git://archive.git.mtrnord.blog/RpicmsTeam/rpicms.git
Log | Files | Refs | README | LICENSE

commit 275bbc6766e02245cdfefad2bf0d037a7acbdbbf
parent e1ce2a1361a719e664d3fd718acb2c1587ac3d80
Author: MTRNord <mtrnord1@gmail.com>
Date:   Tue,  3 Feb 2015 07:13:20 +0100

maybe fixed api (not fully omplemented)

Diffstat:
Mcore/api/v1/api.php | 341+++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------
1 file changed, 245 insertions(+), 96 deletions(-)

diff --git a/core/api/v1/api.php b/core/api/v1/api.php @@ -16,74 +16,53 @@ require_once $root . '/core/api/v1/DbHandler.class.php'; require_once $root . '/core/api/v1/PassHash.class.php'; require_once $root . '/core/libs/Slim/Slim.php'; \Slim\Slim::registerAutoloader(); - + $app = new \Slim\Slim(); - + // User id from db - Global Variable $user_id = NULL; - + /** - * Verifying required params posted or not + * Adding Middle Layer to authenticate every request + * Checking if the request has valid api key in the 'Authorization' header */ -function verifyRequiredParams($required_fields) { - $error = false; - $error_fields = ""; - $request_params = array(); - $request_params = $_REQUEST; - // Handling PUT request params - if ($_SERVER['REQUEST_METHOD'] == 'PUT') { - $app = \Slim\Slim::getInstance(); - parse_str($app->request()->getBody(), $request_params); - } - foreach ($required_fields as $field) { - if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) { - $error = true; - $error_fields .= $field . ', '; +function authenticate(\Slim\Route $route) { + // Getting request headers + $headers = apache_request_headers(); + $response = array(); + $app = \Slim\Slim::getInstance(); + + // Verifying Authorization Header + if (isset($headers['Authorization'])) { + $db = new DbHandler(); + + // get the api key + $api_key = $headers['Authorization']; + // validating api key + if (!$db->isValidApiKey($api_key)) { + // api key is not present in users table + $response["error"] = true; + $response["message"] = "Access Denied. Invalid Api key"; + echoRespnse(401, $response); + $app->stop(); + } else { + global $user_id; + // get user primary key id + $user_id = $db->getUserId($api_key); } - } - - if ($error) { - // Required field(s) are missing or empty - // echo error json and stop the app - $response = array(); - $app = \Slim\Slim::getInstance(); + } else { + // api key is missing in header $response["error"] = true; - $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty'; + $response["message"] = "Api key is misssing"; echoRespnse(400, $response); $app->stop(); } } - + /** - * Validating email address + * ----------- METHODS WITHOUT AUTHENTICATION --------------------------------- */ -function validateEmail($email) { - $app = \Slim\Slim::getInstance(); - if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { - $response["error"] = true; - $response["message"] = 'Email address is not valid'; - echoRespnse(400, $response); - $app->stop(); - } -} - /** - * Echoing json response to client - * @param String $status_code Http response code - * @param Int $response Json response - */ -function echoRespnse($status_code, $response) { - $app = \Slim\Slim::getInstance(); - // Http response code - $app->status($status_code); - - // setting response content type to json - $app->contentType('application/json'); - - echo json_encode($response); -} - - /** * User Registration * url - /register * method - POST @@ -92,34 +71,34 @@ function echoRespnse($status_code, $response) { $app->post('/register', function() use ($app) { // check for required params verifyRequiredParams(array('name', 'email', 'password')); - + $response = array(); - + // reading post params $name = $app->request->post('name'); $email = $app->request->post('email'); $password = $app->request->post('password'); - + // validating email address validateEmail($email); - + $db = new DbHandler(); $res = $db->createUser($name, $email, $password); - + if ($res == USER_CREATED_SUCCESSFULLY) { $response["error"] = false; $response["message"] = "You are successfully registered"; - echoRespnse(201, $response); } else if ($res == USER_CREATE_FAILED) { $response["error"] = true; $response["message"] = "Oops! An error occurred while registereing"; - echoRespnse(200, $response); } else if ($res == USER_ALREADY_EXISTED) { $response["error"] = true; $response["message"] = "Sorry, this email already existed"; - echoRespnse(200, $response); } + // echo json response + echoRespnse(201, $response); }); + /** * User Login * url - /login @@ -129,18 +108,18 @@ $app->post('/register', function() use ($app) { $app->post('/login', function() use ($app) { // check for required params verifyRequiredParams(array('email', 'password')); - + // reading post params $email = $app->request()->post('email'); $password = $app->request()->post('password'); $response = array(); - + $db = new DbHandler(); // check for correct email and password if ($db->checkLogin($email, $password)) { // get the user by email $user = $db->getUserByEmail($email); - + if ($user != NULL) { $response["error"] = false; $response['name'] = $user['name']; @@ -157,46 +136,216 @@ $app->post('/login', function() use ($app) { $response['error'] = true; $response['message'] = 'Login failed. Incorrect credentials'; } - + echoRespnse(200, $response); }); + +/* + * ------------------------ METHODS WITH AUTHENTICATION ------------------------ + */ + /** - * Adding Middle Layer to authenticate every request - * Checking if the request has valid api key in the 'Authorization' header + * Listing all tasks of particual user + * method GET + * url /tasks */ -function authenticate(\Slim\Route $route) { - // Getting request headers - $headers = apache_request_headers(); - $response = array(); - $app = \Slim\Slim::getInstance(); - - // Verifying Authorization Header - if (isset($headers['Authorization'])) { - $db = new DbHandler(); - - // get the api key - $api_key = $headers['Authorization']; - // validating api key - if (!$db->isValidApiKey($api_key)) { - // api key is not present in users table - $response["error"] = true; - $response["message"] = "Access Denied. Invalid Api key"; - echoRespnse(401, $response); - $app->stop(); - } else { +$app->get('/tasks', 'authenticate', function() { global $user_id; - // get user primary key id - $user = $db->getUserId($api_key); - if ($user != NULL) - $user_id = $user["id"]; + $response = array(); + $db = new DbHandler(); + + // fetching all user tasks + $result = $db->getAllUserTasks($user_id); + + $response["error"] = false; + $response["tasks"] = array(); + + // looping through result and preparing tasks array + while ($task = $result->fetch_assoc()) { + $tmp = array(); + $tmp["id"] = $task["id"]; + $tmp["task"] = $task["task"]; + $tmp["status"] = $task["status"]; + $tmp["createdAt"] = $task["created_at"]; + array_push($response["tasks"], $tmp); + } + + echoRespnse(200, $response); + }); + +/** + * Listing single task of particual user + * method GET + * url /tasks/:id + * Will return 404 if the task doesn't belongs to user + */ +$app->get('/tasks/:id', 'authenticate', function($task_id) { + global $user_id; + $response = array(); + $db = new DbHandler(); + + // fetch task + $result = $db->getTask($task_id, $user_id); + + if ($result != NULL) { + $response["error"] = false; + $response["id"] = $result["id"]; + $response["task"] = $result["task"]; + $response["status"] = $result["status"]; + $response["createdAt"] = $result["created_at"]; + echoRespnse(200, $response); + } else { + $response["error"] = true; + $response["message"] = "The requested resource doesn't exists"; + echoRespnse(404, $response); + } + }); + +/** + * Creating new task in db + * method POST + * params - name + * url - /tasks/ + */ +$app->post('/tasks', 'authenticate', function() use ($app) { + // check for required params + verifyRequiredParams(array('task')); + + $response = array(); + $task = $app->request->post('task'); + + global $user_id; + $db = new DbHandler(); + + // creating new task + $task_id = $db->createTask($user_id, $task); + + if ($task_id != NULL) { + $response["error"] = false; + $response["message"] = "Task created successfully"; + $response["task_id"] = $task_id; + echoRespnse(201, $response); + } else { + $response["error"] = true; + $response["message"] = "Failed to create task. Please try again"; + echoRespnse(200, $response); + } + }); + +/** + * Updating existing task + * method PUT + * params task, status + * url - /tasks/:id + */ +$app->put('/tasks/:id', 'authenticate', function($task_id) use($app) { + // check for required params + verifyRequiredParams(array('task', 'status')); + + global $user_id; + $task = $app->request->put('task'); + $status = $app->request->put('status'); + + $db = new DbHandler(); + $response = array(); + + // updating task + $result = $db->updateTask($user_id, $task_id, $task, $status); + if ($result) { + // task updated successfully + $response["error"] = false; + $response["message"] = "Task updated successfully"; + } else { + // task failed to update + $response["error"] = true; + $response["message"] = "Task failed to update. Please try again!"; + } + echoRespnse(200, $response); + }); + +/** + * Deleting task. Users can delete only their tasks + * method DELETE + * url /tasks + */ +$app->delete('/tasks/:id', 'authenticate', function($task_id) use($app) { + global $user_id; + + $db = new DbHandler(); + $response = array(); + $result = $db->deleteTask($user_id, $task_id); + if ($result) { + // task deleted successfully + $response["error"] = false; + $response["message"] = "Task deleted succesfully"; + } else { + // task failed to delete + $response["error"] = true; + $response["message"] = "Task failed to delete. Please try again!"; + } + echoRespnse(200, $response); + }); + +/** + * Verifying required params posted or not + */ +function verifyRequiredParams($required_fields) { + $error = false; + $error_fields = ""; + $request_params = array(); + $request_params = $_REQUEST; + // Handling PUT request params + if ($_SERVER['REQUEST_METHOD'] == 'PUT') { + $app = \Slim\Slim::getInstance(); + parse_str($app->request()->getBody(), $request_params); + } + foreach ($required_fields as $field) { + if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) { + $error = true; + $error_fields .= $field . ', '; } - } else { - // api key is missing in header + } + + if ($error) { + // Required field(s) are missing or empty + // echo error json and stop the app + $response = array(); + $app = \Slim\Slim::getInstance(); $response["error"] = true; - $response["message"] = "Api key is misssing"; + $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty'; echoRespnse(400, $response); $app->stop(); } -$app->run(); } + +/** + * Validating email address + */ +function validateEmail($email) { + $app = \Slim\Slim::getInstance(); + if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { + $response["error"] = true; + $response["message"] = 'Email address is not valid'; + echoRespnse(400, $response); + $app->stop(); + } +} + +/** + * Echoing json response to client + * @param String $status_code Http response code + * @param Int $response Json response + */ +function echoRespnse($status_code, $response) { + $app = \Slim\Slim::getInstance(); + // Http response code + $app->status($status_code); + + // setting response content type to json + $app->contentType('application/json'); + + echo json_encode($response); +} + +$app->run(); ?> \ No newline at end of file