Thanks for your clues !
I succeeded by changing two three things. I'm not sure that the best way to do it but it works.
I've loaded "response" as a service. Can't succeeded to make it works with "redirectResponse".
Instead of creating a new function in baseController I choose to create a library GAuthLib.
If the specialists can give me an opinion. I will be very grateful.
My baseController :
Code:
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\RedirectResponse;
use Psr\Log\LoggerInterface;
/**
* Class BaseController
*
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
* Extend this class in any new controllers:
* class Home extends BaseController
*
* For security be sure to declare any new methods as protected or private.
*/
abstract class BaseController extends Controller
{
/**
* Instance of the main Request object.
*
* @var CLIRequest|IncomingRequest
*/
protected $request;
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* @var array
*/
protected $helpers = [];
/**
* Constructor.
*/
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
// Preload any models, libraries, etc, here.
$this->session = \Config\Services::session();
$this->authLib = new \App\Libraries\GAuthLib;
}
}
My auth library :
Code:
<?php
namespace App\Libraries;
class GAuthLib {
public function checkAccess(array $roles) {
$config = config('thisApp');
$response = \config\Services::response();
// No role : redirection
if (!isset($_SESSION[$config->appName]['user']['role'])) {
return redirect()->to(site_url('init/index'));
die("<p>No role defined.</p>");
}
// Got role. Check if controller accept this role.
else {
if (in_array($_SESSION[$config->appName]['user']['role'], $roles)) {
return TRUE;
} else {
return $response->redirect(site_url('home/index'))->send();
die("<p>No right ! Can't access.</p>");
}
}
}
}
And my test controller :
Code:
function testRole() {
$this->authLib->checkAccess(["dir"]); // Tests roles and redirect if not compatible.
echo "access granted";
}