【问题标题】:Laravel Redirect does not work in Event handler / listenerLaravel 重定向在事件处理程序/侦听器中不起作用
【发布时间】:2013-07-21 19:10:51
【问题描述】:

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

我的事件处理程序:

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

它有效,但我不确定它是否是完美的方法。

【问题讨论】:

  • 为什么是use Redirect;
  • 因为我不想处理身份验证。我尝试在验证用户名和密码之前验证用户登录尝试。如果用户账户被锁定或IP被阻止,进程将被终止并重定向到主页并显示一个flash消息。
  • 不,我的意思是 use Redirect 这是一个有效的命名空间吗?
  • 抱歉,我没有看到“突出显示”背景。是的。它实际上是在 app/config/app.php 中预定义的 Illuminate\Support\Facades\Redirect 的别名。我已经转储了 Redirect::to() 数据,它是正确的。但它只是不会在事件处理程序中重定向。我不知道如何使它工作。
  • 尝试通过放置两个标记进行调试,一个在重定向调用之前,一个在它之后,如果没有通过将其设置在顶部error_reporting(E_ALL); ini_set('display_errors', '1'); 来进行错误报告。

标签: laravel laravel-4 url-redirection


【解决方案1】:

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

abort(redirect('/'));

【讨论】:

  • 谢谢!就我而言,这可以完美地完成工作
【解决方案2】:

没有深入讨论这个非常有趣的讨论:

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

【讨论】:

  • 我使用了你的异常处理方法,效果很好!感谢您指出这种出色的模式。
  • 谢谢,这对我有帮助。
猜你喜欢
  • 1970-01-01
  • 2016-03-01
  • 2017-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-13
  • 1970-01-01
相关资源
最近更新 更多