0

我正在使用核心 Auth 组件。我创建了一个管理所有权限的用户登录。我实现登录监控的方式是$this->Auth->user()在 app_controller 中进行检查。每次 app_controller 循环beforeFilter()函数和!$this->Auth->user()时,它都会增加Captcha.LoginAttempts会话变量。当Captcha.LoginAttempts大于 3 时,我希望它重定向到验证码控制器,显示验证码屏幕,要求用户确认他们是人。(类似于stackoverflow的做法)。

我遇到的问题是,如果我在某处使用某个元素或在页面上的 cake 框架中引用某些内容,它将命中重定向并导致每个访问元素/组件在实际控制器/操作外部被调用的无限循环重定向. 有没有更好的方法来实现这一点?

这是我一直在弄乱的实际代码。但它基本上很烂(IMO):

// this is in the app_controller beforeFilter() method.

if($this->Auth->user()) {
            $this->Session->delete('Captcha');
        } else {
            $this->Session->write('Captcha.LoginAttempts', $this->Session->read('Captcha.LoginAttempts') + 1);
            if ($this->Session->read('Captcha.LoginAttempts') > 3) {
                if (!$this->Session->read('Captcha.controller')) {
                    $this->Session->write('Captcha.controller', $this->params['controller']);
                    $this->Session->write('Captcha.action', $this->params['action']);
                }
                if ($this->Session->read('Captcha.fail') !== 'true') { // avoid circular reference redirects
                    $this->Session->write('Captcha.fail', 'true');
                    $this->redirect(array('controller' => 'captchas', 'action' => 'index'));
                }
            }
        }

您可以看到我如何尝试避免循环引用。但是随后用户可以直接进入登录页面,并且由于Captcha.fail会话变量已经设置,它将忽略重定向。必须有一种更优雅的方式来实现这一点。任何人?

4

1 回答 1

1

通常,我只会尝试回答您尝试这样做的方式,但由于您要求任何更好的想法,我要做的是在登录页面上实际使用验证码并使用 AuthComponents 内置方法和属性,如 loginRedirect,自动重定向和允许()。然后,只需根据 Captchas.loginAttempts 变量打开/关闭验证码。

对于您当前的方法,我认为您不会获得一种优雅的方式来执行此操作。但是,您也许可以更改 AuthComponent 的属性以获得您想要的。您可以更改 loginRedirect 和 loginAction 以便 /captchas/index 是新的登录表单,然后在成功验证码时,将 loginAction 设置回 /users/login 或其他。这样,如果有人试图直接点击 /users/login 而不进行验证码,那么 AuthComponent 逻辑就会启动并重定向到 /captchas/index。

以下是一些相关的手册页:

希望这可以帮助!

于 2010-08-17T15:26:56.040 回答