apignusocialoauthdatastore.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. <?php
  2. /*
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2008-2011, StatusNet, Inc.
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. if (!defined('GNUSOCIAL')) { exit(1); }
  20. require_once 'OAuth.php';
  21. /**
  22. * @fixme class doc
  23. */
  24. class ApiGNUsocialOAuthDataStore extends OAuthDataStore
  25. {
  26. function lookup_consumer($consumerKey)
  27. {
  28. $con = Consumer::getKV('consumer_key', $consumerKey);
  29. if (!$con instanceof Consumer) {
  30. // Create an anon consumer and anon application if one
  31. // doesn't exist already
  32. if ($consumerKey == 'anonymous') {
  33. common_debug("API OAuth - creating anonymous consumer");
  34. $con = new Consumer();
  35. $con->consumer_key = $consumerKey;
  36. $con->consumer_secret = $consumerKey;
  37. $con->created = common_sql_now();
  38. $result = $con->insert();
  39. if (!$result) {
  40. // TRANS: Server error displayed when trying to create an anynymous OAuth consumer.
  41. $this->serverError(_('Could not create anonymous consumer.'));
  42. }
  43. $app = Oauth_application::getByConsumerKey('anonymous');
  44. if (!$app) {
  45. common_debug("API OAuth - creating anonymous application");
  46. $app = new OAuth_application();
  47. $app->owner = 1; // XXX: What to do here?
  48. $app->consumer_key = $con->consumer_key;
  49. $app->name = 'anonymous';
  50. $app->icon = 'default-avatar-stream.png'; // XXX: Fix this!
  51. $app->description = "An anonymous application";
  52. // XXX: allow the user to set the access type when
  53. // authorizing? Currently we default to r+w for anonymous
  54. // OAuth client applications
  55. $app->access_type = 3; // read + write
  56. $app->type = 2; // desktop
  57. $app->created = common_sql_now();
  58. $id = $app->insert();
  59. if (!$id) {
  60. // TRANS: Server error displayed when trying to create an anynymous OAuth application.
  61. $this->serverError(_("Could not create anonymous OAuth application."));
  62. }
  63. }
  64. } else {
  65. return null;
  66. }
  67. }
  68. return new OAuthConsumer(
  69. $con->consumer_key,
  70. $con->consumer_secret
  71. );
  72. }
  73. function getAppByRequestToken($token_key)
  74. {
  75. // Look up the full req token
  76. $req_token = $this->lookup_token(
  77. null,
  78. 'request',
  79. $token_key
  80. );
  81. if (empty($req_token)) {
  82. common_debug("Couldn't get request token from oauth datastore");
  83. return null;
  84. }
  85. // Look up the full Token
  86. $token = new Token();
  87. $token->tok = $req_token->key;
  88. $result = $token->find(true);
  89. if (empty($result)) {
  90. common_debug('Couldn\'t find req token in the token table.');
  91. return null;
  92. }
  93. // Look up the app
  94. $app = new Oauth_application();
  95. $app->consumer_key = $token->consumer_key;
  96. $result = $app->find(true);
  97. if (!empty($result)) {
  98. return $app;
  99. } else {
  100. common_debug("Couldn't find the app!");
  101. return null;
  102. }
  103. }
  104. function new_access_token($token, $consumer, $verifier = null)
  105. {
  106. common_debug(
  107. sprintf(
  108. "New access token from request token %s, consumer %s and verifier %s ",
  109. $token,
  110. $consumer,
  111. $verifier
  112. ),
  113. __FILE__
  114. );
  115. $rt = new Token();
  116. $rt->consumer_key = $consumer->key;
  117. $rt->tok = $token->key;
  118. $rt->type = 0; // request
  119. $app = Oauth_application::getByConsumerKey($consumer->key);
  120. assert(!empty($app));
  121. if ($rt->find(true) && $rt->state == 1 && $rt->verifier == $verifier) { // authorized
  122. common_debug('Request token found.', __FILE__);
  123. // find the app and profile associated with this token
  124. $tokenAssoc = Oauth_token_association::getKV('token', $rt->tok);
  125. if (!$tokenAssoc) {
  126. throw new Exception(
  127. // TRANS: Exception thrown when no token association could be found.
  128. _('Could not find a profile and application associated with the request token.')
  129. );
  130. }
  131. // Check to see if we have previously issued an access token for
  132. // this application and profile; if so we can just return the
  133. // existing access token. That seems to be the best practice. It
  134. // makes it so users only have to authorize the app once per
  135. // machine.
  136. $appUser = new Oauth_application_user();
  137. $appUser->application_id = $app->id;
  138. $appUser->profile_id = $tokenAssoc->profile_id;
  139. $result = $appUser->find(true);
  140. if (!empty($result)) {
  141. common_log(LOG_INFO,
  142. sprintf(
  143. "Existing access token found for application %s, profile %s.",
  144. $app->id,
  145. $tokenAssoc->profile_id
  146. )
  147. );
  148. $at = null;
  149. // Special case: we used to store request tokens in the
  150. // Oauth_application_user record, and the access_type would
  151. // always be 0 (no access) as a failsafe until an access
  152. // token was issued and replaced the request token. There could
  153. // be a few old Oauth_application_user records storing request
  154. // tokens still around, and we don't want to accidentally
  155. // return a useless request token instead of a new access
  156. // token. So if we find one, we generate a new access token
  157. // and update the existing Oauth_application_user record before
  158. // returning the new access token. This should be rare.
  159. if ($appUser->access_type == 0) {
  160. $at = $this->generateNewAccessToken($consumer, $rt, $verifier);
  161. $this->updateAppUser($appUser, $app, $at);
  162. } else {
  163. $at = new Token();
  164. // fetch the full access token
  165. $at->consumer_key = $consumer->key;
  166. $at->tok = $appUser->token;
  167. $result = $at->find(true);
  168. if (!$result) {
  169. throw new Exception(
  170. // TRANS: Exception thrown when no access token can be issued.
  171. _('Could not issue access token.')
  172. );
  173. }
  174. }
  175. // Yay, we can re-issue the access token
  176. return new OAuthToken($at->tok, $at->secret);
  177. } else {
  178. common_log(LOG_INFO,
  179. sprintf(
  180. "Creating new access token for application %s, profile %s.",
  181. $app->id,
  182. $tokenAssoc->profile_id
  183. )
  184. );
  185. $at = $this->generateNewAccessToken($consumer, $rt, $verifier);
  186. $this->newAppUser($tokenAssoc, $app, $at);
  187. // Okay, good
  188. return new OAuthToken($at->tok, $at->secret);
  189. }
  190. } else {
  191. // the token was not authorized or not verfied
  192. common_log(
  193. LOG_INFO,
  194. sprintf(
  195. "API OAuth - Attempt to exchange unauthorized or unverified request token %s for an access token.",
  196. $rt->tok
  197. )
  198. );
  199. return null;
  200. }
  201. }
  202. /*
  203. * Generate a new access token and save it to the database
  204. *
  205. * @param Consumer $consumer the OAuth consumer
  206. * @param Token $rt the authorized request token
  207. * @param string $verifier the OAuth 1.0a verifier
  208. *
  209. * @access private
  210. *
  211. * @return Token $at the new access token
  212. */
  213. private function generateNewAccessToken($consumer, $rt, $verifier)
  214. {
  215. $at = new Token();
  216. $at->consumer_key = $consumer->key;
  217. $at->tok = common_random_hexstr(16);
  218. $at->secret = common_random_hexstr(16);
  219. $at->type = 1; // access
  220. $at->verifier = $verifier;
  221. $at->verified_callback = $rt->verified_callback; // 1.0a
  222. $at->created = common_sql_now();
  223. if (!$at->insert()) {
  224. $e = $at->_lastError;
  225. common_debug('access token "' . $at->tok . '" not inserted: "' . $e->message . '"', __FILE__);
  226. return null;
  227. } else {
  228. common_debug('access token "' . $at->tok . '" inserted', __FILE__);
  229. // burn the old one
  230. $orig_rt = clone($rt);
  231. $rt->state = 2; // used
  232. if (!$rt->update($orig_rt)) {
  233. return null;
  234. }
  235. common_debug('request token "' . $rt->tok . '" updated', __FILE__);
  236. }
  237. return $at;
  238. }
  239. /*
  240. * Add a new app user (Oauth_application_user) record
  241. *
  242. * @param Oauth_token_association $tokenAssoc token-to-app association
  243. * @param Oauth_application $app the OAuth client app
  244. * @param Token $at the access token
  245. *
  246. * @access private
  247. *
  248. * @return void
  249. */
  250. private function newAppUser($tokenAssoc, $app, $at)
  251. {
  252. $appUser = new Oauth_application_user();
  253. $appUser->profile_id = $tokenAssoc->profile_id;
  254. $appUser->application_id = $app->id;
  255. $appUser->access_type = $app->access_type;
  256. $appUser->token = $at->tok;
  257. $appUser->created = common_sql_now();
  258. $result = $appUser->insert();
  259. if (!$result) {
  260. common_log_db_error($appUser, 'INSERT', __FILE__);
  261. throw new Exception(
  262. // TRANS: Exception thrown when a database error occurs.
  263. _('Database error inserting OAuth application user.')
  264. );
  265. }
  266. }
  267. /*
  268. * Update an existing app user (Oauth_application_user) record
  269. *
  270. * @param Oauth_application_user $appUser existing app user rec
  271. * @param Oauth_application $app the OAuth client app
  272. * @param Token $at the access token
  273. *
  274. * @access private
  275. *
  276. * @return void
  277. */
  278. private function updateAppUser($appUser, $app, $at)
  279. {
  280. $original = clone($appUser);
  281. $appUser->access_type = $app->access_type;
  282. $appUser->token = $at->tok;
  283. $result = $appUser->update($original);
  284. if (!$result) {
  285. common_log_db_error($appUser, 'UPDATE', __FILE__);
  286. throw new Exception(
  287. // TRANS: Exception thrown when a database error occurs.
  288. _('Database error updating OAuth application user.')
  289. );
  290. }
  291. }
  292. /**
  293. * Revoke specified access token
  294. *
  295. * Revokes the token specified by $token_key.
  296. * Throws exceptions in case of error.
  297. *
  298. * @param string $token_key the token to be revoked
  299. * @param int $type type of token (0 = req, 1 = access)
  300. *
  301. * @access public
  302. *
  303. * @return void
  304. */
  305. public function revoke_token($token_key, $type = 0) {
  306. $rt = new Token();
  307. $rt->tok = $token_key;
  308. $rt->type = $type;
  309. $rt->state = 0;
  310. if (!$rt->find(true)) {
  311. // TRANS: Exception thrown when an attempt is made to revoke an unknown token.
  312. throw new Exception(_('Tried to revoke unknown token.'));
  313. }
  314. if (!$rt->delete()) {
  315. // TRANS: Exception thrown when an attempt is made to remove a revoked token.
  316. throw new Exception(_('Failed to delete revoked token.'));
  317. }
  318. }
  319. /*
  320. * Create a new request token. Overrided to support OAuth 1.0a callback
  321. *
  322. * @param OAuthConsumer $consumer the OAuth Consumer for this token
  323. * @param string $callback the verified OAuth callback URL
  324. *
  325. * @return OAuthToken $token a new unauthorized OAuth request token
  326. */
  327. function new_request_token($consumer, $callback)
  328. {
  329. $t = new Token();
  330. $t->consumer_key = $consumer->key;
  331. $t->tok = common_random_hexstr(16);
  332. $t->secret = common_random_hexstr(16);
  333. $t->type = 0; // request
  334. $t->state = 0; // unauthorized
  335. $t->verified_callback = $callback;
  336. if ($callback === 'oob') {
  337. // six digit pin
  338. $t->verifier = mt_rand(0, 9999999);
  339. } else {
  340. $t->verifier = common_random_hexstr(8);
  341. }
  342. $t->created = common_sql_now();
  343. if (!$t->insert()) {
  344. return null;
  345. } else {
  346. return new OAuthToken($t->tok, $t->secret);
  347. }
  348. }
  349. /**
  350. * Authorize specified OAuth token
  351. *
  352. * Authorizes the authorization token specified by $token_key.
  353. * Throws exceptions in case of error.
  354. *
  355. * @param string $token_key The token to be authorized
  356. *
  357. * @access public
  358. **/
  359. public function authorize_token($token_key) {
  360. $rt = new Token();
  361. $rt->tok = $token_key;
  362. $rt->type = 0;
  363. $rt->state = 0;
  364. if (!$rt->find(true)) {
  365. throw new Exception('Tried to authorize unknown token');
  366. }
  367. $orig_rt = clone($rt);
  368. $rt->state = 1; # Authorized but not used
  369. if (!$rt->update($orig_rt)) {
  370. throw new Exception('Failed to authorize token');
  371. }
  372. }
  373. /**
  374. *
  375. * http://oauth.net/core/1.0/#nonce
  376. * "The Consumer SHALL then generate a Nonce value that is unique for
  377. * all requests with that timestamp."
  378. * XXX: It's not clear why the token is here
  379. *
  380. * @param type $consumer
  381. * @param type $token
  382. * @param type $nonce
  383. * @param type $timestamp
  384. * @return type
  385. */
  386. function lookup_nonce($consumer, $token, $nonce, $timestamp)
  387. {
  388. $n = new Nonce();
  389. $n->consumer_key = $consumer->key;
  390. $n->ts = common_sql_date($timestamp);
  391. $n->nonce = $nonce;
  392. if ($n->find(true)) {
  393. return true;
  394. } else {
  395. $n->created = common_sql_now();
  396. $n->insert();
  397. return false;
  398. }
  399. }
  400. /**
  401. *
  402. * @param type $consumer
  403. * @param type $token_type
  404. * @param type $token_key
  405. * @return OAuthToken
  406. */
  407. function lookup_token($consumer, $token_type, $token_key)
  408. {
  409. $t = new Token();
  410. if (!is_null($consumer)) {
  411. $t->consumer_key = $consumer->key;
  412. }
  413. $t->tok = $token_key;
  414. $t->type = ($token_type == 'access') ? 1 : 0;
  415. if ($t->find(true)) {
  416. return new OAuthToken($t->tok, $t->secret);
  417. } else {
  418. return null;
  419. }
  420. }
  421. /**
  422. *
  423. * @param type $token_key
  424. * @return Token
  425. */
  426. function getTokenByKey($token_key)
  427. {
  428. $t = new Token();
  429. $t->tok = $token_key;
  430. if ($t->find(true)) {
  431. return $t;
  432. } else {
  433. return null;
  434. }
  435. }
  436. }