['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; } }