yii 登录表单验证

提交表单,处理表单controller


$model=new LoginForm;
if(isset($_POST['LoginForm']))
  {
   $model->attributes=$_POST['LoginForm'];
   if($model->validate() && $model->login())
    $this->redirect(Yii::app()->user->returnUrl);
  }
其中:


$model->validate() //验证表单
$model->login()    //验证用户




LoginForm model



class LoginForm extends CFormModel {

    public $username;
    public $password;
    public $rememberMe;
    private $_identity;
    public $verifyCode;
    public $valid_code;

    /**
     * Declares the validation rules.
     * The rules state that username and password are required,
     * and password needs to be authenticated.
     */
    public function rules() {
        return array(
            array('username, password', 'required'),
            array('rememberMe', 'boolean'),
            array('password', 'authenticate'),
            //array('verifyCode', 'captcha', 'allowEmpty' => !CCaptcha::checkRequirements()),
            array('verifyCode', 'captcha', 'allowEmpty' => $this->checkVerifyCode(), 'on' => 'index'),
            array("valid_code", 'check_valid_code', 'on' => 'login index'),
        );
    }

    /**
     * Authenticates the password.
     * This is the 'authenticate' validator as declared in rules().
     */
    public function authenticate($attribute, $params) {
        $this->_identity = new UserIdentity($this->username, $this->password);
        if (!$this->_identity->authenticate())
            $this->addError('password', '用户名或密码不正确.');
    }

    /**
     * Logs in the user using the given username and password in the model.
     * @return boolean whether login is successful
     */
    public function login() {
        if ($this->_identity === null) {
            $this->_identity = new UserIdentity($this->username, $this->password);
            $this->_identity->authenticate();
        }
        if ($this->_identity->errorCode === UserIdentity::ERROR_NONE) {
            $duration = $this->rememberMe ? 3600 * 24 * 30 : 0; // 30 days
            Yii::app()->user->login($this->_identity, $duration);
            return true;
        } else
            return false;
    }


在model中的验证:

Longin控制器中$model->validate()  在rules() 方法中的 password验证    array('password', 'authenticate'), 

authenticate   就是model里面的authenticate()方法

Login控制器中  $model->login()   指向model中的login() 方法

其中validate() 和 login() 方法都有如下代码:

$this->_identity = new UserIdentity($this->username, $this->password);
 $this->_identity->authenticate();
是获取LoginForm中$_identity变量

如果项目中存在UserIdentity文件 (protected\components\UserIdentity.php),登录验证时项目中的UserIdentity类会继承框架中的UserIdentity类

此处建议在项目中增加用户验证类,方便自定义登录时的业务逻辑

UserIdentity类参考:

class UserIdentity extends CUserIdentity {

    private $_id;

    /**
     * Authenticates a user.
     * @return boolean whether authentication succeeds.
     */
    public function authenticate() {
	$user = User::model()->find('LOWER(username)=?', array(strtolower($this->username)));
	if ($user === null)
	    $this->errorCode = self::ERROR_USERNAME_INVALID;
	else if (!$user->validatePassword($this->password))
	    $this->errorCode = self::ERROR_PASSWORD_INVALID;
	else {
	    $this->_id = $user->id;
	    $this->username = $user->username;

	    /*
	     * session
	     */
	    $this->setState('global_admin_id', $user->id);
	    $this->setState('global_admin_name', $user->username);
	    $this->setState('global_admin_role_type', $user->type);

	    /*
	     * 门店名称 ,余额
	     */
	    $tmp_shop = Shop::model()->model()->find("uid=:uid", array(":uid" => $user->id));
	    $this->setState('global_admin_shop_name', $tmp_shop['shop_name']);
            /**
             * 总店名称 
             */
            if($user->type == 3){
                $tmp_shop_m = Mainshop::model()->find("uid=:uid", array(":uid" => $user->id));
                  $this->setState('global_admin_shop_name', $tmp_shop_m['title']);
            }
	    $this->setState('global_shop_money', $user->money);

	    /*
	     * 登陆记录
	     */
	    $arr = array(
		'login_time' => time(),
		'login_ip' => Yii::app()->request->userHostAddress,
	    );
	    $user->saveAttributes($arr);
	    Yii::app()->session['login_error_times'] = null;

	    $this->errorCode = self::ERROR_NONE;
	}
	return $this->errorCode == self::ERROR_NONE;
    }

    /**
     * @return integer the ID of the user record
     */
    public function getId() {
	return $this->_id;
    }

}



你可能感兴趣的:(yii)