2013-07-22 75 views
3

我有一个Auth.Attempt事件处理程序类,它检测用户的登录尝试以决定锁定用户的帐户。 但是,当我尝试将用户重定向到带有闪存消息的登录页面时,发现重定向不起作用,它仍在继续执行下一步。 我想中断事件中的过程并给出我的自定义警告消息。谁能帮我吗?非常感谢。Laravel Redirect在Event handler/listener中不起作用

我的事件处理程序:

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('/')); 

它的工作原理,但我不知道这是否是做完美的方式。

+0

为什么'使用重定向;'? –

+0

因为我不想处理认证。我尝试在验证用户名和密码之前验证用户登录尝试。如果用户的帐户被锁定或IP被阻止,则该过程将被终止并用闪光消息重定向到主页。 – Jonathan

+0

不,我的意思是'使用Redirect'这是一个有效的命名空间? –

回答

3

没有得到得多进入这个很有趣的讨论:

Should exceptions be used for flow control

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

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"); 
} 
+0

我用你的异常处理程序的方法,它很好用!感谢您指出这种优秀模式。 – CyberMonk

+0

谢谢,这帮了我。 –

相关问题