public function execute() { if (!$this->checkRequest()) { return; } $code = waRequest::post('code'); $auth_codes_model = new waApiAuthCodesModel(); $row = $auth_codes_model->getById($code); if ($row) { // check client_id if ($row['client_id'] != waRequest::post('client_id')) { $this->response(array('error' => 'invalid_grant')); return; } // check expire if (strtotime($row['expires']) < time()) { $this->response(array('error' => 'invalid_grant', 'error_description' => 'Authorization code expired')); return; } // create token $token_model = new waApiTokensModel(); $token = $token_model->getToken($row['client_id'], $row['contact_id'], $row['scope']); $this->response(array('access_token' => $token)); } else { $this->response(array('error' => 'invalid_grant', 'error_description' => 'Invalid code: ' . $code)); } }
protected function approve() { $url = waRequest::get('redirect_uri'); if ($this->response_type == 'token') { $token_model = new waApiTokensModel(); $token = $token_model->getToken($this->client_id, $this->contact_id, waRequest::get('scope')); $this->redirect($url . '#access_token=' . $token); } elseif ($this->response_type == 'code') { $code = $this->createAuthCode(); // redirect if ($url) { $this->redirect($url . (strpos($url, '?') === false ? '?' : '&') . 'code=' . $code); } else { $this->view->assign('code', $code); } } }
PRIMARY KEY (`token`), UNIQUE KEY `contact_client` (`contact_id`,`client_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8'); // new table for api auth codes $model->exec('CREATE TABLE IF NOT EXISTS `wa_api_auth_codes` ( `code` varchar(32) NOT NULL, `contact_id` int(11) NOT NULL, `client_id` varchar(32) NOT NULL, `scope` text NOT NULL, `expires` datetime NOT NULL, PRIMARY KEY (`code`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8'); try { // try move data from old table $rows = $model->query("SELECT * FROM wa_contact_tokens"); $api_tokens_model = new waApiTokensModel(); foreach ($rows as $row) { $row['create_datetime'] = $row['create_timestamp']; unset($row['expires']); $api_tokens_model->insert($row, 2); } // remove old table $model->exec("DROP TABLE wa_contact_tokens"); } catch (waDbException $e) { } // remove old files $path = $this->getAppPath('lib/models/waContactTokens.model.php'); if (file_exists($path)) { waFiles::delete($path); } // create new file api.php in root path
protected function checkToken() { $token = waRequest::request('access_token'); if ($token) { $tokens_model = new waApiTokensModel(); $data = $tokens_model->getById($token); if ($data) { if ($data['expires'] && strtotime($data['expires']) < time()) { throw new waAPIException('invalid_token', 'Access token has expired', 401); } // auth user wa()->setUser(new waUser($data['contact_id'])); return $data; } throw new waAPIException('invalid_token', 'Invalid access token', 401); } throw new waAPIException('invalid_request', 'Required parameter is missing: access_token', 400); }