Files
xk-api-yii/admin/models/forms/LoginForm.php

98 lines
2.3 KiB
PHP

<?php
namespace admin\models\forms;
use admin\models\Admin;
use common\core\BaseModel;
use common\models\oldDb\AdminAccessToken;
use common\validators\MobieValidator;
use yii\db\Exception;
/**
* register form
*/
class LoginForm extends BaseModel
{
public $mobile;
public $password;
public $rememberMe = true;
/**
* @var Admin
*/
private $_user;
/**
* @inheritdoc
*/
public function rules()
{
return [
[['mobile', 'password'], 'required'],
['mobile', MobieValidator::class],
['password', 'validatePassword'],
['rememberMe', 'boolean'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, '账号或密码错误!');
}
}
}
/**
* Logs in a user using the provided username and password.
*
* @return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
$adminAccessToken = new AdminAccessToken();
return $adminAccessToken->createToken($this->_user->uid,'admin');
} else {
throw new Exception($this->getErrorMsg());
}
}
/**
* Finds user by [[username]]
*
* @return Admin|null
*/
public function getUser()
{
if ($this->_user === null) {
$this->_user = Admin::findByMobile($this->mobile);
}
return $this->_user;
}
public function ResetPassword()
{
$admin=Admin::find()->where([
'mobile'=>$this->mobile
])->one();
if (!$admin) return ['账号不存在'];
$admin->password=(new Admin())->setPassword($this->password);
if (!$admin->saveOrFail())throw new Exception('重置密码或忘记密码失败');
return ['重置密码或忘记密码成功'];
}
}