Hi!
I’m new to Slim. I’ve started to learning and I would like to redirect to login page from middleware, but it not realy works. What’s wrong with my code?
Routing:
$app->group("/admin", function (RouteCollectorProxy $group){
$group->get("[/]", [dashboardController::class, "viewDashboard"]);
$group->get("/blog[/]", [blogController::class, "viewBlog"]);
$group->get("/login[/]", [userController::class, "viewlogin"]);
$group->post("/login/auth[/]", [userController::class, "authUser"]);
})->add(permissionMiddleware::class);
permissionMiddleware:
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Routing\RouteContext;
class permissionMiddleware
{
public function __invoke(Request $request, RequestHandler $handler)
{
$routeContext = RouteContext::fromRequest($request);
$route = $routeContext->getRoute();
$pattern = $route->getPattern();
var_dump($pattern);
//loging and login/auth are allowed without permission
if(preg_match("/^\/admin\/login\/?(\/auth\/?|$)/", $pattern)){
return $handler->handle($request);
}
//user has auth session
if(isset($_SESSION["user_auth"]))
return $handler->handle($request);
//no session and no login request redirect to admin/login
$response = $handler->handle($request);
return $response->withStatus(302)->withHeader('Location', '/nt-slim/admin/login');
}
}
I get this error in my browser: