When only some routes of app are protected, you might have to find a solution to redirect user after login
In my App, I managed things like this :
First create a filter named permissionFilter.php in directory App\Filters
PHP Code:
<?php
namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
class PermissionFilter implements FilterInterface
{
public function before(RequestInterface $request, $params = null)
{
$pathsegments = $request->getUri()->getSegments();
$path = implode("/", $pathsegments);
service('session')->set(['redirects' => $path]);
if (empty($params)) {
return;
}
if (!function_exists('auth')) {
helper('auth');
}
if (!auth()->loggedIn()) {
return redirect()->to('login');
}
$result = true;
foreach ($params as $permission) {
$result = $result && auth()->user()->can($permission);
}
if (!$result) {
service('session')->setFlashdata('warning',lang('Auth.notEnoughPrivilege'));
return redirect()->to('/');
}
return $result;
}
Then, in App\Config\Filters.php you have to set the filter so that the one of Shield doesnot fires first. Its done by using an alias
PHP Code:
<?php
namespace Config;
[...]
use App\Filters\PermissionFilter;
class Filters extends BaseConfig
{
/**
* Configures aliases for Filter classes to
* make reading things nicer and simpler.
*
* @var array<string, string>
* @phpstan-var array<string, class-string>
*/
public array $aliases = [
[...]
'perm' => PermissionFilter::class,
];
In App\Config\Auth.php modify Shield code to get the right route to redirect
PHP Code:
/**
* Returns the URL that a user should be redirected
* to after a successful login.
*/
public function loginRedirect(): string
{
$session = session();
if ($session->get('redirects') === NULL) $url = $session->getTempdata('beforeLoginUrl') ?? setting('Auth.redirects')['login'];
else {
$url = $session->get('redirects');
$session->remove('redirects');
}
return $this->getUrl($url);
}
And then App\Config\Route.php must use the right permissionFilter
PHP Code:
$routes->match(['get','post'],'personne/update/(:num)','Personne::update/$1', ['filter' => 'perm:users.edit']);
Maybe this code is not that beautiful, but hope it will help