1

我正在使用该代码进行验证码:https ://github.com/solutudo/cakephp-captcha

这是我user_controller.php在登录操作中的代码:

    public function login() {
        if (!empty($this->data)
            && !empty($this->Auth->data['User']['username'])
            && !empty($this->Auth->data['User']['password'])) {
            // captcha code
            if ($this->RequestHandler->isPost()) {
                $this->User->setCaptcha($this->Captcha->getCode());
                $this->User->set($this->data);
                if ($this->User->validates()) {
                    // captcha code 
                    $user = $this->User->find('first', array(
                        'conditions' => array(
                            'User.email' => $this->Auth->data['User']['username'],
                            'User.password' => $this->Auth->data['User']['password']),
                        'recursive' => -1
                        ));
                    if (!empty($user) && $this->Auth->login($user)) {
                        if ($this->Auth->autoRedirect) {            
                            $this->redirect($this->Auth->redirect());
                        }
                    } else {
                        $this->Session->setFlash($this->Auth->loginError, $this->Auth->flashElement, array(), 'auth');
                    }
                }
            }
        }
    }

查看用户.ctp

    <?php
    echo $this->Form->create(array('action'=>'login'));
    echo $this->Form->input('username');
    echo $this->Form->input('password');
    // captcha code
    echo $this->Html->image('captcha.jpg', array('style' => 'padding: 0.5%;'));
    echo $this->Form->input('captcha');
    // captcha code
    echo $this->Form->end('Login');
    ?>

模型用户.php

    <?php
    class User extends AppModel {
        public $actsAs = array(
            'Captcha' => array(
                'field' => 'captcha',
                'error' => 'Captcha code entered invalid'
            )
        );
    }
    ?>

验证码验证和验证码不起作用,无需输入验证码我就可以登录,我在相同控制器的添加功能中使用了相同的代码user_controller.php,当时验证码正在工作。

我希望用户在输入正确的验证码后登录。

4

1 回答 1

0

通过阅读代码,您似乎必须在尝试验证之前生成验证码。我在您的代码中看不到您生成验证码的地方。也许您有一条指向/img/captcha.jpg生成函数的路线(如在文档中),但我在这里看不到。我也看不到您调用的任何地方CaptchaComponent::generate()实际上将验证码保存在会话中。

确保以下内容在您的routes.php文件中。

Router::connect('/img/captcha.jpg', array('action' => 'captcha'));

并将以下函数放入您的AppController.php文件中:

// auto-outputs an image
public function captcha()  {
    $this->autoRender = false;
    $this->Captcha->generate();
}

基本上,当您的图像被创建时,它实际上会路由到该函数,该函数创建代码并将其保存在会话中。用户点击提交,您的登录功能会尝试验证。如果无效,则呈现视图并取而代之的是新的验证码。

于 2012-10-08T15:26:09.143 回答