3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011, StatusNet, Inc.
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.
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.
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/>.
20 if (!defined('GNUSOCIAL')) { exit(1); }
22 require_once 'OAuth.php';
27 class ApiGNUsocialOAuthDataStore extends OAuthDataStore
29 function lookup_consumer($consumerKey)
31 $con = Consumer::getKV('consumer_key', $consumerKey);
33 if (!$con instanceof Consumer) {
35 // Create an anon consumer and anon application if one
36 // doesn't exist already
37 if ($consumerKey == 'anonymous') {
39 common_debug("API OAuth - creating anonymous consumer");
40 $con = new Consumer();
41 $con->consumer_key = $consumerKey;
42 $con->consumer_secret = $consumerKey;
43 $con->created = common_sql_now();
45 $result = $con->insert();
47 // TRANS: Server error displayed when trying to create an anynymous OAuth consumer.
48 $this->serverError(_('Could not create anonymous consumer.'));
51 $app = Oauth_application::getByConsumerKey('anonymous');
54 common_debug("API OAuth - creating anonymous application");
55 $app = new OAuth_application();
56 $app->owner = 1; // XXX: What to do here?
57 $app->consumer_key = $con->consumer_key;
58 $app->name = 'anonymous';
59 $app->icon = 'default-avatar-stream.png'; // XXX: Fix this!
60 $app->description = "An anonymous application";
61 // XXX: allow the user to set the access type when
62 // authorizing? Currently we default to r+w for anonymous
63 // OAuth client applications
64 $app->access_type = 3; // read + write
65 $app->type = 2; // desktop
66 $app->created = common_sql_now();
71 // TRANS: Server error displayed when trying to create an anynymous OAuth application.
72 $this->serverError(_("Could not create anonymous OAuth application."));
80 return new OAuthConsumer(
86 function getAppByRequestToken($token_key)
88 // Look up the full req token
89 $req_token = $this->lookup_token(
95 if (empty($req_token)) {
96 common_debug("Couldn't get request token from oauth datastore");
100 // Look up the full Token
101 $token = new Token();
102 $token->tok = $req_token->key;
103 $result = $token->find(true);
105 if (empty($result)) {
106 common_debug('Couldn\'t find req token in the token table.');
111 $app = new Oauth_application();
112 $app->consumer_key = $token->consumer_key;
113 $result = $app->find(true);
115 if (!empty($result)) {
118 common_debug("Couldn't find the app!");
123 function new_access_token($token, $consumer, $verifier = null)
127 "New access token from request token %s, consumer %s and verifier %s ",
137 $rt->consumer_key = $consumer->key;
138 $rt->tok = $token->key;
139 $rt->type = 0; // request
141 $app = Oauth_application::getByConsumerKey($consumer->key);
142 assert(!empty($app));
144 if ($rt->find(true) && $rt->state == 1 && $rt->verifier == $verifier) { // authorized
146 common_debug('Request token found.', __FILE__);
148 // find the app and profile associated with this token
149 $tokenAssoc = Oauth_token_association::getKV('token', $rt->tok);
153 // TRANS: Exception thrown when no token association could be found.
154 _('Could not find a profile and application associated with the request token.')
158 // Check to see if we have previously issued an access token for
159 // this application and profile; if so we can just return the
160 // existing access token. That seems to be the best practice. It
161 // makes it so users only have to authorize the app once per
164 $appUser = new Oauth_application_user();
166 $appUser->application_id = $app->id;
167 $appUser->profile_id = $tokenAssoc->profile_id;
169 $result = $appUser->find(true);
171 if (!empty($result)) {
175 "Existing access token found for application %s, profile %s.",
177 $tokenAssoc->profile_id
183 // Special case: we used to store request tokens in the
184 // Oauth_application_user record, and the access_type would
185 // always be 0 (no access) as a failsafe until an access
186 // token was issued and replaced the request token. There could
187 // be a few old Oauth_application_user records storing request
188 // tokens still around, and we don't want to accidentally
189 // return a useless request token instead of a new access
190 // token. So if we find one, we generate a new access token
191 // and update the existing Oauth_application_user record before
192 // returning the new access token. This should be rare.
194 if ($appUser->access_type == 0) {
196 $at = $this->generateNewAccessToken($consumer, $rt, $verifier);
197 $this->updateAppUser($appUser, $app, $at);
203 // fetch the full access token
204 $at->consumer_key = $consumer->key;
205 $at->tok = $appUser->token;
207 $result = $at->find(true);
211 // TRANS: Exception thrown when no access token can be issued.
212 _('Could not issue access token.')
217 // Yay, we can re-issue the access token
218 return new OAuthToken($at->tok, $at->secret);
224 "Creating new access token for application %s, profile %s.",
226 $tokenAssoc->profile_id
230 $at = $this->generateNewAccessToken($consumer, $rt, $verifier);
231 $this->newAppUser($tokenAssoc, $app, $at);
234 return new OAuthToken($at->tok, $at->secret);
239 // the token was not authorized or not verfied
243 "API OAuth - Attempt to exchange unauthorized or unverified request token %s for an access token.",
252 * Generate a new access token and save it to the database
254 * @param Consumer $consumer the OAuth consumer
255 * @param Token $rt the authorized request token
256 * @param string $verifier the OAuth 1.0a verifier
260 * @return Token $at the new access token
262 private function generateNewAccessToken($consumer, $rt, $verifier)
266 $at->consumer_key = $consumer->key;
267 $at->tok = common_random_hexstr(16);
268 $at->secret = common_random_hexstr(16);
269 $at->type = 1; // access
270 $at->verifier = $verifier;
271 $at->verified_callback = $rt->verified_callback; // 1.0a
272 $at->created = common_sql_now();
274 if (!$at->insert()) {
275 $e = $at->_lastError;
276 common_debug('access token "' . $at->tok . '" not inserted: "' . $e->message . '"', __FILE__);
279 common_debug('access token "' . $at->tok . '" inserted', __FILE__);
281 $orig_rt = clone($rt);
282 $rt->state = 2; // used
283 if (!$rt->update($orig_rt)) {
286 common_debug('request token "' . $rt->tok . '" updated', __FILE__);
293 * Add a new app user (Oauth_application_user) record
295 * @param Oauth_token_association $tokenAssoc token-to-app association
296 * @param Oauth_application $app the OAuth client app
297 * @param Token $at the access token
303 private function newAppUser($tokenAssoc, $app, $at)
305 $appUser = new Oauth_application_user();
307 $appUser->profile_id = $tokenAssoc->profile_id;
308 $appUser->application_id = $app->id;
309 $appUser->access_type = $app->access_type;
310 $appUser->token = $at->tok;
311 $appUser->created = common_sql_now();
313 $result = $appUser->insert();
316 common_log_db_error($appUser, 'INSERT', __FILE__);
319 // TRANS: Exception thrown when a database error occurs.
320 _('Database error inserting OAuth application user.')
326 * Update an existing app user (Oauth_application_user) record
328 * @param Oauth_application_user $appUser existing app user rec
329 * @param Oauth_application $app the OAuth client app
330 * @param Token $at the access token
336 private function updateAppUser($appUser, $app, $at)
338 $original = clone($appUser);
339 $appUser->access_type = $app->access_type;
340 $appUser->token = $at->tok;
342 $result = $appUser->update($original);
345 common_log_db_error($appUser, 'UPDATE', __FILE__);
347 // TRANS: Exception thrown when a database error occurs.
348 _('Database error updating OAuth application user.')
354 * Revoke specified access token
356 * Revokes the token specified by $token_key.
357 * Throws exceptions in case of error.
359 * @param string $token_key the token to be revoked
360 * @param int $type type of token (0 = req, 1 = access)
366 public function revoke_token($token_key, $type = 0) {
368 $rt->tok = $token_key;
372 if (!$rt->find(true)) {
373 // TRANS: Exception thrown when an attempt is made to revoke an unknown token.
374 throw new Exception(_('Tried to revoke unknown token.'));
377 if (!$rt->delete()) {
378 // TRANS: Exception thrown when an attempt is made to remove a revoked token.
379 throw new Exception(_('Failed to delete revoked token.'));
384 * Create a new request token. Overrided to support OAuth 1.0a callback
386 * @param OAuthConsumer $consumer the OAuth Consumer for this token
387 * @param string $callback the verified OAuth callback URL
389 * @return OAuthToken $token a new unauthorized OAuth request token
391 function new_request_token($consumer, $callback)
394 $t->consumer_key = $consumer->key;
395 $t->tok = common_random_hexstr(16);
396 $t->secret = common_random_hexstr(16);
397 $t->type = 0; // request
398 $t->state = 0; // unauthorized
399 $t->verified_callback = $callback;
401 if ($callback === 'oob') {
403 $t->verifier = mt_rand(0, 9999999);
405 $t->verifier = common_random_hexstr(8);
408 $t->created = common_sql_now();
412 return new OAuthToken($t->tok, $t->secret);
417 * Authorize specified OAuth token
419 * Authorizes the authorization token specified by $token_key.
420 * Throws exceptions in case of error.
422 * @param string $token_key The token to be authorized
426 public function authorize_token($token_key) {
428 $rt->tok = $token_key;
431 if (!$rt->find(true)) {
432 throw new Exception('Tried to authorize unknown token');
434 $orig_rt = clone($rt);
435 $rt->state = 1; # Authorized but not used
436 if (!$rt->update($orig_rt)) {
437 throw new Exception('Failed to authorize token');
443 * http://oauth.net/core/1.0/#nonce
444 * "The Consumer SHALL then generate a Nonce value that is unique for
445 * all requests with that timestamp."
446 * XXX: It's not clear why the token is here
448 * @param type $consumer
451 * @param type $timestamp
454 function lookup_nonce($consumer, $token, $nonce, $timestamp)
457 $n->consumer_key = $consumer->key;
458 $n->ts = common_sql_date($timestamp);
460 if ($n->find(true)) {
463 $n->created = common_sql_now();
471 * @param type $consumer
472 * @param type $token_type
473 * @param type $token_key
476 function lookup_token($consumer, $token_type, $token_key)
479 if (!is_null($consumer)) {
480 $t->consumer_key = $consumer->key;
482 $t->tok = $token_key;
483 $t->type = ($token_type == 'access') ? 1 : 0;
484 if ($t->find(true)) {
485 return new OAuthToken($t->tok, $t->secret);
493 * @param type $token_key
496 function getTokenByKey($token_key)
499 $t->tok = $token_key;
500 if ($t->find(true)) {