Presenter redirect in onError function of application

about a year ago

Bejn
Member | 13
+
0
-

Hello,

I am trying to globaly handle \Nette\ForbiddenRequestException. I need to make a redirect to Sign:in with a flash message. I tried it in Static function called from $application->onError, but it throws BadRequestException.

Is it possible to make a redirect in function called from $application->onError? Do you know a better solution for this?

Last edited by Bejn (2013-11-04 07:58)

about a year ago

Bejn
Member | 13
+
0
-

It is nonesense. It just occurred to me, ForbiddenRequest can be and mostly is for insufficient rights, so the user can be logged in. Never mind :-)

about a year ago

Bejn
Member | 13
+
0
-

But I can stil check if the error is because the user is not logged in. Something like this:

<?php

class Common {

    public static function redirectForbidden(\Nette\Application\Application $application, \Exception $e) {

        if ( $e instanceof \Nette\Application\ForbiddenRequestException ) {
            $presenter = $application->getPresenter();

            if ( $presenter->user->isLoggedIn() ) {
                throw $e;
            }

            $presenter->flashMessage('For access you need to log in');
            $presenter->redirect( 'Sign:in' );

        }

    }

}

about a year ago

Quinix
Member | 92
+
0
-

How about handling it in overridden function checkRequirments?

class SecuredPresenter extends BasePresenter {

    public function checkRequirements($element) {
        try {
            parent::checkRequirements($element);
        } catch (Application\ForbiddenRequestException $e) {
            $this->storeRequest();
            $this->flashMessage('You need to log in.');
            $this->redirect('Sign:in');
        }
    }
}

about a year ago

Bejn
Member | 13
+
0
-

Quinix wrote:

How about handling it in overridden function checkRequirments?

class SecuredPresenter extends BasePresenter {

    public function checkRequirements($element) {
        try {
            parent::checkRequirements($element);
        } catch (Application\ForbiddenRequestException $e) {
            $this->storeRequest();
            $this->flashMessage('You need to log in.');
            $this->redirect('Sign:in');
        }
    }
}

Thank you, I didn't know about this cool function. My current solution:

public function checkRequirements($element) {

    if ( $element->name !== 'AdminModule\\SignPresenter' &&
         strpos( $element->name, 'AdminModule\\') !== FALSE &&
         !$this->user->isLoggedIn() )
    {
        $this->backlink = $this->storeRequest();
        $this->flashMessage('You need to log in.');
        $this->redirect(':Admin:Sign:in');
    }

    return parent::checkRequirements($element);
}

Board footer

Nette Tracy Latte Tester Login Register Česká verze