guild/frontend/modules/api/models/LoginForm.php

70 lines
1.7 KiB
PHP
Raw Normal View History

2021-07-28 18:15:38 +03:00
<?php
namespace frontend\modules\api\models;
use common\models\User;
use Yii;
use yii\base\Model;
/**
* Login form
*/
class LoginForm extends Model
{
2023-12-15 19:30:25 +03:00
public $email;
2021-07-28 18:15:38 +03:00
public $password;
public $rememberMe = true;
private $_user;
Const EXPIRE_TIME = 604800; // token expiration time, valid for 7 days
/**
* {@inheritdoc}
*/
public function rules()
{
return [
2023-12-15 19:30:25 +03:00
// email and password are both required
[['email', 'password'], 'required'],
2021-07-28 18:15:38 +03:00
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
public function validatePassword($attribute)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
2023-12-15 19:30:25 +03:00
$this->addError($attribute, 'Incorrect e-mail or password.');
2021-07-28 18:15:38 +03:00
}
}
}
public function login()
{
if ($this->validate()) {
if ($this->getUser()) {
$access_token = $this->_user->generateAccessToken();
$this->_user->access_token_expired_at = date('Y-m-d', time() + static::EXPIRE_TIME);
$this->_user->save();
Yii::$app->user->login($this->_user, static::EXPIRE_TIME);
return $access_token;
}
}
return false;
}
2022-12-23 17:40:43 +03:00
public function getUser(): ?User
2021-07-28 18:15:38 +03:00
{
if ($this->_user === null) {
2023-12-15 19:30:25 +03:00
$this->_user = User::findByEmail($this->email);
2021-07-28 18:15:38 +03:00
}
return $this->_user;
}
}