Всем привет.
Как в yii2 сделать авторизацию по логину без пароля.
User
public static function findByUsername($username)
{
return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
}
Login
class Login extends Model
{
public $username;
//public $password;
//public $rememberMe = true;
public $status;
private $_user = false;
public function rules()
{
return [
[['username'], 'required', 'on' => 'default'],
//['rememberMe', 'boolean'],
//['password', 'validatePassword']
];
}
/**
* @param $attribute
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
}
return $this->_user;
}
/**
* @return array
*/
public function attributeLabels()
{
return [
'username' => 'Почта',
];
}
/**
* @return bool
*/
public function login()
{
if ($this->validate()) {
$this->status = ($user = $this->getUser()) ? $user->status : User::STATUS_NOT_ACTIVE;
if ($this->status === User::STATUS_ACTIVE) {
return Yii::$app->user->login($user, $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
} else {
return false;
}
}
}
view login
<?php $form = ActiveForm::begin([
'id' => 'login-form',
'layout' => 'horizontal',
'fieldConfig' => [
'template' => "{label}\n<div class=\"col-lg-3\">{input}</div>\n<div class=\"col-lg-8\">{error}</div>",
'labelOptions' => ['class' => 'col-lg-1 control-label'],
],
]); ?>
<?= $form->field($model, 'username')->textInput(['autofocus' => true]) ?>
<?php // $form->field($model, 'password')->passwordInput() ?>
<div class="form-group">
<div class="col-lg-offset-1 col-lg-11">
<?= Html::submitButton('Авторизация', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>