> YII2默認生成的登錄案例里用的是user表,只是給出一個案例。那么如果我們要用到后臺管理員登錄、商家中心登錄呢?
> 那么我們需要另外建各自的表,如admin表、seller表等。下面我以管理員后臺登錄為例進行講解。
[TOC]
#### 1.創建admin表
> 參考yii自帶的用戶表結構(自帶的用戶表參考console\migrations\xxx_init.php文件)創建如下數據表
~~~
CREATE TABLE `admin` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(255) COLLATE utf8_unicode_ci NOT NULL,
`auth_key` VARCHAR(32) COLLATE utf8_unicode_ci NOT NULL,
`password_hash` VARCHAR(255) COLLATE utf8_unicode_ci NOT NULL,
`password_reset_token` VARCHAR(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`email` VARCHAR(255) COLLATE utf8_unicode_ci NOT NULL,
`status` SMALLINT(6) NOT NULL DEFAULT '10',
`created_at` INT(11) NOT NULL,
`updated_at` INT(11) NOT NULL,
`access_token` VARCHAR(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`),
UNIQUE KEY `email` (`email`),
UNIQUE KEY `password_reset_token` (`password_reset_token`)
) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
~~~
#### 2.拷貝LoginForm
>打開common\models\LoginForm.php文件,找到getUser方法,這里的User類使用的還是common\models\User類,改為Admin類。
~~~
protected function getUser()
{
if ($this->_user === null) {
$this->_user = Admin::findByUsername($this->username);
}
return $this->_user;
}
~~~
#### 3.拷貝User類,并改為Admin類
>打開backend\models\Admin.php文件,該類至少需要實現接口 yii\web\IdentityInterface 幾個抽象方法才可以,可以從common\models\User.php里拷貝相應代碼。
~~~
<?php
namespace backend\models;
use Yii;
use yii\web\IdentityInterface;
/**
* This is the model class for table "user_backend".
*
* @property integer $id
* @property string $username
* @property string $auth_key
* @property string $password_hash
* @property string $email
* @property string $created_at
* @property string $updated_at
*/
class Admin extends \yii\db\ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
// 其他gii生成的代碼,因為我們并未對其進行過改動,因此這里省略,下面只補充我們實現的幾個抽象方法
/**
* @inheritdoc
* 根據admin表的主鍵(id)獲取用戶
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id]);
}
/**
* @inheritdoc
* 根據access_token獲取用戶,我們暫時先不實現
*/
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
//throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by username
*
* @param string $username
* @return static|null
*/
public static function findByUsername($username)
{
return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
}
/**
* Finds user by password reset token
*
* @param string $token password reset token
* @return static|null
*/
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
}
return static::findOne([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
/**
* Finds out if password reset token is valid
*
* @param string $token password reset token
* @return boolean
*/
public static function isPasswordResetTokenValid($token)
{
if (empty($token)) {
return false;
}
$timestamp = (int) substr($token, strrpos($token, '_') + 1);
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
return $timestamp + $expire >= time();
}
/**
* @inheritdoc
* 用以標識 Yii::$app->user->id 的返回值
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* @inheritdoc
* 獲取auth_key
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* @inheritdoc
* 驗證auth_key
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*
* @param string $password password to validate
* @return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_hash);
}
/**
* Generates password hash from password and sets it to the model
*
* @param string $password
*/
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}
/**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
}
~~~
#### 4.修改配置文件,identityClass指向Admin類
>打開backend\config\main.php, 找到components user這里,修改backend\models\Admin類為我們的認證類
~~~
'components' => [
'user' => [
'identityClass' => 'backend\models\Admin',
'enableAutoLogin' => true,
],
],
~~~
- 基礎教程
- 入門安裝
- Yii2 composer 安裝慢解決
- Cookies
- 數據庫操作
- 數據提供者
- 助手類
- 驗證規則
- GridView
- DetailView
- YII2分頁
- JS、CSS的引用
- Excel導出
- 中文轉拼音
- 發送郵件
- 第三方插件
- Session跨域共享
- Url跨域訪問
- 場景應用
- 查詢條件鏈
- Session分布式共享
- Redis的使用
- mongodb
- 高級教程
- 自定義gii模板
- 角色權限管理(RBAC)
- user組件的配置
- 國際化(I18N)
- 小部件(Widget)
- 模塊(Module)
- 行為(Behavior)
- 緩存(Cache)
- migrate 數據庫遷移
- phpstorm
- 快捷鍵
- 自定義
- 其它插件