Yii2博客实战教程——实现前后台用户完全分离

Yii自带开箱即用的用户模型,包括整个用户的登陆注册等。可以这个默认的用户模型有个缺点,就是不区分前台用户和后台用户,而往往我们希望我们对后天管理员采用不同的数据表进行单独的管理。如何实现这个功能呢,我们现在就来讲讲如何实现前后台用户的完全分离。

1.创建后台管理员AR模型Admin(backend\models\Admin) 实现IdentityInterface接口。也可以直接修改common\models\User然后修改。

<?php
namespace backend\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use yii\web\IdentityInterface;
/**
 * User model
 *
 * @property integer $id
 * @property string $username
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property string $auth_key
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 * @property string $password write-only password
 */
class Admin extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
/**
 * @inheritdoc
*/
public static function tableName()
 {
return '{{%admin}}';
}
/**
 * @inheritdoc
*/
public function behaviors()
 {
return [
 TimestampBehavior::className(),
];
}
/**
 * @inheritdoc
*/
public function rules()
 {
return [
 ['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
];
}
public static function getStatusTitle($status=false){
$status_array= [
''=>'请选择',
self::STATUS_DELETED=>'禁止',
self::STATUS_ACTIVE=>'正常'
];
return $status==false?$status_array:ArrayHelper::getValue($status_array,$status,'未知');
}
/**
 * @inheritdoc
*/
public static function findIdentity($id)
 {
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
/**
 * @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
 {
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
*/
public function getId()
 {
return $this->getPrimaryKey();
}
/**
 * @inheritdoc
*/
public function getAuthKey()
 {
return $this->auth_key;
}
/**
 * @inheritdoc
*/
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;
}
}

2.添加backend\models\LoginForm.php 其实也可以直接copy common中的loginform做少许修改

<?php
namespace backend\models;

use Yii;
use yii\base\Model;

/**
 * Login form
 */
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
public $verifyCode;
private $_user;


/**
 * @inheritdoc
*/
public function rules()
 {
return [
// username and password are both required
[['username', 'password'], 'required','message' => '请输入信息'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'], 
['verifyCode', 'captcha','message' => '验证码不正确'],
];
}

public function attributeLabels()
 {
return [
'username' => '用户名',
'password' => '密码',
'email' => '邮箱',
'rememberMe' => '记住密码',
'verifyCode' =>'验证码',
];
}



/**
 * Validates the password.
 * This method serves as the inline validation for password.
 *
 * @param string $attribute the attribute currently being validated
 * @param array $params the additional name-value pairs given in the rule
 */
public function validatePassword($attribute, $params)
 {
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, '用户名或密码错误.');
}
 }
 }

/**
 * Logs in a user using the provided username and password.
 *
 * @return boolean whether the user is logged in successfully
 */
public function login()
 {
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
 }

/**
 * Finds user by [[username]]
 *
 * @return User|null
 */
protected function getUser()
 {
if ($this->_user === null) {
$this->_user = Admin::findByUsername($this->username);
}

return $this->_user;
}
}

3.为登陆增加验证码功能

backend\views\siteController.php中增加captcha验证码,

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'maxLength'=>4,
                'minLength'=>4,
            ],
        ];
    }

<span class="redactor-invisible-space">    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error', 'captcha',],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }</span>

同时修改backend\views\siteController.php中LoginForm的引用

use common\models\LoginForm;
<span class="redactor-invisible-space">修改为
</span>use backend\models\LoginForm;

在backend\views\site\login.php 在ActiveForm中加入验证码字段

<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \common\models\LoginForm */

$this->title = 'Sign In';

$fieldOptions1 = [
'options' => ['class' => 'form-group has-feedback'],
'inputTemplate' => "{input}<span class='glyphicon glyphicon-envelope form-control-feedback'></span>"
];

$fieldOptions2 = [
'options' => ['class' => 'form-group has-feedback'],
'inputTemplate' => "{input}<span class='glyphicon glyphicon-lock form-control-feedback'></span>"
];
?>

<div class="login-box">
 <div class="login-logo">
 <a href="#"><b>Admin</b>LTE</a>
 </div>
<!-- /.login-logo -->
<div class="login-box-body">
 <p class="login-box-msg">Sign in to start your session</p>

<?php $form = ActiveForm::begin(['id' => 'login-form', 'enableClientValidation' => false]); ?>

<?= $form
->field($model, 'username', $fieldOptions1)
 ->label(false)
 ->textInput(['placeholder' => $model->getAttributeLabel('username')]) ?>

<?= $form
->field($model, 'password', $fieldOptions2)
 ->label(false)
 ->passwordInput(['placeholder' => $model->getAttributeLabel('password')]) ?>

<?= $form
->field($model, 'verifyCode')
 ->label(false)
 ->widget(Captcha::className(), [
'template' => '<div class="input-group"> 
 {input}
 <span class="input-group-addon" style="padding-left:10px; padding-right:10px;">{image}</span>
 </div>',
'options' => ['class' => 'form-control', 'maxlength'=>"4", 'placeholder'=>"验证码" ],
'imageOptions' =>['style'=>'height:20px', 'border'=>'0', 'alt'=>"点击更换验证码" ]
 ]) ?>



<div class="row">
 <div class="col-xs-8">
<?= $form->field($model, 'rememberMe')
 ->checkbox()
 ->label($model->getAttributeLabel('rememberMe')) ?>
</div>
<!-- /.col -->
<div class="col-xs-4">
<?= Html::submitButton('登陆', ['class' => 'btn btn-primary btn-block btn-flat', 'name' => 'login-button']) ?>
</div>
<!-- /.col -->
</div>

<?php ActiveForm::end(); ?> 

</div>
<!-- /.login-box-body -->
</div><!-- /.login-box -->

4.修改backend\config\main中的components下的user 节点

'components' => [

'user' => [
'identityClass' => 'backend\models\Admin',
'enableAutoLogin' => true,
'identityCookie' => [
'name' => '_backendUser', // cookie name for backend user
]
 ],
...

这样就做到l前后台用户的完全分离,包括cookie记住用户,用户的登陆、登出互不影响。







本文由 Leo's Blog 创作,采用 署名-非商业性使用 2.5 中国大陆 进行许可。
如需转载、引用请署名作者且注明文章出处。
2016年06月27日 3552 浏览 评论 YII2 前后台用户分离
上一篇:Yii2博客实战教程——后台模板AdminLTE的整合 | 下一篇:Yii2博客实战教程——用gii快速创建CURD页面