codeigniterfiltercodeigniter-4php-8.1route-parameters

User redirection issue on login page in CodeIgniter 4.5


I am a beginner in programming and I am using CodeIgniter v4.5 to create a user management system. I cannot redirect users who try to access my app dashboard without logging in to the login form. I tried to protect my routes using many methods, but it always displays the same message when trying to access the dashboard or the user profile page without going through the Login form: "TypeError: str_contains(): Argument #1 ($haystack) must be of type string, null given"

I created the filters that should protect the routes to be able to redirect users to the login page. first, I created the AuthFilter.php file in the app\Filters folder, here are the contents:

// AuthFilter.php
<?php 

namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;

class AuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {

            if (!session()->has('loggedInUser')) {
               return redirect()->to('auth/login')->with('fail', 'You must be logged in, To access this page.');
            }
            
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Après le filtre
    }
}

secondly, I configured the filter file which is located in app/config, like this:

public array $aliases = [ 'auth' => \App\Filters\AuthFilter::class, ]; finally, I configured the routes like this:

<?php

namespace Config;

use CodeIgniter\Router\RouteCollection;

/**
 * @var RouteCollection $routes 
 */
//$routes->get('/', 'Home::index');

$routes->group('auth', function(RouteCollection $routes) {
    $routes->match(['get', 'post'], 'login', 'Auth::login');
    $routes->match(['get', 'post'], 'register', 'Auth::register');
    $routes->match(['get', 'post'], 'register/registerUser', 'Auth::registerUser');
    $routes->match(['get', 'post'], 'login/loginUser', 'Auth::loginUser');
    $routes->get('logout', 'Auth::logout');
});


// Logged in profil user
$routes->group('users', ['filter' => 'auth'], function(RouteCollection $routes) {
    $routes->get('profil', 'Profil::profilUtilisateur');
});

// Logged in dashboard
$routes->group('', ['filter' => 'auth'], function(RouteCollection $routes) {
    $routes->get('/Home', 'Home::index');
});

but it still shows this message: "TypeError str_contains(): Argument #1 ($haystack) must be of type string, null given "

How could you help me please?


Solution

  • good evening everyone, I would like to let you know that my problem is resolved. The problem is in codeigniter 4.5.0, there was definitely a bug, I downloaded version 4.5.1 and everything is fixed.

    https://forum.codeigniter.com/showthread.php?tid=90644

    https://github.com/codeigniter4/CodeIgniter4/issues/8730

    Thanks you!