Yii框架应用程序整合Ucenter实现同步注册、登录和退出等
?
如今很多网站都要整合论坛程序,而康盛的Discuz系列产品往往是首选。然后就有了整合用户的需要,康盛提供了Ucenter架构,方便对不同的应用程序进行单点登录整合。
?
进来我尝试将ucenter整合到Yii网站中,获得了成功,虽然登录同步程序不是很妥当,基本使用没有问题了。我将继续改进。下面说说步骤:
?
继续修改 SiteController/actionLogout方法,实现同步退出:
进行到这里,我们已经实现了整合ucenter的登录和注册了,这样ucenter中有的用户,可以登录到yii应用,yii应用也可以注册用户到ucenter了。但是这还没有完成,我们需要的是在discuz中用户登录时,也同步登录yii应用,退出亦然,那么我们需要实现 Yii应用的 api/uc.php 这个接口程序。由于我们要用到Yii的框架资源,所以我没有采用硬编码的方式实现这个接口,而是创建了一个UcApplication类完成这个任务,继续往下看。首先建立 api/uc.php 入口文件,代码如下:
<?php/** * UserIdentity represents the data needed to identity a user. * It contains the authentication method that checks if the provided * data can identity the user. */class UcUserIdentity extends CUserIdentity{ public $id;/** * Constructor. * @param string $username username */public function __construct($username){$this->username=$username;$this->password='';}/** * Authenticates a user. * The example implementation makes sure if the username and password * are both 'demo'. * In practical applications, this should be changed to authenticate * against some persistent user identity storage (e.g. database). * @return boolean whether authentication succeeds. */public function authenticate(){$user = user::model()->findByAttributes(array('username'=>$this->username));if($user == null)//说明网站数据库中没有,而ucenter中有这个用户,添加用户{//ucenterYii::import('application.vendors.*');include_once 'ucenter.php';list($uid, $username, $email) = uc_get_user($this->username);if($uid){$user = new user;$user->username = $username;$user->password = md5(rand(10000,99999));$user->email = $email;$user->id = $uid;$user->save();$user->refresh();}} $this->id = $user->id; $user->last_login_time = $user->this_login_time; $user->this_login_time = time(); $user->last_login_ip = $user->this_login_ip; $user->this_login_ip = Yii::app()->getRequest()->userHostAddress; $user->save(); $this->errorCode=self::ERROR_NONE;return !$this->errorCode;} public function getId(){return $this->id;}}
可以看到,在这个认证类中,实现了对yii应用中没有的用户的建立操作。然后不需要对yii应用做任何特殊设置,就可以实现api接口了。然后我们在ucenter中添加yii应用的设置,修改main.php中的相应设置,应该就可以实现ucenter的同步登录、注册、退出、删除用户、修改用户名等等功能了!这个实现方法相对很Yii,呵呵。
有什么问题,欢迎评论,和我联系。大家一起进步吧!
?
PS: 需要注意的是,整合了ucenter的Yii应用在部署时,需将 protected/vendors/uc_client/data/及其子目录、文件设为可写。否则将会有些奇怪的问题。
1 楼 eric68 2011-12-13 你好,我的开发环境是windows xp+apache+mysql, 按照你的博客连接ucenter不成功,运行yii。返回一个php错误,