Hey SlimPeople,
I’m fairly new new to PHP/Slim.
I’ve got pretty much everything going the way I want. Except for one thing I can’t wrap my brain around.
Middleware…
I’ve managed to get the routing middleware to work the way I want… YEAH!
Now I’d like to block the whole execution from happening on routes the logged in user doesn’t have access to.
I’m able to change the response’s status code
$response = $handler->handle($request);
if(SOME_CONDITION) {
$response = $response->withStatus(403);//Forbidden
}return $response;
The trouble is I’m still running and returning the forbidden data.
So I tried:
if(!$path_is_not_protected && !$session && !$is_option) { $response = new ResponseInterface(); $response = $response->withStatus(403);//Forbidden return $response; }
$response = $handler->handle($request);
return $response;
But I get the following error (using Postman for simplicity)
Details
Type: Error
Code: 0
Message: Cannot instantiate interface Psr\Http\Message\ResponseInterface
File: /var/www/src/Middleware/Auth.php
Line: 51
Here’s the complete Auth.php file
<?php
namespace App\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Routing\RouteContext;
/**
* CORS middleware.
*/
final class Auth implements MiddlewareInterface
{
/**
* Invoke middleware.
*
* @param ServerRequestInterface $request The request
* @param RequestHandlerInterface $handler The handler
*
* @return ResponseInterface The response
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
$request_path = $request->getUri()->getPath();
$unprotected_paths = [
'/users/login',
'/access/request',
];
$admin_only_paths = [
'/users/login',
'/access/request',
];
$clinician_only_paths = [
'/users/login',
'/access/request',
];
$path_is_not_protected = in_array($request_path, $unprotected_paths);
$qrit_auth = $request->getHeaders()['QRIT-AUTH'][0] ?? '';
session_start();
$_SESSION['UUID'] = $qrit_auth;
$_SESSION['USER_ROLE'] = 'unknown';
$has_qrit_auth = ($qrit_auth != '');
$is_option = ($request->getMethod() == 'OPTIONS');
if(!$path_is_not_protected && !$session && !$is_option) {
$response = new ResponseInterface();
$response = $response->withStatus(403);//Forbidden
return $response;
}
$response = $handler->handle($request);
return $response;
}
private function retrieve_session(string $uuid) {
$query = $this->queryFactory->newSelect('sessions');
$query->select('*');
$query->andWhere(['uuid' => $uuid]);
return $query->execute()->fetch('assoc');
}
}