I created a small middleware function for slim php framework that checks if the user is authenticated or not, like so.
function authenticate($app) {
return function() use ($app) {
if (!isset($_SESSION['user'])) {
$response = array();
array_push($response, array(
'error' => true,
'message' => 'You are not logged in.'
)
);
echoRes(403, $response);
}
};
}
What happens is that if I tried to insert it in a route like this:
$app->get('/', authenticate($app), function() use ($app){
echoRes(200, 'hello world!');
});
The echoRes
function
function echoRes($code, $response) {
$app = \Slim\Slim::getInstance();
$app->status($code);
$app->contentType('application/json');
echo json_encode($response);
}
What happens is that it will continue to give me a status code of 200
even when not authenticated, even I kill it using die()
;
function authenticate($app) {
return function() use ($app) {
if (!isset($_SESSION['user'])) {
$response = array();
array_push($response, array(
'error' => true,
'message' => 'You are not logged in.'
)
);
echoRes(403, $response);
die();
}
};
}
I use $app->notfound() or $app->halt(403) to halt execution. There is no need to set the status code as it is set by these functions.
If you happen to be using version 2.2.0 (I'm not sure if applicable in higher version) and also have to add JSON response after setting 403 response status, then you may use $app->stop()
. Using $app->halt(arg)
removes the contents of the body.