]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/apignusocialoauthdatastore.php
Misses this file to merge. I like the comments.
[quix0rs-gnu-social.git] / lib / apignusocialoauthdatastore.php
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
20 if (!defined('GNUSOCIAL')) { exit(1); }
21
22 require_once 'OAuth.php';
23
24 /**
25  * @fixme class doc
26  */
27 class ApiGNUsocialOAuthDataStore extends OAuthDataStore
28 {
29     function lookup_consumer($consumerKey)
30     {
31         $con = Consumer::getKV('consumer_key', $consumerKey);
32
33         if (!$con instanceof Consumer) {
34
35             // Create an anon consumer and anon application if one
36             // doesn't exist already
37             if ($consumerKey == 'anonymous') {
38
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();
44
45                 $result = $con->insert();
46                 if (!$result) {
47                     // TRANS: Server error displayed when trying to create an anynymous OAuth consumer.
48                     $this->serverError(_('Could not create anonymous consumer.'));
49                 }
50
51                 $app = Oauth_application::getByConsumerKey('anonymous');
52
53                 if (!$app) {
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();
67
68                     $id = $app->insert();
69
70                     if (!$id) {
71                         // TRANS: Server error displayed when trying to create an anynymous OAuth application.
72                         $this->serverError(_("Could not create anonymous OAuth application."));
73                     }
74                 }
75             } else {
76                 return null;
77             }
78         }
79
80         return new OAuthConsumer(
81             $con->consumer_key,
82             $con->consumer_secret
83         );
84     }
85
86     function getAppByRequestToken($token_key)
87     {
88         // Look up the full req token
89         $req_token = $this->lookup_token(
90             null,
91             'request',
92             $token_key
93         );
94
95         if (empty($req_token)) {
96             common_debug("Couldn't get request token from oauth datastore");
97             return null;
98         }
99
100         // Look up the full Token
101         $token = new Token();
102         $token->tok = $req_token->key;
103         $result = $token->find(true);
104
105         if (empty($result)) {
106             common_debug('Couldn\'t find req token in the token table.');
107             return null;
108         }
109
110         // Look up the app
111         $app = new Oauth_application();
112         $app->consumer_key = $token->consumer_key;
113         $result = $app->find(true);
114
115         if (!empty($result)) {
116             return $app;
117         } else {
118             common_debug("Couldn't find the app!");
119             return null;
120         }
121     }
122
123     function new_access_token($token, $consumer, $verifier = null)
124     {
125         common_debug(
126             sprintf(
127                 "New access token from request token %s, consumer %s and verifier %s ",
128                 $token,
129                 $consumer,
130                 $verifier
131             ),
132             __FILE__
133         );
134
135         $rt = new Token();
136
137         $rt->consumer_key = $consumer->key;
138         $rt->tok          = $token->key;
139         $rt->type         = 0; // request
140
141         $app = Oauth_application::getByConsumerKey($consumer->key);
142         assert(!empty($app));
143
144         if ($rt->find(true) && $rt->state == 1 && $rt->verifier == $verifier) { // authorized
145
146             common_debug('Request token found.', __FILE__);
147
148             // find the app and profile associated with this token
149             $tokenAssoc = Oauth_token_association::getKV('token', $rt->tok);
150
151             if (!$tokenAssoc) {
152                 throw new Exception(
153                     // TRANS: Exception thrown when no token association could be found.
154                     _('Could not find a profile and application associated with the request token.')
155                 );
156             }
157
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
162             // machine.
163
164             $appUser = new Oauth_application_user();
165
166             $appUser->application_id = $app->id;
167             $appUser->profile_id     = $tokenAssoc->profile_id;
168
169             $result = $appUser->find(true);
170
171             if (!empty($result)) {
172
173                 common_log(LOG_INFO,
174                      sprintf(
175                         "Existing access token found for application %s, profile %s.",
176                         $app->id,
177                         $tokenAssoc->profile_id
178                      )
179                 );
180
181                 $at = null;
182
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.
193
194                 if ($appUser->access_type == 0) {
195
196                     $at = $this->generateNewAccessToken($consumer, $rt, $verifier);
197                     $this->updateAppUser($appUser, $app, $at);
198
199                 } else {
200
201                     $at = new Token();
202
203                     // fetch the full access token
204                     $at->consumer_key = $consumer->key;
205                     $at->tok          = $appUser->token;
206
207                     $result = $at->find(true);
208
209                     if (!$result) {
210                         throw new Exception(
211                             // TRANS: Exception thrown when no access token can be issued.
212                             _('Could not issue access token.')
213                         );
214                     }
215                 }
216
217                 // Yay, we can re-issue the access token
218                 return new OAuthToken($at->tok, $at->secret);
219
220             } else {
221
222                common_log(LOG_INFO,
223                     sprintf(
224                         "Creating new access token for application %s, profile %s.",
225                         $app->id,
226                         $tokenAssoc->profile_id
227                      )
228                 );
229
230                 $at = $this->generateNewAccessToken($consumer, $rt, $verifier);
231                 $this->newAppUser($tokenAssoc, $app, $at);
232
233                 // Okay, good
234                 return new OAuthToken($at->tok, $at->secret);
235             }
236
237         } else {
238
239             // the token was not authorized or not verfied
240             common_log(
241                 LOG_INFO,
242                 sprintf(
243                     "API OAuth - Attempt to exchange unauthorized or unverified request token %s for an access token.",
244                      $rt->tok
245                 )
246             );
247             return null;
248         }
249     }
250
251     /*
252      * Generate a new access token and save it to the database
253      *
254      * @param Consumer $consumer the OAuth consumer
255      * @param Token    $rt       the authorized request token
256      * @param string   $verifier the OAuth 1.0a verifier
257      *
258      * @access private
259      *
260      * @return Token   $at       the new access token
261      */
262     private function generateNewAccessToken($consumer, $rt, $verifier)
263     {
264         $at = new Token();
265
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();
273
274         if (!$at->insert()) {
275             $e = $at->_lastError;
276             common_debug('access token "' . $at->tok . '" not inserted: "' . $e->message . '"', __FILE__);
277             return null;
278         } else {
279             common_debug('access token "' . $at->tok . '" inserted', __FILE__);
280             // burn the old one
281             $orig_rt   = clone($rt);
282             $rt->state = 2; // used
283             if (!$rt->update($orig_rt)) {
284                 return null;
285             }
286             common_debug('request token "' . $rt->tok . '" updated', __FILE__);
287         }
288
289         return $at;
290     }
291
292    /*
293     * Add a new app user (Oauth_application_user) record
294     *
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
298     *
299     * @access private
300     *
301     * @return void
302     */
303     private function newAppUser($tokenAssoc, $app, $at)
304     {
305         $appUser = new Oauth_application_user();
306
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();
312
313         $result = $appUser->insert();
314
315         if (!$result) {
316             common_log_db_error($appUser, 'INSERT', __FILE__);
317
318             throw new Exception(
319                 // TRANS: Exception thrown when a database error occurs.
320                 _('Database error inserting OAuth application user.')
321             );
322         }
323     }
324
325    /*
326     * Update an existing app user (Oauth_application_user) record
327     *
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
331     *
332     * @access private
333     *
334     * @return void
335     */
336     private function updateAppUser($appUser, $app, $at)
337     {
338         $original = clone($appUser);
339         $appUser->access_type = $app->access_type;
340         $appUser->token       = $at->tok;
341
342         $result = $appUser->update($original);
343
344         if (!$result) {
345             common_log_db_error($appUser, 'UPDATE', __FILE__);
346             throw new Exception(
347                 // TRANS: Exception thrown when a database error occurs.
348                 _('Database error updating OAuth application user.')
349             );
350         }
351     }
352
353     /**
354      * Revoke specified access token
355      *
356      * Revokes the token specified by $token_key.
357      * Throws exceptions in case of error.
358      *
359      * @param string $token_key the token to be revoked
360      * @param int    $type      type of token (0 = req, 1 = access)
361      *
362      * @access public
363      *
364      * @return void
365      */
366     public function revoke_token($token_key, $type = 0) {
367         $rt        = new Token();
368         $rt->tok   = $token_key;
369         $rt->type  = $type;
370         $rt->state = 0;
371
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.'));
375         }
376
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.'));
380         }
381     }
382
383     /*
384      * Create a new request token. Overrided to support OAuth 1.0a callback
385      *
386      * @param OAuthConsumer $consumer the OAuth Consumer for this token
387      * @param string        $callback the verified OAuth callback URL
388      *
389      * @return OAuthToken   $token a new unauthorized OAuth request token
390      */
391     function new_request_token($consumer, $callback)
392     {
393         $t = new Token();
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;
400
401         if ($callback === 'oob') {
402             // six digit pin
403             $t->verifier = mt_rand(0, 9999999);
404         } else {
405             $t->verifier = common_random_hexstr(8);
406         }
407
408         $t->created = common_sql_now();
409         if (!$t->insert()) {
410             return null;
411         } else {
412             return new OAuthToken($t->tok, $t->secret);
413         }
414     }
415
416     /**
417      * Authorize specified OAuth token
418      *
419      * Authorizes the authorization token specified by $token_key.
420      * Throws exceptions in case of error.
421      *
422      * @param string $token_key The token to be authorized
423      *
424      * @access public
425      **/
426     public function authorize_token($token_key) {
427         $rt = new Token();
428         $rt->tok = $token_key;
429         $rt->type = 0;
430         $rt->state = 0;
431         if (!$rt->find(true)) {
432             throw new Exception('Tried to authorize unknown token');
433         }
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');
438         }
439     }
440
441     /**
442      *
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
447      *
448      * @param type $consumer
449      * @param type $token
450      * @param type $nonce
451      * @param type $timestamp
452      * @return type
453      */
454     function lookup_nonce($consumer, $token, $nonce, $timestamp)
455     {
456         $n = new Nonce();
457         $n->consumer_key = $consumer->key;
458         $n->ts = common_sql_date($timestamp);
459         $n->nonce = $nonce;
460         if ($n->find(true)) {
461             return true;
462         } else {
463             $n->created = common_sql_now();
464             $n->insert();
465             return false;
466         }
467     }
468
469     /**
470      *
471      * @param type $consumer
472      * @param type $token_type
473      * @param type $token_key
474      * @return OAuthToken
475      */
476     function lookup_token($consumer, $token_type, $token_key)
477     {
478         $t = new Token();
479         if (!is_null($consumer)) {
480             $t->consumer_key = $consumer->key;
481         }
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);
486         } else {
487             return null;
488         }
489     }
490
491     /**
492      *
493      * @param type $token_key
494      * @return Token 
495      */
496     function getTokenByKey($token_key)
497     {
498         $t = new Token();
499         $t->tok = $token_key;
500         if ($t->find(true)) {
501             return $t;
502         } else {
503             return null;
504         }
505     }
506 }