123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- <?php
- namespace backend\forms;
- use common\models\AccessToken;
- use common\models\Client;
- use common\models\User;
- use components\Exception;
- use Yii;
- class AuthForm extends BaseForm
- {
- /**
- * @var
- */
- public $username;
- /**
- * @var
- */
- public $password;
- /**
- * @var null
- */
- public $access_token = null;
- /**
- * @var null
- */
- private $_user = null;
- /**
- * @var
- */
- private $_response;
- /**
- * 失效时长
- */
- const EXPIRES = 30 * 86400;
- public function rules()
- {
- return [
- [['username', 'password'], 'required', 'on' => ['access_token']],
- [['username', 'password'], 'trim', 'on' => ['access_token']],
- //['username', 'validateUser', 'on' => 'access_token'],
- ['password', 'validatePassword', 'on' => ['access_token']],
- ];
- }
- public function validatePassword($attribute)
- {
- if (!$this->hasErrors()) {
- if (!$this->findUser(['username' => $this->username, 'status' => User::STATUS_ACTIVE])
- || !$this->password
- || !$this->_user['password']
- || !Yii::$app->security->validatePassword($this->password, $this->_user['password']))
- {
- $this->addError($attribute, 2001);
- }
- }
- }
- /**
- * getAccessToken
- * @author: libingke
- * @return string
- */
- public function getAccessToken()
- {
- $this->generateAccessToken();
- return $this->_response;
- }
- public function generateAccessToken()
- {
- $this->access_token = Yii::$app->security->generateRandomString();
- $expires = strtotime(date('Y-m-d 23:59:59')) + static::EXPIRES;
- //insert
- if ( !($one = AccessToken::findOne(['access_token' => $this->access_token])) ) {
- $model = new AccessToken();
- $model->access_token = $this->access_token;
- $model->user_id = $this->_user['uid'];
- $model->ip = isset(Yii::$app->request->userIP) ? Yii::$app->request->userIP : '';
- $model->user_agent = isset(Yii::$app->request->userAgent) ? Yii::$app->request->userAgent : '';
- $model->expires = $expires;
- if (!$model->save(false))
- throw new Exception(2002);
- }
- $this->_response = array(
- "access_token" => $this->access_token,
- "expires" => $expires
- );
- }
- /**
- * findUser
- * @author: libingke
- * @param array $query
- */
- public function findUser(Array $query = [])
- {
- if (!$this->_user) {
- $user = User::findOne($query);
- if ($user)
- $this->_user = [
- 'uid' => $user->id,
- 'username' => $user->username,
- 'password' => $user->password_hash
- ];
- }
- return $this->_user;
- }
- }
|