Search code examples
.htaccessslimmiddlewareslim-3

SLIM 3 logn middleware enter in a loop


i have some problems with a SLIM 3 login middleware. In any route I try to go i receive this browser error: "ERR_TOO_MANY_REDIRECTS". It seems to be that SLIM entered a loop and could not render the login page. What can i do? I have obviously done the print_r of the session variables and of course it is initially empty and is only populated after the correct login..

This is my index php:

<?

use Slim\Views\PhpRenderer;

session_start();

define( "BASE_URL", "/test/");
define("ROOT_PATH", $_SERVER["DOCUMENT_ROOT"] . "/test/");

require 'vendor/autoload.php';
require 'config/db.php';
require('functions/middleware.php');

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;
$capsule->addConnection([
    'driver' => 'mysql',
    'host' => DB_HOST,
    'port' => DB_PORT,
    'database' => DB_NAME,
    'username' => DB_USER,
    'password' => DB_PASSWORD,
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
]);

$capsule->bootEloquent();
$capsule->setAsGlobal();

$config['displayErrorDetails'] = true;
$config['addContentLengthHeader'] = false;
$config['determineRouteBeforeAppMiddleware'] = true;

$app = new \Slim\App(['settings' => $config]);

$container = $app->getContainer();
$container['renderer'] = new PhpRenderer("./templates");
$container['notFoundHandler'] = function ($container) {
    return function ($request, $response) use ($container) {
        return $container['renderer']->render($response, "/404.php");
    };
};

// Apply the middleware to every request.
$app->add($loggedInMiddleware);

include 'routes.php';

$app->run();

And this is the middleware included file:

<?
// Check the user is logged in when necessary.
$loggedInMiddleware = function ($request, $response, $next) {

    $route = $request->getAttribute('route');
    $routeName = $route->getName();
    $groups = $route->getGroups();
    $methods = $route->getMethods();
    $arguments = $route->getArguments();

    # Define routes that user does not have to be logged in with. All other routes, the user
    # needs to be logged in with.
    $publicRoutesArray = array(
        'login',
        'logout'
    );

    if (!$_SESSION && !in_array($routeName, $publicRoutesArray)) {

        // redirect the user to the login page and do not proceed.
        $response =  $response->withRedirect('/test/login');

    } else {

        if ($routeName == "login")
            return $response->withRedirect('/test/dashboard');

        // Proceed as normal...
        $response = $next($request, $response);
    }

    return $response;
};

And these are GET and POST login routes:

$app->get('login', function ($request, $response, $args) {

        return $this->renderer->render($response, "/login.php", $args);

    })->setName('login');

$app->post('login', function ($request, $response, $args) {

    $res = [];

    if(!$_POST['username'] || !$_POST['password']) {
        $res['error'] = "Inserisci i campi richiesti per il LogIn";
        return $this->response->withJson($res);
    }

    $thisUser = \test\Model\users::select("users.*")
        ->where("username",$_POST['username'])
        ->where("password",MD5($_POST['password']))
        ->get();

    if (!$thisUser[0]){
        $res['error'] = "I dati inseriti non corrispondono a nessun utente";
        return $this->response->withJson($res);
    }

    $_SESSION['user']['id'] = $thisUser[0]['id'];
    $_SESSION['user']['username'] = $thisUser[0]['username'];
    $_SESSION['user']['role'] = $thisUser[0]['role'];
    $_SESSION['user']['name'] = $thisUser[0]['name'];
    $_SESSION['user']['profileImg'] = "https://www.media-rdc.com/medias/32d9119760683046ad0c1e2d7e50e009/p_50x50/stsm144.jpg";

    $res['success'] = true;

    return $this->response->withJson($res);

});

And finally this is my .htaccess:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

Solution

  • Well I've tried many things; I'm not sure if it is the right answer, but it solves the problem (at least on my end):

    I've modified your middelware to this:

    <?php
    function (\Slim\Http\Request $request, \Slim\Http\Response $response, $next) {
    
        $route = $request->getAttribute('route');
    
        if (empty($route)) {
            throw new \Slim\Exception\NotFoundException($request, $response);
        }
    
        $routeName = $route->getName();
    
        // Define routes that user does not have to be logged in with. All other routes, the user
        // needs to be logged in with.
        $publicRoutesArray = array(
            'login',
            'logout'
        );
    
        if ( empty($_SESSION['user']) && !in_array($routeName, $publicRoutesArray)) {
            // redirect the user to the login page and do not proceed.
            return $response->withRedirect('/test/login');
        }
    
        // Proceed as normal...
        return $next($request, $response);
    }
    ?>
    

    Also it seems that you have to include the test in the defined routes to work (or filter them out in .htaccess)

    <?php
    $app->get('/test/login', function ($request, $response, $args) {
    
        return $this->renderer->render($response, 'index.phtml', $args);
    
    })->setName('login');
    ?>
    

    I sincerely hope it helps