]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/apioauthstore.php
Use a new table (oauth_token_association) to associate authorized
[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                     $this->serverError(_("Could not create anonymous consumer."));
45                 }
46
47                 $app = Oauth_application::getByConsumerKey('anonymous');
48
49                 if (!$app) {
50
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                         $this->serverError(_("Could not create anonymous OAuth application."));
69                     }
70                 }
71             } else {
72                 return null;
73             }
74         }
75
76         return new OAuthConsumer(
77             $con->consumer_key,
78             $con->consumer_secret
79         );
80     }
81
82     function getAppByRequestToken($token_key)
83     {
84         // Look up the full req token
85         $req_token = $this->lookup_token(
86             null,
87             'request',
88             $token_key
89         );
90
91         if (empty($req_token)) {
92             common_debug("couldn't get request token from oauth datastore");
93             return null;
94         }
95
96         // Look up the full Token
97         $token = new Token();
98         $token->tok = $req_token->key;
99         $result = $token->find(true);
100
101         if (empty($result)) {
102             common_debug('Couldn\'t find req token in the token table.');
103             return null;
104         }
105
106         // Look up the app
107         $app = new Oauth_application();
108         $app->consumer_key = $token->consumer_key;
109         $result = $app->find(true);
110
111         if (!empty($result)) {
112             return $app;
113         } else {
114             common_debug("Couldn't find the app!");
115             return null;
116         }
117     }
118
119     function new_access_token($token, $consumer, $verifier)
120     {
121         common_debug(
122             sprintf(
123                 "New access token from request token %s, consumer %s and verifier %s ",
124                 $token,
125                 $consumer,
126                 $verifier
127             ),
128             __FILE__
129         );
130
131         $rt = new Token();
132
133         $rt->consumer_key = $consumer->key;
134         $rt->tok          = $token->key;
135         $rt->type         = 0; // request
136
137         $app = Oauth_application::getByConsumerKey($consumer->key);
138         assert(!empty($app));
139
140         if ($rt->find(true) && $rt->state == 1 && $rt->verifier == $verifier) { // authorized
141
142             common_debug('Request token found.', __FILE__);
143
144             // find the app and profile associated with this token
145
146             $tokenAssoc = OAuth_token_association::staticGet('token', $rt->tok);
147
148             if (!$tokenAssoc) {
149                 throw new Exception(
150                     _('Could not find a profile and application associated with the request token.')
151                 );
152             }
153
154             // check to see if we have previously issued an access token for this application
155             // and profile
156
157             $appUser = new Oauth_application_user();
158
159             $appUser->application_id = $app->id;
160             $appUser->profile_id     = $tokenAssoc->profile_id;
161
162             $result = $appUser->find(true);
163
164             if (!empty($result)) {
165
166                 common_log(LOG_INFO,
167                      sprintf(
168                         "Existing access token found for application %s, profile %s.",
169                         $app->id,
170                         $tokenAssoc->profile_id
171                      )
172                 );
173
174                 $at = new Token();
175
176                 // fetch the full access token
177                 $at->consumer_key = $consumer->key;
178                 $at->tok          = $appUser->token;
179
180                 $result = $at->find(true);
181
182                 if (!$result) {
183                     throw new Exception(
184                         _('Could not issue access token.')
185                     );
186                 }
187
188                 // Yay, we can re-issue the access token
189                 return new OAuthToken($at->tok, $at->secret);
190
191             } else {
192
193                common_log(LOG_INFO,
194                     sprintf(
195                         "Creating new access token for application %s, profile %s.",
196                         $app->id,
197                         $tokenAssoc->profile_id
198                      )
199                 );
200
201                 // make a brand new access token
202                 $at = new Token();
203
204                 $at->consumer_key      = $consumer->key;
205                 $at->tok               = common_good_rand(16);
206                 $at->secret            = common_good_rand(16);
207                 $at->type              = 1; // access
208                 $at->verifier          = $verifier;
209                 $at->verified_callback = $rt->verified_callback; // 1.0a
210                 $at->created           = common_sql_now();
211
212                 if (!$at->insert()) {
213                     $e = $at->_lastError;
214                     common_debug('access token "' . $at->tok . '" not inserted: "' . $e->message . '"', __FILE__);
215                     return null;
216                 } else {
217                     common_debug('access token "' . $at->tok . '" inserted', __FILE__);
218                     // burn the old one
219                     $orig_rt   = clone($rt);
220                     $rt->state = 2; // used
221                     if (!$rt->update($orig_rt)) {
222                         return null;
223                     }
224                     common_debug('request token "' . $rt->tok . '" updated', __FILE__);
225                 }
226
227                 // insert a new Oauth_application_user record w/access token
228                 $appUser = new Oauth_application_user();
229
230                 $appUser->profile_id     = $tokenAssoc->profile_id;;
231                 $appUser->application_id = $app->id;
232                 $appUser->access_type    = $app->access_type;
233                 $appUser->token          = $at->tok;
234                 $appUser->created        = common_sql_now();
235
236                 $result = $appUser->insert();
237
238                 if (!$result) {
239                     common_log_db_error($appUser, 'INSERT', __FILE__);
240                     $this->serverError(_('Database error inserting OAuth application user.'));
241                 }
242
243                 // Okay, good
244                 return new OAuthToken($at->tok, $at->secret);
245             }
246
247         } else {
248
249             // the token was not authorized or not verfied
250             common_log(
251                 LOG_INFO,
252                 sprintf(
253                     "API OAuth - Attempt to exchange unauthorized or unverified request token %s for an access token.",
254                      $rt->tok
255                 )
256             );
257             return null;
258         }
259     }
260
261     /**
262      * Revoke specified access token
263      *
264      * Revokes the token specified by $token_key.
265      * Throws exceptions in case of error.
266      *
267      * @param string $token_key the token to be revoked
268      * @param int    $type      type of token (0 = req, 1 = access)
269      *
270      * @access public
271      *
272      * @return void
273      */
274     public function revoke_token($token_key, $type = 0) {
275         $rt        = new Token();
276         $rt->tok   = $token_key;
277         $rt->type  = $type;
278         $rt->state = 0;
279
280         if (!$rt->find(true)) {
281             // TRANS: Exception thrown when an attempt is made to revoke an unknown token.
282             throw new Exception(_('Tried to revoke unknown token.'));
283         }
284
285         if (!$rt->delete()) {
286             // TRANS: Exception thrown when an attempt is made to remove a revoked token.
287             throw new Exception(_('Failed to delete revoked token.'));
288         }
289     }
290
291     /*
292      * Create a new request token. Overrided to support OAuth 1.0a callback
293      *
294      * @param OAuthConsumer $consumer the OAuth Consumer for this token
295      * @param string        $callback the verified OAuth callback URL
296      *
297      * @return OAuthToken   $token a new unauthorized OAuth request token
298      */
299
300     function new_request_token($consumer, $callback)
301     {
302         $t = new Token();
303         $t->consumer_key = $consumer->key;
304         $t->tok = common_good_rand(16);
305         $t->secret = common_good_rand(16);
306         $t->type = 0; // request
307         $t->state = 0; // unauthorized
308         $t->verified_callback = $callback;
309
310         if ($callback === 'oob') {
311             // six digit pin
312             $t->verifier = mt_rand(0, 9999999);
313         } else {
314             $t->verifier = common_good_rand(8);
315         }
316
317         $t->created = DB_DataObject_Cast::dateTime();
318         if (!$t->insert()) {
319             return null;
320         } else {
321             return new OAuthToken($t->tok, $t->secret);
322         }
323     }
324
325
326 }