Thursday, 18 December 2014

CAPTCHA in YII application

http://www.yiiframework.com/wiki/515/activate-captcha-after-unsuccessful-login-attempts/


First In LoginForm Model declare a public member as follows :

    public $verifyCode;

In the rules add the line 

public function rules()
    {
        return array(
            // username and password are required
            array('username, password', 'required'),
            // rememberMe needs to be a boolean
            array('rememberMe', 'boolean'),
            // password needs to be authenticated
            array('password', 'authenticate'),
            array('verifyCode', 'captcha', 'allowEmpty' => !CCaptcha::checkRequirements(), 'on' => 'withCaptcha'), //only on withCaptcha scenario
          );
    }

Now in Site Controller define action 'captcha'

    public function actions()
    {
        return array(
             'captcha'=>array(
                        'class'=>'CCaptchaAction',
                        'backColor'=>0xFFFFFF,
                    ), 
               'page'=>array(
                'class'=>'CViewAction',
            ),
        );
    }


then define/modify accessrules If not existing add the method, otherwise add the allow action captcha to all users

public function accessRules()
    {
        return array(
        array('allow',
            'actions'=>array('captcha'),
            'users'=>array('*'),
           ),
        );
    }

In the same SiteController:
add the below sentense in login action of sitecontroller
public function actionLogin()
{
                 .....
        $model->scenario = 'withCaptcha';
                ......
               ......
}
// If in the rules  'on' => 'withCaptcha is not given This statement is not necessary in login action.

Finally in the view login.php of site folder add the below code 

<?php  if ($model->scenario == 'withCaptcha' && CCaptcha::checkRequirements()): ?>
            <div class="row">
                <?php echo $form->labelEx($model, 'verifyCode'); ?>
                <div>
                  
            <?php $this->widget('CCaptcha', array('buttonOptions' => array('style' => 'display:block'))); ?>
                    <?php echo $form->textField($model, 'verifyCode'); ?>
                </div>
                <?php echo $form->error($model, 'verifyCode'); ?>
            </div>
        <?php  endif; ?>

the 'style' => 'display:block' makes the "get a new code" below the textbox.

and now check the application.

No comments:

Post a Comment