CodeIgniter Forums
Filter's dont work - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forum-28.html)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forum-30.html)
+--- Thread: Filter's dont work (/thread-78095.html)

Pages: 1 2


Filter's dont work - pippuccio76 - 11-29-2020

HI , i try to implement a filter to control if admin is authenticated :

Code:
<?php namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;

class AdminFiltersAuth implements FilterInterface
{
    /**
     * Do whatever processing this filter needs to do.
     * By default it should not return anything during
     * normal execution. However, when an abnormal state
     * is found, it should return an instance of
     * CodeIgniter\HTTP\Response. If it does, script
     * execution will end and that Response will be
     * sent back to the client, allowing for error pages,
     * redirects, etc.
     *
     * @param \CodeIgniter\HTTP\RequestInterface $request
     * @param array|null                         $params
     *
     * @return mixed
     */
    public function before(RequestInterface $request, $params = null)
    {
        // if no user is logged in then send them to the login form
        if (!session()->get('admin_id'))
        {           
            session()->set('redirect_url', current_url());
           
            return redirect()->to( base_url().'/admin/login');
        }
    }

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

    /**
     * Allows After filters to inspect and modify the response
     * object as needed. This method does not allow any way
     * to stop execution of other after filters, short of
     * throwing an Exception or Error.
     *
     * @param \CodeIgniter\HTTP\RequestInterface  $request
     * @param \CodeIgniter\HTTP\ResponseInterface $response
     * @param array|null                          $arguments
     *
     * @return void
     */
    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {

    }

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

}   // End of YourFilterName Class.


i want filter every controller's method except login to prevent loop redirect

in Config/Filter this is my code:

Code:
<?php namespace Config;

use CodeIgniter\Config\BaseConfig;

class Filters extends BaseConfig
{
    // Makes reading things below nicer,
    // and simpler to change out script that's used.
    public $aliases = [
        'csrf'     => \CodeIgniter\Filters\CSRF::class,
        'toolbar'  => \CodeIgniter\Filters\DebugToolbar::class,
        'honeypot' => \CodeIgniter\Filters\Honeypot::class,
        'adminFiltersAuth' => \App\Filters\AdminFiltersAuth::class,
        'adminFiltersNoAuth' => \App\Filters\AdminFiltersNoAuth::class,
        'showSessionFilter' => \App\Filters\ShowSessionFilter::class,
    ];

    // Always applied before every request
    public $globals = [
        'before' => [
            //'showSessionFilter'
            //'honeypot'
            // 'csrf',
        ],
        'after'  => [
            'toolbar',
            //'honeypot'
        ],
    ];

    // Works on all of a particular HTTP method
    // (GET, POST, etc) as BEFORE filters only
    //     like: 'post' => ['CSRF', 'throttle'],
    public $methods = [];

    // List filter aliases and any before/after uri patterns
    // that they should run on, like:
    //    'isLoggedIn' => ['before' => ['account/*', 'profiles/*']],
    public $filters = [

        'adminFiltersAuth' => ['before' => ['admin/*'] ],
        'adminFiltersAuth' => ['except' => ['admin/login']],
        'adminFiltersNoAuth' => ['before' => ['admin/login']],



    ];
}

but if i go to ade admin/changeEmail if the admin are not logged in mut im not redirected . 
in route if i insert this code :

Code:
$routes->add('admin/changeEmail', 'Admin::changeEmail',['filter'=>'adminFiltersAuth']);

it works fine  but in some controller i want to filter every method and is too boring write a route with filter for every metods
Why ?


RE: Filter's dont work - InsiteFX - 11-29-2020

If you setup your base_url correct then it already has the ending / slash on it.

PHP Code:
public function before(RequestInterface $request$params null)
{
    // if no user is logged in then send them to the login form
    if (!session('admin_id')
    {
        session()->set('redirect_url'current_url());

        return redirect()->to(base_url('admin/login'));
    }




RE: Filter's dont work - tgix - 11-29-2020

(11-29-2020, 02:18 AM)pippuccio76 Wrote: it works fine  but in some controller i want to filter every method and is too boring write a route with filter for every metods
Why ?
I agree, the routes file can easily become unwieldy and extensive.
Have you looked at the $routes->group() function https://codeigniter4.github.io/userguide/incoming/routing.html#grouping-routes which may reduce some typing at least?

Real-world example. In my case I went from this:
PHP Code:
// Routes for handling Companies
$routes->options('companies/(.+)''Options::index');
$routes->get('companies/proctors''Companies::proctors', ['filter' => 'bearer-auth:comp']);
$routes->get('companies/findusers''Companies::find_users_to_link', ['filter' => 'bearer-auth:comp']);
$routes->post('companies/link''Companies::post_link', ['filter' => 'bearer-auth:comp']);
$routes->post('companies/linkmanage''Companies::post_linkmanage', ['filter' => 'bearer-auth:comp']);
$routes->get('companies/(:segment)/employees''Companies::get_employees/$1', ['filter' => 'bearer-auth:comp']);
$routes->delete('companies/(:segment)/employees''Companies::delete_employees/$1', ['filter' => 'bearer-auth:comp']); 

To this:

PHP Code:
$routes->options('companies/(.+)''Options::index');
$routes->group('companies', ['filter' => 'bearer-auth:comp'], function($routes) {
    $routes->get('proctors''Companies::proctors');
    $routes->get('findusers''Companies::find_users_to_link');
    $routes->post('link''Companies::post_link');
    $routes->post('linkmanage''Companies::post_linkmanage');
    $routes->get('(:segment)/employees''Companies::get_employees/$1');
    $routes->delete('(:segment)/employees''Companies::delete_employees/$1');
});
$routes->resource('companies', ['controller' => 'Companies''filter' => 'bearer-auth:comp']); 

A bit more readable I think and also reduces the risk of typos.


RE: Filter's dont work - pippuccio76 - 11-30-2020

(11-29-2020, 01:25 PM)InsiteFX Wrote: If you setup your base_url correct then it already has the ending / slash on it.

PHP Code:
public function before(RequestInterface $request$params null)
{
    // if no user is logged in then send them to the login form
    if (!session('admin_id')
    {
        session()->set('redirect_url'current_url());

        return redirect()->to(base_url('admin/login'));
    }

If i dont use slash im redirecting to www.mywebsite.com/admin/admin/login with a 404...


RE: Filter's dont work - InsiteFX - 12-01-2020

www.mywebsite.com/admin/admin/login

Your showing two admin is admin a sub-folder? If so you need to also pass that in the route.

Show us your folder dump.


RE: Filter's dont work - pippuccio76 - 12-02-2020

(12-01-2020, 01:49 PM)InsiteFX Wrote: www.mywebsite.com/admin/admin/login

Your showing two admin is admin a sub-folder? If so you need to also pass that in the route.

Show us your folder dump.

This is my folder in / there are :

-assets
-codeigniter
-file index.php

in codeigniter there are :
-app
-system
-vendor
-writeble
-file .env

In the index.php file :

$pathsPath = realpath(FCPATH . 'codeigniter/app/Config/Paths.php');

This is the row in .env :

app.baseURL = 'https://rxxxxxxxxxxxxxxxxx.it/'


RE: Filter's dont work - Matleyx - 12-02-2020

OFF TOPIC
Toh... un altro italiano che "litiga" con ci4!!!!!!!

Ciao PIPPUCCIO


RE: Filter's dont work - pippuccio76 - 12-02-2020

(12-02-2020, 09:06 AM)Matleyx Wrote: OFF TOPIC
Toh... un altro italiano che "litiga" con ci4!!!!!!!

Ciao PIPPUCCIO
Buonasera ...


RE: Filter's dont work - pippuccio76 - 12-03-2020

PHP Code:
$routes->options('companies/(.+)''Options::index');
$routes->group('companies', ['filter' => 'bearer-auth:comp'], function($routes) {
    $routes->get('proctors''Companies::proctors');
    $routes->get('findusers''Companies::find_users_to_link');
    $routes->post('link''Companies::post_link');
    $routes->post('linkmanage''Companies::post_linkmanage');
    $routes->get('(:segment)/employees''Companies::get_employees/$1');
    $routes->delete('(:segment)/employees''Companies::delete_employees/$1');
});
$routes->resource('companies', ['controller' => 'Companies''filter' => 'bearer-auth:comp']); 
Can you explain the first and last row ?


RE: Filter's dont work - tgix - 12-03-2020

First line sets up a catch-all for OPTIONS pre-flight requests to companies/ (could probably use (:any) instead of (.+) )

The last line is a convenient function to set up RESTful methods (get, update, create etc...) for companies (see https://codeigniter4.github.io/userguide/incoming/restful.html#resource-routes)