in codeigniter 4 there is a class name filter u can create class for authentication, u can read the documentation for more details.
this is the solution for your problem
- create file Auth.php inside App/Filters folder
<?php
namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
class Auth implements FilterInterface
{
public function before(RequestInterface $request)
{
if(session()->get('logged_in') !== true)
{
return redirect()->to('login');
}
}
//--------------------------------------------------------------------
public function after(RequestInterface $request, ResponseInterface $response)
{
// Do something here
}
}
- add your your new filter inside filters App/Config/Filters.php class to make it work
public $aliases = [
'csrf' => \CodeIgniter\Filters\CSRF::class,
'toolbar' => \CodeIgniter\Filters\DebugToolbar::class,
'honeypot' => \CodeIgniter\Filters\Honeypot::class,
'auth' => \App\Filters\Auth::class,
];
- in your Routes.php u can use that filter to spesify what route use run that filter before go to the route you want.
for single route
$routes->get('examplefunction', 'ControllerName::examplefunction', ['filter' => 'auth']);
for route group
$routes->group('', ['filter' => 'auth'], function ($routes) {
$routes->get('/', 'ControllerName::examplefunction');
$routes->get('examplefunction2', 'ControllerName::examplefunction2');
};
so that filter will executed before all single route inside the group run.
i hope this help you