yii2单点接入ucenter(原创)
1.第一步
在中心端添加应用,此处略去,根据官方文档即可实现.
第二步.
用户表如下,基本用原生的用户表即可,取决于你的ucenter主机服务端传送什么用户信息:
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(20) UNSIGNED NOT NULL AUTO_INCREMENT, `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名', `password_hash` varchar(80) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码', `password_reset_token` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '密码token', `email` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '邮箱', `auth_key` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `status` tinyint(5) NULL DEFAULT 1 COMMENT '0禁用 1启用', `created_at` int(18) NULL DEFAULT NULL COMMENT '创建时间', `updated_at` int(18) NULL DEFAULT NULL COMMENT '更新时间', `realname` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '真实名称', `user_id` int(11) NULL DEFAULT NULL COMMENT '统一登录用户id', `dep_id` int(11) NULL DEFAULT NULL COMMENT '部门id', `title` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `nickname` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '昵称', PRIMARY KEY (`id`) USING BTREE, UNIQUE INDEX `username`(`username`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 72 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '后台用户表' ROW_FORMAT = Compact; SET FOREIGN_KEY_CHECKS = 1;
第三步:
yii2在配置文件加入:
'components' => [ ... 'ucenter' => [ 'class' => 'yii\lyuser\Client', 'baseUrl' => 'http://www-test.lanyife.com.cn/passport', 'appKey' => 'medusa', 'appSecret' => '1f13f6b2508b03b25dc1088588bef3eb', 'jumpUrl' => "http://{$_SERVER['HTTP_HOST']}/site/login", 'url' => "http://{$_SERVER['HTTP_HOST']}", ], ... ],
第四步:
在默认控制器里这么改造
<?php namespace backend\controllers; use Yii; use yii\helpers\Url; use yii\web\Controller; use yii\filters\VerbFilter; use yii\filters\AccessControl; use common\models\LoginForm; use common\models\User; use yii\web\Response; /** * Site controller */ class SiteController extends Controller { /** * {@inheritdoc} */ public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['POST'], ], ], ]; } /** * {@inheritdoc} */ public function actions() { return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], ]; } /** * Displays homepage. * * @return string */ public function actionIndex() { if(yii::$app->user->isGuest){ return $this->redirect(Url::toRoute('site/login')); } return $this->render('index'); } /** * Login action. * * @return string */ public function actionLogin() { if( \Yii::$app->user->isGuest ){ return \Yii::$app->ucenter->goLogin(); } $this->redirect('/'); } /** * 同步登录 * @return string */ public function actionSyncLogin() { $r = \Yii::$app->ucenter->synLogin(); // \Yii::$app->response->format = Response::FORMAT_JSONP; if ($r) { if (\Yii::$app->request->get('action') == 'login') { //获取登录用户信息 $userInfo = \Yii::$app->ucenter->getUserInfo(); file_put_contents('/tmp/77.log',json_encode($userInfo).date('y-m-d H:i:s') ); if (empty($userInfo)) { return false; } $res = $this->_loginOrRegister($userInfo); if($res){ $user = User::findOne(['username'=>$userInfo['username'] ]); \Yii::$app->getUser()->login($user, 86400); } } \Yii::$app->response->content = 'login(1)'; } else { \Yii::$app->response->content = 'login(0)'; } \Yii::$app->response->send(); \Yii::$app->end(); } //注销 public function actionLogout() { //本地 注销 Yii::$app->user->logout(); // Yii::$app->getUser()->logout(); //跳转UCenter注销页面 $callback 注销返回的url \Yii::$app->ucenter->goLogout(\Yii::$app->ucenter->jumpUrl); } /** * 第一次登录或者多次登录,实现信息同步并注册 * @param array $userInfo * @return bool */ private function _loginOrRegister($userInfo) { if (empty($userInfo)||!isset($userInfo['username'])) { return false; } $user = User::findOne(['username'=>$userInfo['username']]); if (empty($user)) { //保存创建本地新用户 $res = yii::$app->db->createCommand()->insert('user',[ 'username' => $userInfo['username'], 'auth_key'=> $userInfo['auth_key'], 'realname' =>$userInfo['realname'], 'user_id' => $userInfo['id'], 'dep_id' => $userInfo['dep_id'], 'status' => $userInfo['status'], 'created_at' =>$userInfo['created_at'], 'updated_at'=> $userInfo['updated_at'], 'email' =>$userInfo['email'], 'title' =>$userInfo['title'], 'nickname' => $userInfo['nickname'], //模型User的激活状态要定义,比如我 //见下图 'status' => User::STATUS_ACTIVE, 'password_hash'=>Yii::$app->security->generatePasswordHash('123456') ])->execute(); } else { yii::$app->db->createCommand()->update('user',['user_id'=>$userInfo['id']] ,[ 'dep_id' => $userInfo['dep_id'], 'realname' => $userInfo['realname'], 'updated_at' => $userInfo['updated_at'], 'title' => $userInfo['title'], ])->execute(); } return true; } }