Welcome Guest, Not a member yet? Register   Sign In
Multiple filter to group route
#1

Hi can i add multiple filter for a route group ?

this is my groupe :

Code:
$routes->options('consensi/:any', 'Consensi::index');
$routes->group('consensi', ['filter' => 'centriFiltersAuth'], function($routes) {
    $routes->add('inserisciRecord', 'Consensi::inserisciRecord');
    $routes->add('eliminaRecord/(:num)', 'Consensi::eliminaRecord/$1');
    $routes->add('lista_completa', 'Consensi::lista_completa');

});


cen
centriFiltersAuth is a filter to control if the user is logged but i want control if value in a table are empty and redirect in this case . 

Can i do this ?
Reply
#2

(This post was last modified: 08-06-2021, 12:44 PM by paliz.)

to add  multipel filter you have to use service 
look add the code i add  multiple   and see

PHP Code:
<?php namespace Modules\Auth\Config;


use 
Config\Services as BaseService;
use 
Modules\Auth\Services\RuleRoute;

class 
Services extends BaseService
{


    public static function ruleRoute($getShared true)
    {
        if ($getShared) {
            return static::getSharedInstance('ruleRoute');
        }

        return new RuleRoute();
    }



PHP Code:
<?php

namespace Modules\Auth\Services;

class 
RuleRoute
{
    public static function getRuleAccess(string $name): ?array
    {
        $listOfRule = array(
            'profile' => null,
            'chatContact' => null,
            'chatRoom' => null,
            'chatRoomMedia' => null,
            'chatPrivate' => null,
            'chatPrivateMedia' => null,
            'dashboard' => null,
            'user' => ['admin'],
            'group' => ['admin'],
            'setting' => ['admin'],
            'visitor' => ['admin'],
            'advertisement' => ['admin'],
            'advertisementMedia' => ['admin'],
            'contact' => ['admin''coworker'],
            'contactMedia' => ['admin''coworker'],
            'newsCategory' => ['admin''coworker'],
            'newsSubCategory' => ['admin''coworker'],
            'newsPost' => ['admin''coworker'],
            'newsComment' => ['admin''coworker'],
            'newsMedia' => ['admin''coworker'],
            'viewOption' => ['admin''coworker'],
            'viewMedia' => ['admin''coworker'],
            'requestCategory' => ['admin''coworker'],
            'requestPost' => ['admin''coworker'],
            'requestReply' => ['admin''coworker'],
        );

        foreach ($listOfRule as $key => $value) {
            if ($key == $name) {
                return $value;
            }
        }
        return null;
    }

    public static function ignoreRoute():bool
    
{
        $listOfIgnore = array('home','msc''test''auth','payPal','zarinPal');

        foreach ($listOfIgnore as $item) {
            if (preg_match("~\b" $item "\b~"uri_string())) {
                return true;
            }
        }

        return false;
    }




PHP Code:
<?php namespace Modules\Auth\Filters;

use 
Modules\Shared\Enums\FilterErrorType;
use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\Response;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
CodeIgniter\Filters\FilterInterface;


class 
AuthFilter implements FilterInterface
{
    public function after(RequestInterface $requestResponseInterface $response$arguments null)
    {

    }

    public function before(RequestInterface $request$arguments null)
    {

        $ruleRoute = \Modules\Auth\Config\Services::ruleRoute();

        if ($ruleRoute->ignoreRoute()) {
            return;
        }
        $response = \CodeIgniter\Config\Services::response();

        $uri uri_string();

        $authenticate = \Myth\Auth\Config\Services::authentication();
        $authorize = \Myth\Auth\Config\Services::authorization();

        $explode explode('/'$uri);

        $controller strtolower($explode[1]);

        $controllerRule $ruleRoute->getRuleAccess(explode('/'$uri)[1]);

        $isGroup false;
        $isAccess false;
        $counterPermission 0;
        if (!function_exists('logged_in')) {
            //  helper('Myth\Auth\Helpers\Auth');
            helper('auth');
        }

        $current = (string)current_url(true)
            ->setHost('')
            ->setScheme('')
            ->stripQuery('token');

        // Make sure this isn't already a login route
        if (in_array((string)$current, [route_to('login'), route_to('forgot'), route_to('reset-password'), route_to('register'), route_to('activate-account')])) {

            return;
        }

        // if no user is logged in then send to the login form

        if (!$authenticate->check()) {
            return $response->setJSON(['success' => false,
                'type' => FilterErrorType::Login,
                'error' => lang('Authenticate.filter.login')])->setContentType('application/json')
                ->setStatusCode(Response::HTTP_UNAUTHORIZEDlang('Authenticate.filter.login'));
        }


        if (empty($controllerRule)) {

            return;
        }

        // Check each requested permission
        foreach ($controllerRule as $group) {
            if ($authorize->inGroup($group$authenticate->id())) {
                $isGroup true;
                // return;
            }
        }


        $method strtolower($_SERVER['REQUEST_METHOD']);
        // permission by http request post put delete
        $permissions permissionMethod($method);

        if ($isGroup == true && !empty($permissions)) {

            foreach ($permissions as $item) {

                if ($authorize->permission($controller "" $item)) {
                    $counterPermission++;
                    if ($authorize->hasPermission($controller "" $item$authenticate->id())) {
                        $isAccess true;
                        break;
                    }
                }

            }
        }
        // it get request  dont need any permission
        //or dont have permission in database for http request
        if (empty($permissions) || $counterPermission == 0) {


            $isAccess true;
        }


        if ($isGroup == true and $isAccess == true) {
            return;
        }


        if ($authenticate->silent()) {
            $redirectURL session('redirect_url') ?? '/';
            unset($_SESSION['redirect_url']);
        }

        return $response->setJSON(['success' => false,
            'type' => FilterErrorType::Permission,
            'error' => lang('Auth.notEnoughPrivilege')])->setContentType('application/json')
            ->setStatusCode(Response::HTTP_UNAUTHORIZEDlang('Auth.notEnoughPrivilege'));


    }




PHP Code:
<?php namespace Modules\Auth\Filters;

use 
Modules\Shared\Enums\FilterErrorType;
use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\Response;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
CodeIgniter\Filters\FilterInterface;
use 
CodeIgniter\Config\Services;


class  JwtFilter implements FilterInterface
{

    public function before(RequestInterface $request$arguments null)
    {

        $authHeader $request->getServer('HTTP_AUTHORIZATION');

        $ruleRoute = \Modules\Auth\Config\Services::ruleRoute();
        if ($ruleRoute->ignoreRoute()) {
            return;
        }

        helper('jwt');
        try {
            $token isJWT($authHeader);

            $authConfig new  \Modules\Auth\Config\ModuleAuthConfig();
            validateJWT($token$authConfig->jwtSecertKey);

        } catch (\Exception $e) {


            return Services::response()->setJSON(['success' => false,
                'type' => FilterErrorType::Jwt,
                'error' => lang('Authenticate.filter.jwt')])->setContentType('application/json')
                ->setStatusCode(Response::HTTP_UNAUTHORIZEDlang('Authenticate.filter.jwt'));

        }
    }

    //--------------------------------------------------------------------

    public function after(RequestInterface $requestResponseInterface $response$arguments null)
    {
        // Do something here
    }

PHP Code:
<?php

namespace Config;

use 
CodeIgniter\Config\BaseConfig;
use 
CodeIgniter\Filters\CSRF;
use 
CodeIgniter\Filters\DebugToolbar;
use 
CodeIgniter\Filters\Honeypot;
use 
Modules\Auth\Filters\AuthFilter;
use 
Modules\Auth\Filters\CsrfFilter;
use 
Modules\Auth\Filters\JwtFilter;
use 
Modules\Auth\Filters\ThrottleFilter;
use 
Modules\Common\Filters\ContentNegotiationFilter;
use 
Modules\Common\Filters\CorsFilter;
use 
Modules\Common\Filters\UrlFilter;

class 
Filters extends BaseConfig
{
    /**
    * Configures aliases for Filter classes to
    * make reading things nicer and simpler.
    *
    * @var array
    */
    public $aliases = [
        //'csrf'    => CSRF::class,
        'toolbar' => DebugToolbar::class,
        'honeypot' => Honeypot::class,
        'csrf' => CsrfFilter::class,
        'cors' => CorsFilter::class,
        'auth' => AuthFilter::class,
        'jwt' => JwtFilter::class,
        'url' => UrlFilter::class,
        'throttle' => ThrottleFilter::class,
        'contentNegotiation' => ContentNegotiationFilter::class,

    ];

    /**
    * List of filter aliases that are always
    * applied before and after every request.
    *
    * @var array
    */
    public $globals = [
        'before' => [
            // 'honeypot',
            // 'csrf',
            // 'honeypot',
            // 'csrf',
            'cors',
            'url',
          // 'contentNegotiation'
            //  'csrf',
        ],
        'after' => [
            'toolbar',
            // 'honeypot',
            //  'csrf',
        ],
    ];

    /**
    * List of filter aliases that works on a
    * particular HTTP method (GET, POST, etc.).
    *
    * Example:
    * 'post' => ['csrf', 'throttle']
    *
    * @var array
    */
    public $methods = [

        //  'get' => ['csrf'],
        // 'post' => ['csrf'],
        // 'put' => ['csrf'],
        // 'delete' => ['csrf']

    ];

    /**
    * List of filter aliases that should run on any
    * before or after URI patterns.
    *
    * Example:
    * 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
    *
    * @var array
    */
    public $filters = [
        'auth' => ['before' => 'api*'],
        'jwt' => ['before' => 'api*',],

    ];


it has a 3 filter for dashboardCtl auth then jwt then csrf
Enlightenment  Is  Freedom
Reply




Theme © iAndrew 2016 - Forum software by © MyBB