接上一篇:基于yii2的blog系统开发7-评论审核:
第十四步 用户认证
高级模版装好以后,前端frontend的用户认证就已经完成了
常用代码说明:
//检测当前用户身份
$identity = Yii::$app->user->identity;
//获取用户id,未认证用户为Null
$id = Yii::$app->user->id;
//判断当前用户是否是游客
$isGuest = Yii::$app->user->isGuest;
//将当前用户的身份登记到yii\web\User。根据设置用session或cookie记录用户身份,用户的认证状态将在整个会话中得以维持。
Yii::$app->user->login($identity);
//注销用户
Yii::$app->user->logout();
后端用户认证
前端用户的默认认证类是User,对应前端用户的user表,后端用户表是adminuser,而后端用户的默认模版安装的认证类还是user显然就不对了,所以这儿
1.修改backend/config/main.php:
'identityClass' => 'common\models\Adminuser',
另外,要实现后端用户认证可以参考前端用户认证代码来改。
2.修改common/models/Adminuser.php:
<?php
namespace common\models;
use Yii;
use yii\web\IdentityInterface;
/**
* This is the model class for table "adminuser".
*
* @property int $id
* @property string $username
* @property string $nickname
* @property string $password
* @property string $email
* @property string|null $profile
* @property string $auth_key
* @property string $password_hash
* @property string|null $password_reset_token
*
* @property Post[] $posts
*/
class Adminuser extends \yii\db\ActiveRecord implements IdentityInterface
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'adminuser';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['username', 'nickname', 'password', 'email', 'auth_key', 'password_hash'], 'required'],
[['profile'], 'string'],
[['username', 'nickname', 'password', 'email'], 'string', 'max' => 128],
[['auth_key'], 'string', 'max' => 32],
[['password_hash', 'password_reset_token'], 'string', 'max' => 255],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => 'Username',
'nickname' => 'Nickname',
'password' => 'Password',
'email' => 'Email',
'profile' => 'Profile',
'auth_key' => 'Auth Key',
'password_hash' => 'Password Hash',
'password_reset_token' => 'Password Reset Token',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getPosts()
{
return $this->hasMany(Post::className(), ['author_id' => 'id']);
}
/**
* {@inheritdoc}
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id]);
}
/**
* {@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]);
}
/**
* 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 user by verification email token
*
* @param string $token verify email token
* @return static|null
*/
public static function findByVerificationToken($token) {
return static::findOne([
'verification_token' => $token,
// 'status' => self::STATUS_INACTIVE
]);
}
/**
* Finds out if password reset token is valid
*
* @param string $token password reset token
* @return bool
*/
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 bool 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();
}
/**
* Generates new token for email verification
*/
public function generateEmailVerificationToken()
{
$this->verification_token = Yii::$app->security->generateRandomString() . '_' . time();
}
/**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
}
3.修改backend/controllers/siteController.php:
LoginForm已经被前端用了,所以这儿用一个新的BackLoginForm
use common\models\BackLoginForm;
public function actionLogin()
{...
$model = new BackLoginForm();
...
}
4.把common/models/LoginForm.php拷贝一份,重新命名为BackLoginForm.php并修改对应代码:
class BackLoginForm extends Model
{
public function attributeLabels()
{
return [
'username' => '用户名',
'password' => '密码',
'rememberMe'=>'记住密码',
];
}
protected function getUser()
{
if ($this->_user === null) {
$this->_user = Adminuser::findByUsername($this->username);
}
return $this->_user;
}
}