Welcome Guest, Not a member yet? Register   Sign In
redirect()->to() doesn't work in controller __construct()
#1

Hi,

why redirect()->to() doesn't work in controller __construct()??

some options?

I need to put the redirect()->to() in the method

public function __construct()
    {
        helper('admin_auth');

        if(comprovacio_auth_usuari() == false)
        {
            return redirect()->to('/admin/login');
        }
    }

    public function dashboard()
    { 
        $session = session();
        $auth_user = $session->get('auth_user');

        $data['idioma'] = comprovacio_idioma_usuari();
        $data['auth_user'] = (object)$auth_user;
        $data['opc'] = OPC_DASHBOARD;

        echo view('admin/layouts/html_start', $data);
echo view('admin/layouts/head');
echo view('admin/layouts/body_start');
        echo view('admin/layouts/sidebar');
       
echo view('admin/pages/dashboard');

        echo view('admin/layouts/footer');
echo view('admin/layouts/html_end');
    }


thanks,

Andreu.
Reply
#2

It doesn’t work because it’s an actual return value from Controller methods, which isn’t received when called in the constructor. What you want are Filters - check them out in the User Guide.
Reply
#3

(This post was last modified: 11-27-2019, 09:57 AM by aparedesv.)

thanks!

I try filters...
Reply
#4

thanks MGatner,

I create a filter...

class AuthFilter implements FilterInterface
{
public function before(RequestInterface $request)
{
$session = session();
$auth_user = (object)$session->get('auth_user');

if(property_exists($auth_user, 'token') && property_exists($auth_user, 'usuari_id'))
{
$sessionUsuarisModel = new SessionUsuarisModel();

$user_session = $sessionUsuarisModel->where('token', $auth_user->token)->first();

if($auth_user->token <> $user_session->token || $auth_user->usuari_id <> $user_session->usuari_id)
{
return redirect()->to('/admin/login');
}
}
else
{
return redirect()->to('/admin/login');
}
}

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

public function after(RequestInterface $request, ResponseInterface $response)
{
// Do something here
}
}

And declare in config/filter
// Always applied before every request
public $globals = [
'before' => [
//'honeypot'
// 'csrf',
'authfilter' => ['except' => ['page/*', 'admin/login', 'admin/logout', 'admin/check-login']]
],
'after' => [
'toolbar',
//'honeypot'
],
];


it's oky!!

and a better than a helper declare in __construct(), because only declare one time!

thnaks
Reply
#5

So glad it worked! Thanks for the feedback.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB