提问者:小点点

Laravel重定向在事件处理程序/监听器中不工作


我有一本授权书。尝试事件处理程序类,我检测用户的登录尝试以决定锁定用户的帐户。然而,当我试图用一条闪光消息将用户重定向到登录页面时,我发现重定向不起作用,它仍然在进行下一步。我想在事件中中断进程,并给出自定义警告消息。有人能帮我吗?谢谢。

我的事件处理程序:

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.');
    }
}

现在我这样做的方式如下:

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

这是可行的,但我不确定这是否是一个完美的方法。


共2个答案

匿名用户

您仍然可以发送一个HttpExc0019谁将工作。但显然事件处理程序后的指令不会被解释

abort(redirect('/'));

匿名用户

没有太多关于这个非常有趣的讨论:

是否应将异常用于流量控制

您可以尝试设置自己的异常处理程序,并从那里重定向到登录页面。

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
    }


});

在你的职能中:

public function onLoginAttempt($data)
{
    //detection process.......
    // if login attempts more than max attempts
    throw new FancyException("some msg here");
}