Restricting Routes or controllers for auth status #257
|
So I'm still very new to MVC and CI/Shield, working on my first project on it. How do I go about restricting or making sure people can't access areas they're not authorized for? In my layout file I've figured out how to use loggedIn and can to control the loggedIn and authorized areas in the view/layout: helper("auth");
$user = auth()->user();
if (auth()->loggedIn()) {
...
if($user->can("airports.admin")) {How do I ensure if somehow they access it? Do I try a filter on a route? From the way I read the filter code, all it does is check if loggedIn, not if they can access an area, or do I daisy chain a filter with a can access function in the route, or do I write it in the controller? |
Replies: 3 comments 13 replies
|
Yeah, it sounds like a PermissionFilter would be handy to bring across. Looks like the initial port missed that and it's a good feature. |
|
The example is here.
$routes->get('/admin/airports', 'Admin::airports', ['filter' => 'permission:admin.airports']);
<?php
namespace Shield\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use Shield\Exceptions\PermissionException;
class PermissionFilter implements FilterInterface
{
public function before(RequestInterface $request, $params = null)
{
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) {
throw new PermissionException(lang('Auth.notEnoughPrivilege'));
}
}
// ------------------------------------------------------------------------
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Do nothing
}
} |
The example is here.
App\Config\Routes.phpApp\Filters\PermissionFilter.php