I am using the Slim Framework to create a stateless REST API. Before using this I created a SESSION on server side with session check on every page. But now, I don't know how to control it.
I have an api_key in my database for each user. After a user signin, I respond with a api_key and redirect the user to index.php. But the api_key is not retained. How can I pass the api_key to each page with Javascript? Reason being if someone wants data from my REST API, they have to send me an api_key and also if the user logged in before I don't want to show login page again.
Here is my REST API part:
$app->post('/userlogin', function() use ($app) {
verifyRequiredParams(array('email', 'password'));
$email = $app->request->post('email');
$password = $app->request->post('password');
$objUserRegLog = new UserRegistrationLogin;
$result = $objUserRegLog->getUserByEmailAndPassword($email, $password);
if (!$result) {
$response["error"] = true;
$response["message"] = "Error! Invalid e-mail address or password.";
} else {
$response["error"] = false;
$response["id"] = $result["id"];
$response["email"] = $result["email"];
$response["api_key"] = $result["api_key"];
}
echoResponse(200, $response);
});
$app->get('/students', 'authenticateStudent', function() use ($app) {
$objStd = new Students;
$result = $objCases->getAllStudents();
if (!$result) {
$response["error"] = true;
$response["error_msg"] = "An error occured.";
$status_code = 404;
} else {
$response["error"] = false;
$response["cases"] = $result;
$status_code = 200;
}
echoResponse($status_code, $response);
});
function authenticateStudent(\Slim\Route $route) {
$headers = apache_request_headers();
$response = array();
$app = \Slim\Slim::getInstance();
if (isset($headers['Authorization'])) {
$db = new DbOperation();
$api_key = $headers['Authorization'];
if (!$db->isValidStudent($api_key)) {
$response["error"] = true;
$response["message"] = "Access Denied. Invalid Api key";
echoResponse(401, $response);
$app->stop();
}
} else {
$response["error"] = true;
$response["message"] = "Api key is misssing";
echoResponse(400, $response);
$app->stop();
}
}
And the call with AJAX :
$.signin = function() {
var inputVals = $("#form_signin").serialize();
$.ajax({
url : "api/v1/userlogin",
data : inputVals,
dataType : "json",
type : "post",
success : function(response) {
if (response.error) {
$(".popup").trigger("click");
$(".modal-title").html(response.message_title);
$(".modal-body").html(response.message);
} else {
window.location.href = "index.php";
}
console.log(response);
}
});
return false;
}