我们的blog应用要区分系统用户和访客的不同身份。所以需要实现用户的验证部分。
或许你已经看到系统提供了一个用户验证,通过检查admin和demo的用户名密码。在这节中我们修改这段代码,让用户验证根据User表里的数据进行验证。
用户验证是由实现了IUserIdentity接口的的一个类来实现的。我们的应用架构中使用类UserIdentity来实现此目标.该文件存放在/wwwroot/blog/protected/components/UserIdentity.php。
约定class文件的名字必须和class的名字符合。也即是说类的名字加上".php"就是存放改类的文件的名字。按照这样的约定。我们可以引用一个class通过路径的别名。如:我们可以通过这样的别名application.components.UserIdentity使用UserIdentity类。多数的Yii APIs可以识别这样的别名(如 Yii::createComponent()),通过使用这样的别名来避免嵌入绝对的地址。后者往往在我们部署一个应用的时候带来麻烦。
我们如下修改用户验证的文件。
- <?php
- class UserIdentity extends CUserIdentity
- {
- private $_id;
- 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(md5($this->password)!==$user->password)
- $this->errorCode=self::ERROR_PASSWORD_INVALID;
- else
- {
- $this->_id=$user->id;
- $this->username=$user->username;
- $this->errorCode=self::ERROR_NONE;
- }
- return !$this->errorCode;
- }
- public function getId()
- {
- return $this->_id;
- }
- }
在 authenticate()方法中,我们User类来检查在数据表中是否存在该用户名,检查时通过转换为小写来不区分大小写。User类是在上一节中通过Yiic工具来实现的。因为User类是继承CActiveRecord。我们可以用oop的风格来扩展CActiveRecord和对User表的数据进行存取
在UserIdentity类中我们重写了getId()方法,用于返回在数据表中查找到得用户id,在其父类中返回的是用户名。用户名和id属性被保存到user session中,在程序的任何地方可以通过Yii::app()->user进行存取访问。
在用户验证的类中我们使用其他的类文没有明显的去加载他们,这是因为这些类是Yii framework提过的核心类,当他们第一次没使用的时候,Yii自动的加载他们。User类也可以这么直接使用,这是因为他存放在blog/protected/models 目录下。这些路径被添加到php的include_path中。因为在配置文件已经有了这样的设置。
return array(
......
'import'=>array(
'application.models.*',
'application.components.*',
),
......
);
以上配置表明任何在/wwwroot/blog/protected/models或/wwwroot/blog/protected/components下的类将会被自动加载。
return array(
......
'import'=>array(
'application.models.*',
'application.components.*',
),
......
);
以上配置表明任何在/wwwroot/blog/protected/models或/wwwroot/blog/protected/components下的类将会被自动加载。
UserIdentity类主要被LoginForm类使用,用来根据登陆页面输入的用户和密码验证用户。以下的代码片段显示UserIdentity是如何使用的。
- $identity=new UserIdentity($username,$password);
- $identity->authenticate();
- switch($identity->errorCode)
- {
- case UserIdentity::ERROR_NONE:
- Yii::app()->user->login($identity);
- break;
- ......
- }
人们经常会混淆了identity和user两个组件。前者实现了用户的验证,后者提供了当前用户的相关信息。一个应用只能有一个user组件,但是可以有一个或者多个验证类,取决于它支持的验证类型。一旦验证成功,一个identity 实例会把它的状态信息传递给user组(Once authenticated, an identity instance may pass its state information to the user component so that they are globally accessible via user)
再次打开网站http://www.example.com/blog/index.php便可以测试修改过的UserIdentity类。在此之前记得在数据里进行初始。系统没有提供用户管理模块,所以无法修改自己和的账户和没法添加新的账户。