antonyz89 / yii2-password-behavior
密码管理行为
0.1.3.3
2021-07-31 21:39 UTC
Requires
- yiisoft/yii2: ~2.0.0
README
密码管理行为
安装
安装此扩展的首选方式是通过 composer。
运行以下命令之一:
php composer.phar require --prefer-dist antonyz89/yii2-password-behavior "*"
或者将以下内容添加到你的 composer.json
文件的 require 部分:
"antonyz89/yii2-password-behavior": "*"
用法
只需在 Model 的行为函数中添加 PasswordBehavior::class
public function behaviors() { return [ PasswordBehavior::class, ]; }
_form.php
:
<div class="row"> <div class="col-md-4"> <?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?> <?php if ($model->isNewRecord): ?> <?= $form->field($model, 'password_hash')->passwordInput() ?> <!-- required on create --> <?= $form->field($model, 'confirm_password')->passwordInput() ?> <?php else: ?> <?= $form->field($model, 'old_password')->passwordInput() ?> <?= $form->field($model, 'new_password')->passwordInput() ?> <!-- required on update (replaces password_hash) --> <?= $form->field($model, 'confirm_password')->passwordInput() ?> <?php endif; ?> </div> <!-- /.col-md-4 --> </div> <!-- /.row -->
要正常工作,你的 Model 需要有以下四个变量
$password_hash
、$new_password
、$confirm_password
、$old_password
如果你有这些变量,但名称不同,只需做以下操作
/** * @property string $password */ class ExampleModel extends ActiveRecord implements IdentityInterface, UserCredentialsInterface { public $new_password, $confirmPsw, $oldPsw, $authorizationKey; // new_password can be skipped because they already exists /** * @inheritDoc */ public function behaviors() { return [ [ 'class' => PasswordBehavior::class, 'password_hash' => 'password', 'confirm_password' => 'confirmPsw', 'auth_key' => 'authorizationKey', 'old_password' => 'oldPsw' ] ]; } }
如果你想要忽略 $confirm_password
、$old_password
和/或 $auth_key
,只需做以下操作
/** * @property string $password */ class ExampleModel extends ActiveRecord implements IdentityInterface, UserCredentialsInterface { public $new_password; // new_password can be skipped because they already exists /** * @inheritDoc */ public function behaviors() { return [ [ 'class' => PasswordBehavior::class, 'password_hash' => 'password', /* * Will be ignored and comparison between * `$confirm_password` and `$new_password` or `$password_hash` will not happen */ 'confirm_password' => false, /* * Will be ignored and comparison between * `old_password` and `$new_password` will not happen */ 'old_password' => false, /* * Will be ignored and when a new password is defined * a new Authorization Key will not generated */ 'auth_key' => false ] ]; } }
国际化
添加到 common\config\main.php
'components' => [ ... 'i18n' => [ 'translations' => [ 'psw' => [ 'class' => PhpMessageSource::class, 'basePath' => '@antonyz89/password_behaviour/messages', ] ], ] ];