YII学习笔记之登陆验证

yii登陆身份验证

步骤:

1.使用yiic生成yii项目,具体方法:去掉main.php中gii模块的注释,修改密码;

2.准备登陆使用的数据库表,这里使用test_user表;

3.使用gii生成表对应的model以及表的CRUD操作;

4.CUserIdentity是yii非常重要的组件,会被自动加载,修改.../components/UserIdentity.php的验证方式:

public function authenticate()
	{
		$username = strtolower($this->username);
		$user = User::model()->find('LOWER(username)=?',array($username));
		if ($user == null){
			$this->errorCode = self::ERROR_USERNAME_INVALID;
		}else if (!$user->validatePassword($this->password)){//validatePassword method
			$this->errorCode = self::ERROR_PASSWORD_INVALID;
		}else{
			$this->_id = $user->id;
			$this->username = $user->username;
			$this->errorCode = self::ERROR_NONE;
		}
		return $this->errorCode == self::ERROR_NONE;
		
	}

通常,还会重写getId方法,这样做,在代码的任何位置使用yii::app()->user访问到;

5.增加表对应model的validatePassword方法,可使用yii内置的CPasswordHelper,方式如下:

public function validatePassword($password)
	{
		return CPasswordHelper::verifyPassword($password,$this->password);
	}
	public function hashPassword($password)
	{
		return CPasswordHelper::hashPassword($password);
	}

6.最后在处理登陆表单提交上来数据的控制器,增加两个方法调用:

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'),
		);
	}
public function authenticate($attribute,$params)
	{
		if(!$this->hasErrors())
		{
			$this->_identity=new UserIdentity($this->username,$this->password);
			if(!$this->_identity->authenticate())
				$this->addError('password','Incorrect username or password.');
		}
	}

7.验证登陆!

你可能感兴趣的:(yii,login,登陆验证)