This repository has been archived on 2024-10-16. You can view files and clone it, but cannot push or open issues or pull requests.
skillparts/mirzaev/skillparts/system/models/AccountForm.php

139 lines
3.8 KiB
PHP

<?php
namespace app\models;
use Yii;
use yii\base\Model;
use app\models\Account;
/**
* AccountForm is the model behind the login form.
*
* @property-read Account|null $account This property is read-only.
*
*/
class AccountForm extends Model
{
const SCENARIO_REGISTRATION = 'registration';
const SCENARIO_REGISTRATION_END = 'registration_end';
const SCENARIO_AUTHENTICATION = 'authentication';
public $mail;
public $pswd;
public $auto = true;
private $account = false;
public function rules()
{
return [
// Обязательные поля
[['mail', 'pswd'], 'required', 'message' => 'Заполните поле'],
// Функция "Запомнить меня"
['auto', 'boolean', 'on' => self::SCENARIO_AUTHENTICATION],
// Проверка почты,
['mail', 'email', 'message' => 'Проверьте почту'],
['mail', 'validateMail', 'on' => self::SCENARIO_REGISTRATION],
// Проверка пароля
['pswd', 'validatePassword', 'on' => self::SCENARIO_AUTHENTICATION]
];
}
public function attributeLabels()
{
return [
'mail' => 'Почта',
'pswd' => 'Пароль',
'auto' => '<i class="fas fa-lock"></i>'
];
}
public function validateMail($attribute, $params)
{
if (!$this->hasErrors()) {
// Проблем нет, обрабатывается событие регистрации
$account = $this->getAccount();
if (!$account || $account->validateMail($this->mail)) {
// Проверка не пройдена
$this->addError($attribute, 'Почта уже привязана');
}
}
}
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
// Проблем нет, обрабатывается событие аутентификации
$account = $this->getAccount();
if (!$account || !$account->validatePassword($this->pswd)) {
// Проверка не пройдена
$this->addError($attribute, 'Проверьте пароль');
}
}
}
/**
* Logs in a account using the provided accountname and password.
* @return bool whether the account is logged in successfully
*/
public function authentication(string $mail = null, string $pswd = null)
{
if (isset($mail, $pswd)) {
$this->mail = $mail;
$this->pswd = $pswd;
}
if (isset($this->mail, $this->pswd) && $this->validate()) {
// Проверка пройдена
// Аутентификация
return Yii::$app->user->login($this->getAccount(), $this->auto ? 3600 * 24 * 30 : 0);
}
return false;
}
/**
* @return bool
*/
public function registration()
{
// Инициализация нового аккаунта
$this->account = new Account();
if (isset($this->mail, $this->pswd) && $this->validate()) {
// Проверка пройдена
// Запись параметров
$this->account->mail = $this->mail;
$this->account->pswd = Yii::$app->security->generatePasswordHash($this->pswd);
// Регистрация
return $this->account->save();
}
return false;
}
/**
* Finds account by [[accountname]]
*
* @return Account|null
*/
public function getAccount()
{
if ($this->account === false) {
$this->account = Account::findByMail($this->mail);
}
return $this->account;
}
}