現在不少網站都要整合論壇程序,而康盛的Discuz系列產品每每是首選。而後就有了整合用戶的須要,康盛提供了Ucenter架構,方便對不一樣的應用程序進行單點登陸整合。 javascript
進來我嘗試將ucenter整合到Yii網站中,得到了成功,雖然登陸同步程序不是很穩當,基本使用沒有問題了。我將繼續改進。下面說說步驟: php
- 下載安裝ucenter和discuz,我使用的是ucenter1.6和discuz7.2,因爲7.2自帶的uc_client是舊版本,因此須要覆蓋一下1.6版本。
- 複製一份uc_client文件夾到 protected/vendors/下,而後創建一個ucenter.php文件,內容以下:
Php代碼
- <?php
- include dirname(__FILE__).'/../config/main.php';
- include dirname(__FILE__).'/uc_client/client.php';
能夠看到這裏只是包含了兩個文件。而後打開yii的主配置文件 protected/config/main.php,加入ucenter的一些全局變量的設置:
Php代碼
- <?php
- define('UC_CONNECT', 'mysql'); // 鏈接 UCenter 的方式: mysql/NULL, 默認爲空時爲 fscoketopen()
- // mysql 是直接鏈接的數據庫, 爲了效率, 建議採用 mysql
- //數據庫相關 (mysql 鏈接時, 而且沒有設置 UC_DBLINK 時, 須要配置如下變量)
- define('UC_DBHOST', 'localhost'); // UCenter 數據庫主機
- define('UC_DBUSER', 'root'); // UCenter 數據庫用戶名
- define('UC_DBPW', ''); // UCenter 數據庫密碼
- define('UC_DBNAME', '027xfbbs'); // UCenter 數據庫名稱
- define('UC_DBCHARSET', 'utf8'); // UCenter 數據庫字符集
- define('UC_DBTABLEPRE', '027xfbbs.uc_'); // UCenter 數據庫表前綴
-
- //通訊相關
- define('UC_KEY', 'ebR4GhhpZB7e9Mhb'); // 與 UCenter 的通訊密鑰, 要與 UCenter 保持一致
- define('UC_API', 'http://027xf.test/ucenter'); // UCenter 的 URL 地址, 在調用頭像時依賴此常量
- define('UC_CHARSET', 'utf8'); // UCenter 的字符集
- define('UC_IP', ''); // UCenter 的 IP, 當 UC_CONNECT 爲非 mysql 方式時, 而且當前應用服務器解析域名有問題時, 請設置此值
- define('UC_APPID', 2); // 當前應用的 ID
-
- // uncomment the following to define a path alias
- // Yii::setPathOfAlias('local','path/to/local-folder');
-
- // This is the main Web application configuration. Any writable
- // CWebApplication properties can be configured here.
- return array(
- 'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
-
- .....
請根據你的狀況修改上面的數據庫名等設置。
- 實現同步註冊,我採用的是定義了表單RegisterForm來處理用戶的註冊,下面是一個典型的註冊表單及其驗證和業務邏輯代碼:
Php代碼
- <?php
-
- /**
- * LoginForm class.
- * LoginForm is the data structure for keeping
- * user login form data. It is used by the 'login' action of 'SiteController'.
- */
- class RegisterForm extends CFormModel
- {
- public $username;
- public $password;
- public $repassword;
- public $email;
- public $verifyCode;
-
- /**
- * Declares the validation rules.
- * The rules state that username and password are required,
- * and password needs to be authenticated.
- */
- public function rules()
- {
- return array(
- // username and password are required
- array('username, password, repassword, email, verifyCode', 'required'),
- array('username', 'length', 'max'=>20, 'min'=>5),
- // 用戶名惟一性驗證
- //array('username', 'unique','caseSensitive'=>false,'className'=>'user','message'=>'用戶名"{value}"已經被註冊,請更換'),
- array('username', 'checkname'),
- // 密碼一致性驗證
- array('repassword', 'compare', 'compareAttribute'=>'password','message'=>'兩處輸入的密碼並不一致'),
- // 電子郵件驗證
- array('email', 'email'),
- // 電子郵件惟一性
- //array('email', 'unique','caseSensitive'=>false,'className'=>'user','message'=>'電子郵件"{value}"已經被註冊,請更換'),
- array('email', 'checkemail'),
- //array('birthday', 'match', 'pattern'=& gt;'%^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$%', 'allowEmpty'=> true, 'message'=>'生日必須是年-月-日格式'),
- //array('mobile', 'length', 'max'=>11, 'min'=>11, 'tooLong'=>'手機號碼錯誤','tooShort'=>'手機號碼錯誤'),
- array('verifyCode', 'captcha', 'allowEmpty'=> false),
- );
- }
-
- public function checkname($attribute,$params)
- {
- //ucenter
- Yii::import('application.vendors.*');
- include_once 'ucenter.php';
- $flag = uc_user_checkname($this->username);
-
- switch($flag)
- {
- case -1:
- $this->addError('username', '用戶名不合法');
- break;
- case -2:
- $this->addError('username','包含不容許註冊的詞語');
- break;
- case -3:
- $this->addError('username','用戶名已經存在');
- break;
- }
- }
-
- public function checkemail($attribute,$params)
- {
- //ucenter
- Yii::import('application.vendors.*');
- include_once 'ucenter.php';
- $flag = uc_user_checkemail($this->email);
-
- switch($flag)
- {
- case -4:
- $this->addError('email', 'Email 格式有誤');
- break;
- case -5:
- $this->addError('email','Email 不容許註冊');
- break;
- case -6:
- $this->addError('email','該 Email 已經被註冊');
- break;
- }
- }
-
- /**
- * Declares attribute labels.
- */
- public function attributeLabels()
- {
- return array(
- 'username'=>'設定用戶名',
- 'password'=>'設定密碼',
- 'repassword'=>'再次輸入密碼',
- 'email'=>'電子郵件地址',
- 'mobile'=>'手機號碼',
- 'verifyCode'=>'驗證碼',
- );
- }
-
- /**
- * 註冊用戶
- * @return boolean whether register is successful
- */
- public function register($uid)
- {
- //ucenter
- Yii::import('application.vendors.*');
- include_once 'ucenter.php';
- $uid = uc_user_register($this->username, $this->password, $this->email);
- if($uid>0)
- {
- $model = new user;
- $model->attributes = $_POST['RegisterForm'];
- $model->password = md5($_POST['RegisterForm']['password']);
- $model->id = $uid;
-
- return $model->save();
- }
- }
- }
咱們看看上面的代碼,調用了uc_user_checkname和uc_user_checkemail完成了用戶名和email的驗證,而後調用了 uc_user_register將用戶註冊到ucenter,成功後,再註冊到Yii應用。
- 實現用戶登陸,典型的Yii應用使用 CUserIdentity來實現登陸,咱們要作的就是繼承它,實現本身的驗證邏輯:
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 UserIdentity extends CUserIdentity
- {
- public $id;
- /**
- * 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()
- {
- //ucenter
- Yii::import('application.vendors.*');
- include_once 'ucenter.php';
- list($uid, $username, $password, $email) = uc_user_login($this->username, $this->password);
- if($uid > 0)
- {
- $user = user::model()->findByPk($uid);
-
- if($user == null)//說明網站數據庫中沒有,而ucenter中有這個用戶,添加用戶
- {
- $user = new user;
- $user->username = $username;
- $user->password = md5($password);
- $user->email = $email;
- $user->id = $uid;
- $user->save();
-
- $user->refresh();
- }
-
- $this->username = $user->username;
- $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;
- }
- elseif($uid == -1)
- {
- $this->errorCode=self::ERROR_USERNAME_INVALID;
- }
- elseif($uid == -2)
- {
- $this->errorCode=self::ERROR_PASSWORD_INVALID;
- }
-
- return !$this->errorCode;
- }
-
- public function getId()
- {
- return $this->id;
- }
- }
請根據本身的應用狀況進行修改便可,這裏咱們不須要對Yii的用戶登陸作任何修改。
- 而後咱們修改 SiteController/actionLogin 方法,將同步登陸其餘應用的js輸出到瀏覽器:
Php代碼
- /**
- * Displays the login page
- */
- public function actionLogin()
- {
- $model=new LoginForm;
-
- // if it is ajax validation request
- if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
- {
- echo CActiveForm::validate($model);
- Yii::app()->end();
- }
-
- // collect user input data
- if(isset($_POST['LoginForm']))
- {
- $model->attributes=$_POST['LoginForm'];
- // validate user input and redirect to the previous page if valid
- if($model->validate() && $model->login())
- {
- //ucenter
- Yii::import('application.vendors.*');
- include_once 'ucenter.php';
- $script = uc_user_synlogin(Yii::app()->user->id);
- $this->render('loginsuc', array(
- 'script' => $script,
- ));
- Yii::app()->end();
- }
- }
- // display the login form
- $this->render('login',array('model'=>$model));
- }
簡單的loginsuc.php視圖文件:
Php代碼
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- </head>
- <body>
- <?php
- $this->layout = 'none';
- echo $script;
- ?>
- <script type="text/javascript">setTimeout('location.href="<?php echo Yii::app()->user->returnUrl ?>"',3000);</script>
- 登陸成功,正在返回登陸前頁面...
- </body>
- </html>
- 繼續修改 SiteController/actionLogout方法,實現同步退出:
Php代碼
- /**
- * Logs out the current user and redirect to homepage.
- */
- public function actionLogout()
- {
- Yii::app()->user->logout();
- //ucenter
- Yii::import('application.vendors.*');
- include_once 'ucenter.php';
- $script = uc_user_synlogout();
- $this->render('logoutsuc', array(
- 'script' => $script,
- ));
- Yii::app()->end();
- }
-
簡單的logoutsuc.php視圖文件:
Php代碼
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- </head>
- <body>
- <?php
- $this->layout = 'none';
- echo $script;
- ?>
- <script type="text/javascript">setTimeout('location.href="<?php echo Yii::app()->homeUrl ?>"',3000);</script>
- 退出成功,正在返回首頁...
- </body>
- </html>
- 進行到這裏,咱們已經實現了整合ucenter的登陸和註冊了,這樣ucenter中有的用戶,能夠登陸到yii應用,yii應用也能夠註冊用戶 到ucenter了。可是這尚未完成,咱們須要的是在discuz中用戶登陸時,也同步登陸yii應用,退出亦然,那麼咱們須要實現 Yii應用的 api/uc.php 這個接口程序。因爲咱們要用到Yii的框架資源,因此我沒有采用硬編碼的方式實現這個接口,而是建立了一個UcApplication類完成這個任務,繼 續往下看。
- 首先創建 api/uc.php 入口文件,代碼以下:
Php代碼
- <?php
- define('UC_CLIENT_VERSION', '1.6.0');
- define('UC_CLIENT_RELEASE', '20110501');
-
- define('API_DELETEUSER', 1); //note 用戶刪除 API 接口開關
- define('API_RENAMEUSER', 1); //note 用戶更名 API 接口開關
- define('API_GETTAG', 1); //note 獲取標籤 API 接口開關
- define('API_SYNLOGIN', 1); //note 同步登陸 API 接口開關
- define('API_SYNLOGOUT', 1); //note 同步登出 API 接口開關
- define('API_UPDATEPW', 1); //note 更改用戶密碼 開關
- define('API_UPDATEBADWORDS', 1); //note 更新關鍵字列表 開關
- define('API_UPDATEHOSTS', 1); //note 更新域名解析緩存 開關
- define('API_UPDATEAPPS', 1); //note 更新應用列表 開關
- define('API_UPDATECLIENT', 1); //note 更新客戶端緩存 開關
- define('API_UPDATECREDIT', 1); //note 更新用戶積分 開關
- define('API_GETCREDITSETTINGS', 1); //note 向 UCenter 提供積分設置 開關
- define('API_GETCREDIT', 1); //note 獲取用戶的某項積分 開關
- define('API_UPDATECREDITSETTINGS', 1); //note 更新應用積分設置 開關
-
- define('API_RETURN_SUCCEED', '1');
- define('API_RETURN_FAILED', '-1');
- define('API_RETURN_FORBIDDEN', '-2');
-
- // change the following paths if necessary
- $yii=dirname(__FILE__).'/../protected/yii-1.1.6/framework/yii.php';
- $config=dirname(__FILE__).'/../protected/config/main.php';
-
- // remove the following lines when in production mode
- defined('YII_DEBUG') or define('YII_DEBUG',true);
- // specify how many levels of call stack should be shown in each log message
- defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',0);
-
- require_once($yii);
- require(dirname(__FILE__).'/../protected/components/UcApplication.php');
- Yii::createApplication('UcApplication', $config)->run();
這裏能夠看到,這個腳本和標準的index.php是同樣的,只是使用了不一樣的Application類。咱們接着看這個類。
- 創建 protected/components/UcApplication.php類文件:
Php代碼
- <?php
- class UcApplication extends CWebApplication
- {
- public $defaultController = 'Uc';
-
- private $route = '';
-
- protected function preinit()
- {
- $this->parseRequest();
- }
-
- private function parseRequest()
- {
- $_DCACHE = $get = $post = array();
-
- $code = @$_GET['code'];
- parse_str($this->_authcode($code, 'DECODE', UC_KEY), $get);
- if(MAGIC_QUOTES_GPC) {
- $get = $this->_stripslashes($get);
- }
-
- $timestamp = time();
- if($timestamp - $get['time'] > 3600) {
- //exit('Authracation has expiried');
- }
- if(emptyempty($get)) {
- exit('Invalid Request');
- }
- $action = $get['action'];
-
- require_once 'xml.class.php';
- $post = xml_unserialize(file_get_contents('php://input'));
- Yii::log($get, 'debug');
- Yii::log($post, 'debug');
- $_GET = $get;
- $_POST = $post;
-
- $this->route = $this->defaultController .'/'. $action;
-
- if(!in_array($action, array('test', 'deleteuser', 'renameuser', 'gettag', 'synlogin', 'synlogout', 'updatepw', 'updatebadwords', 'updatehosts', 'updateapps', 'updateclient', 'updatecredit', 'getcreditsettings', 'updatecreditsettings')))
- {
- exit(API_RETURN_FAILED);
- }
- }
-
- public function processRequest()
- {
- $this->runController($this->route);
- }
-
- private function _authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
- $ckey_length = 4;
-
- $key = md5($key ? $key : UC_KEY);
- $keya = md5(substr($key, 0, 16));
- $keyb = md5(substr($key, 16, 16));
- $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
-
- $cryptkey = $keya.md5($keya.$keyc);
- $key_length = strlen($cryptkey);
-
- $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
- $string_length = strlen($string);
-
- $result = '';
- $box = range(0, 255);
-
- $rndkey = array();
- for($i = 0; $i <= 255; $i++) {
- $rndkey[$i] = ord($cryptkey[$i % $key_length]);
- }
-
- for($j = $i = 0; $i < 256; $i++) {
- $j = ($j + $box[$i] + $rndkey[$i]) % 256;
- $tmp = $box[$i];
- $box[$i] = $box[$j];
- $box[$j] = $tmp;
- }
-
- for($a = $j = $i = 0; $i < $string_length; $i++) {
- $a = ($a + 1) % 256;
- $j = ($j + $box[$a]) % 256;
- $tmp = $box[$a];
- $box[$a] = $box[$j];
- $box[$j] = $tmp;
- $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
- }
-
- if($operation == 'DECODE') {
- if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
- return substr($result, 26);
- } else {
- return '';
- }
- } else {
- return $keyc.str_replace('=', '', base64_encode($result));
- }
-
- }
-
- private function _stripslashes($string) {
- if(is_array($string)) {
- foreach($string as $key => $val) {
- $string[$key] = $this->_stripslashes($val);
- }
- } else {
- $string = stripslashes($string);
- }
- return $string;
- }
- }
這裏能夠看到,主要邏輯是processRequest方法,實現了ucenter通知的解碼、調用相應的控制器和動做實現操做。
- 而後創建 protected/controller/UcController.php文件,代碼以下:
Php代碼
- <?php
- class UcController extends Controller
- {
- private $appdir = '';
-
- protected function beforeAction(CAction $action)
- {
- $this->appdir = Yii::app()->basePath . '/vendors/';
- return parent::beforeAction($action);
- }
-
- public function actionTest() {
- echo API_RETURN_SUCCEED;
- }
-
- public function actionDeleteuser() {
- $uids = explode(',', str_replace("'", '', $_GET['ids']));
- !API_DELETEUSER && exit(API_RETURN_FORBIDDEN);
-
- $users = user::model()->findAllByPk($uids);
- foreach($users as $user)
- {
- $user->delete();
- }
-
- echo API_RETURN_SUCCEED;
- }
-
- public function actionRenameuser() {
- $uid = $_GET['uid'];
- $usernameold = $_GET['oldusername'];
- $usernamenew = $_GET['newusername'];
- if(!API_RENAMEUSER) {
- echo API_RETURN_FORBIDDEN;
- }
-
- $user = user::model()->findByPk($uid);
- if($user !== null)
- {
- $user->username = $usernamenew;
- if($user->save(false))
- echo API_RETURN_SUCCEED;
- else
- echo API_RETURN_FAILED;
- }
- }
-
- public function actionGettag() {
- $name = $_GET['id'];
- if(!API_GETTAG) {
- echo API_RETURN_FORBIDDEN;
- }
-
- $echo = array();
- echo $this->_serialize($return, 1);
- }
-
- public function actionSynlogin() {
- $uid = $_GET['uid'];
- $username = $_GET['username'];
- if(!API_SYNLOGIN) {
- echo API_RETURN_FORBIDDEN;
- }
-
- $identity=new UcUserIdentity($username);
-
- if($identity->authenticate())
- {
- Yii::app()->user->login($identity, 0);
- }
-
- header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
- //$_SESSION[Yii::app()->user->stateKeyPrefix.'__id'] = $uid;
- //$_SESSION[Yii::app()->user->stateKeyPrefix.'__name'] = $username;
- }
-
- public function actionSynlogout() {
- if(!API_SYNLOGOUT) {
- echo API_RETURN_FORBIDDEN;
- }
-
- //note 同步登出 API 接口
- header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
- Yii::app()->user->logout();
- }
-
- public function actionUpdatepw() {
- if(!API_UPDATEPW) {
- echo API_RETURN_FORBIDDEN;
- }
- $username = $_GET['username'];
- $password = $_GET['password'];
-
- $user = user::model()->findByAttributes(array('username'=>$username));
- if($user !== null)
- {
- $user->password = md5($password);
- if($user->save())
- echo API_RETURN_SUCCEED;
- else
- echo API_RETURN_FAILED;
- }
- else
- echo API_RETURN_FAILED;
- }
-
- public function actionUpdatebadwords() {
- if(!API_UPDATEBADWORDS) {
- echo API_RETURN_FORBIDDEN;
- }
- $cachefile = $this->appdir.'./uc_client/data/cache/badwords.php';
- $fp = fopen($cachefile, 'w');
- $data = array();
- if(is_array($_POST)) {
- foreach($_POST as $k => $v) {
- $data['findpattern'][$k] = $v['findpattern'];
- $data['replace'][$k] = $v['replacement'];
- }
- }
- $s = "<?php\r\n";
- $s .= '$_CACHE[\'badwords\'] = '.var_export($data, TRUE).";\r\n";
- fwrite($fp, $s);
- fclose($fp);
- echo API_RETURN_SUCCEED;
- }
-
- public function actionUpdatehosts() {
- if(!API_UPDATEHOSTS) {
- echo API_RETURN_FORBIDDEN;
- }
- $cachefile = $this->appdir.'./uc_client/data/cache/hosts.php';
- $fp = fopen($cachefile, 'w');
- $s = "<?php\r\n";
- $s .= '$_CACHE[\'hosts\'] = '.var_export($_POST, TRUE).";\r\n";
- fwrite($fp, $s);
- fclose($fp);
- echo API_RETURN_SUCCEED;
- }
-
- public function actionUpdateapps() {
- if(!API_UPDATEAPPS) {
- echo API_RETURN_FORBIDDEN;
- }
- $UC_API = $_POST['UC_API'];
-
- //note 寫 app 緩存文件
- $cachefile = $this->appdir.'./uc_client/data/cache/apps.php';
- $fp = fopen($cachefile, 'w');
- $s = "<?php\r\n";
- $s .= '$_CACHE[\'apps\'] = '.var_export($_POST, TRUE).";\r\n";
- fwrite($fp, $s);
- fclose($fp);
-
- //note 寫配置文件
- $config_file = Yii::app()->basePath.'./config/main.php';
- if(is_writeable($config_file)) {
- $configfile = trim(file_get_contents($config_file));
- $configfile = substr($configfile, -2) == '?>' ? substr($configfile, 0, -2) : $configfile;
- $configfile = preg_replace("/define\('UC_API',\s*'.*?'\);/i", "define('UC_API', '$UC_API');", $configfile);
- if($fp = @fopen($config_file, 'w')) {
- @fwrite($fp, trim($configfile));
- @fclose($fp);
- }
- }
-
- echo API_RETURN_SUCCEED;
- }
-
- public function actionUpdateclient() {
- if(!API_UPDATECLIENT) {
- echo API_RETURN_FORBIDDEN;
- }
- $cachefile = $this->appdir.'./uc_client/data/cache/settings.php';
- $fp = fopen($cachefile, 'w');
- $s = "<?php\r\n";
- $s .= '$_CACHE[\'settings\'] = '.var_export($_POST, TRUE).";\r\n";
- fwrite($fp, $s);
- fclose($fp);
- echo API_RETURN_SUCCEED;
- }
-
- public function actionUpdatecredit() {
- if(!API_UPDATECREDIT) {
- echo API_RETURN_FORBIDDEN;
- }
- $credit = $_GET['credit'];
- $amount = $_GET['amount'];
- $uid = $_GET['uid'];
- echo API_RETURN_SUCCEED;
- }
-
- public function actionGetcredit() {
- if(!API_GETCREDIT) {
- echo API_RETURN_FORBIDDEN;
- }
- }
-
- public function actionGetcreditsettings() {
- if(!API_GETCREDITSETTINGS) {
- echo API_RETURN_FORBIDDEN;
- }
- $credits = array();
- echo $this->_serialize($credits);
- }
-
- public function actionUpdatecreditsettings() {
- if(!API_UPDATECREDITSETTINGS) {
- echo API_RETURN_FORBIDDEN;
- }
- echo API_RETURN_SUCCEED;
- }
-
- private function _serialize($arr, $htmlon = 0) {
- if(!function_exists('xml_serialize')) {
- include_once 'xml.class.php';
- }
- echo xml_serialize($arr, $htmlon);
- }
- }
上面用到了xml.class.php這個類文件,能夠在uc_client/lib目錄找到。
這裏須要說明的是,actionSynlogin方法中,利用了我定義的特殊的UserIdentity來登陸的,由於不須要提供密碼。
- 再來看看最後一個類:
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中有這個用戶,添加用戶
- {
- //ucenter
- Yii::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,呵呵。
有什麼問題,歡迎評論,和我聯繫。你們一塊兒進步吧! html
PS: 須要注意的是,整合了ucenter的Yii應用在部署時,需將 protected/vendors/uc_client/data/及其子目錄、文件設爲可寫。不然將會有些奇怪的問題。 java