/** * Adding Middle Layer to authenticate every request * Checking if the request has valid api key in the 'Authorization' header */ 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']) && isset($headers['Token'])) { $db = new DbHandlerParse(); // get the api key $api_key = $headers['Authorization']; // get the session token $session_token = $headers['Token']; // validating api key if (!$db->isValidApiKey($api_key)) { // api key is not present in users table $response["result"] = "error"; $response["message"] = "Access Denied. Invalid Api key"; echoRespnse(401, $response); $app->stop(); } else { if (!$db->isValidSessionToken($session_token, $api_key)) { // session token does not match api key or is just invalid $response["result"] = "error"; $response["message"] = "Access Denied. Invalid Token"; echoRespnse(401, $response); $app->stop(); } else { global $user_id; // get user primary key id $userID = $db->getUserId($api_key); if (NULL != $userID) { $user_id = $userID; $_SESSION['userId'] = $user_id; } } } } else { if (!isset($headers['Authorization'])) { // api key is missing in header $response["result"] = "error"; $response["message"] = "Api key is misssing"; echoRespnse(400, $response); $app->stop(); } else { // token is missing in header $response["result"] = "error"; $response["message"] = "Token is misssing"; echoRespnse(400, $response); $app->stop(); } } }