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