Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Redirect does not work in Event handler / listener

I have a Auth.Attempt event handler class, which I detect user's login attempts to decide to lock user's account. However, when I tried to redirect user to login page with a flash message, I found the redirection does not work, it's still carry on next step. I want to interrupt the process in the event and give my custom warning message. Can anyone help me out? Thanks a lot.

My event handler:

namespace MyApp\Handlers\Security;

use DB;
use Session;
use Redirect;

class LoginHandler 
{
    /**
     * Maximum attempts
     * If user tries to login but failed more than this number, User account will be locked
     * 
     * @var integer
     */
    private $max_attemtps;

    /**
     * Maximum attempts per IP
     * If an IP / Device tries to login but failed more than this number, the IP will be blocked
     * 
     * @var integer
     */
    private $ip_max_attempts;

    public function __construct()
    {
        $this->max_attempts = 10;
        $this->ip_max_attempts = 5;
    }

    public function onLoginAttempt($data)
    {
        //detection process.......
        // if login attempts more than max attempts
        return Redirect::to('/')->with('message', 'Your account has been locked.');
    }
}

Now the way I am doing this is like below:

Session::flash('message', 'Your account has been locked.');
header('Location: '.URL::to('/'));

It works but I am not sure if it's perfect way to do it.

like image 551
Jonathan Avatar asked Jan 12 '23 20:01

Jonathan


2 Answers

You can still send an HttpException who will work. But obviously instructions after the event handler will not be interpreted

abort(redirect('/'));
like image 57
Léonard Avatar answered Jan 17 '23 17:01

Léonard


Not getting to much into this very interesting discussion:

Should exceptions be used for flow control

You can try setting up your own exception handler and redirect from there on to the login page.

class FancyException extends Exception {}

App::error(function(FancyException $e, $code, $fromConsole)
{
    $msg = $e->getMessage();        
    Log::error($msg);

    if ( $fromConsole )
    {
        return 'Error '.$code.': '.$msg."\n";
    }

    if (Config::get('app.debug') == false) {
        return Redirect::route('your.login.route');
    }
    else
    {
        //some debug stuff here
    }


});

And in your function:

public function onLoginAttempt($data)
{
    //detection process.......
    // if login attempts more than max attempts
    throw new FancyException("some msg here");
}
like image 23
Gadoma Avatar answered Jan 17 '23 18:01

Gadoma