更新时间:2023-01-15 17:39:54
你可以使用像 https://github.com/amnah/yii2-user.
或
如果您想编写自己的自定义脚本来管理用户,您可以覆盖 Yii2 identityClass.
If you want to write your own custom script to manage the users you can override Yii2 identityClass.
在配置的组件部分添加:
In the component section of your config add:
'user' => [
'identityClass' => 'appmodelsUser',
'enableAutoLogin' => true,
],
请注意,您的用户模型必须实现 yiiwebIdentityInterface
Please note that your user model MUST IMPLEMENT yiiwebIdentityInterface
这里是你可以用来实现数据库认证的模型类的例子
Here is the example of the model class that you can use to implement database authentication
namespace appmodels;
//appmodelsgiiUsers is the model generated using Gii from users table
use appmodelsgiiUsers as DbUser;
class User extends yiiaseObject implements yiiwebIdentityInterface {
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
public $email;
public $phone_number;
public $user_type;
/**
* @inheritdoc
*/
public static function findIdentity($id) {
$dbUser = DbUser::find()
->where([
"id" => $id
])
->one();
if (!count($dbUser)) {
return null;
}
return new static($dbUser);
}
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $userType = null) {
$dbUser = DbUser::find()
->where(["accessToken" => $token])
->one();
if (!count($dbUser)) {
return null;
}
return new static($dbUser);
}
/**
* Finds user by username
*
* @param string $username
* @return static|null
*/
public static function findByUsername($username) {
$dbUser = DbUser::find()
->where([
"username" => $username
])
->one();
if (!count($dbUser)) {
return null;
}
return new static($dbUser);
}
/**
* @inheritdoc
*/
public function getId() {
return $this->id;
}
/**
* @inheritdoc
*/
public function getAuthKey() {
return $this->authKey;
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey) {
return $this->authKey === $authKey;
}
/**
* Validates password
*
* @param string $password password to validate
* @return boolean if password provided is valid for current user
*/
public function validatePassword($password) {
return $this->password === $password;
}
}
希望对你有帮助.干杯:)
I hope that would be helpful to you . Cheers :)