]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/apioauthstore.php
Fix syntax error
[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
52                     common_debug("API OAuth - creating anonymous application");
53                     $app               = new OAuth_application();
54                     $app->owner        = 1; // XXX: What to do here?
55                     $app->consumer_key = $con->consumer_key;
56                     $app->name         = 'anonymous';
57                     $app->icon         = 'default-avatar-stream.png'; // XXX: Fix this!
58                     $app->description  = "An anonymous application";
59                     // XXX: allow the user to set the access type when
60                     // authorizing? Currently we default to r+w for anonymous
61                     // OAuth client applications
62                     $app->access_type  = 3; // read + write
63                     $app->type         = 2; // desktop
64                     $app->created      = common_sql_now();
65
66                     $id = $app->insert();
67
68                     if (!$id) {
69                                                 // TRANS: Server error displayed when trying to create an anynymous OAuth application.
70                         $this->serverError(_("Could not create anonymous OAuth application."));
71                     }
72                 }
73             } else {
74                 return null;
75             }
76         }
77
78         return new OAuthConsumer(
79             $con->consumer_key,
80             $con->consumer_secret
81         );
82     }
83
84     function getAppByRequestToken($token_key)
85     {
86         // Look up the full req token
87         $req_token = $this->lookup_token(
88             null,
89             'request',
90             $token_key
91         );
92
93         if (empty($req_token)) {
94             common_debug("couldn't get request token from oauth datastore");
95             return null;
96         }
97
98         // Look up the full Token
99         $token = new Token();
100         $token->tok = $req_token->key;
101         $result = $token->find(true);
102
103         if (empty($result)) {
104             common_debug('Couldn\'t find req token in the token table.');
105             return null;
106         }
107
108         // Look up the app
109         $app = new Oauth_application();
110         $app->consumer_key = $token->consumer_key;
111         $result = $app->find(true);
112
113         if (!empty($result)) {
114             return $app;
115         } else {
116             common_debug("Couldn't find the app!");
117             return null;
118         }
119     }
120
121     function new_access_token($token, $consumer, $verifier)
122     {
123         common_debug(
124             sprintf(
125                 "New access token from request token %s, consumer %s and verifier %s ",
126                 $token,
127                 $consumer,
128                 $verifier
129             ),
130             __FILE__
131         );
132
133         $rt = new Token();
134
135         $rt->consumer_key = $consumer->key;
136         $rt->tok          = $token->key;
137         $rt->type         = 0; // request
138
139         $app = Oauth_application::getByConsumerKey($consumer->key);
140         assert(!empty($app));
141
142         if ($rt->find(true) && $rt->state == 1 && $rt->verifier == $verifier) { // authorized
143
144             common_debug('Request token found.', __FILE__);
145
146             // find the app and profile associated with this token
147             $tokenAssoc = Oauth_token_association::staticGet('token', $rt->tok);
148
149             if (!$tokenAssoc) {
150                 throw new Exception(
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 this application
156             // and profile
157
158             $appUser = new Oauth_application_user();
159
160             $appUser->application_id = $app->id;
161             $appUser->profile_id     = $tokenAssoc->profile_id;
162
163             $result = $appUser->find(true);
164
165             if (!empty($result)) {
166
167                 common_log(LOG_INFO,
168                      sprintf(
169                         "Existing access token found for application %s, profile %s.",
170                         $app->id,
171                         $tokenAssoc->profile_id
172                      )
173                 );
174
175                 $at = new Token();
176
177                 // fetch the full access token
178                 $at->consumer_key = $consumer->key;
179                 $at->tok          = $appUser->token;
180
181                 $result = $at->find(true);
182
183                 if (!$result) {
184                     throw new Exception(
185                         _('Could not issue access token.')
186                     );
187                 }
188
189                 // Yay, we can re-issue the access token
190                 return new OAuthToken($at->tok, $at->secret);
191
192             } else {
193
194                common_log(LOG_INFO,
195                     sprintf(
196                         "Creating new access token for application %s, profile %s.",
197                         $app->id,
198                         $tokenAssoc->profile_id
199                      )
200                 );
201
202                 // make a brand new access token
203                 $at = new Token();
204
205                 $at->consumer_key      = $consumer->key;
206                 $at->tok               = common_good_rand(16);
207                 $at->secret            = common_good_rand(16);
208                 $at->type              = 1; // access
209                 $at->verifier          = $verifier;
210                 $at->verified_callback = $rt->verified_callback; // 1.0a
211                 $at->created           = common_sql_now();
212
213                 if (!$at->insert()) {
214                     $e = $at->_lastError;
215                     common_debug('access token "' . $at->tok . '" not inserted: "' . $e->message . '"', __FILE__);
216                     return null;
217                 } else {
218                     common_debug('access token "' . $at->tok . '" inserted', __FILE__);
219                     // burn the old one
220                     $orig_rt   = clone($rt);
221                     $rt->state = 2; // used
222                     if (!$rt->update($orig_rt)) {
223                         return null;
224                     }
225                     common_debug('request token "' . $rt->tok . '" updated', __FILE__);
226                 }
227
228                 // insert a new Oauth_application_user record w/access token
229                 $appUser = new Oauth_application_user();
230
231                 $appUser->profile_id     = $tokenAssoc->profile_id;;
232                 $appUser->application_id = $app->id;
233                 $appUser->access_type    = $app->access_type;
234                 $appUser->token          = $at->tok;
235                 $appUser->created        = common_sql_now();
236
237                 $result = $appUser->insert();
238
239                 if (!$result) {
240                     common_log_db_error($appUser, 'INSERT', __FILE__);
241                     $this->serverError(_('Database error inserting OAuth application user.'));
242                 }
243
244                 // Okay, good
245                 return new OAuthToken($at->tok, $at->secret);
246             }
247
248         } else {
249
250             // the token was not authorized or not verfied
251             common_log(
252                 LOG_INFO,
253                 sprintf(
254                     "API OAuth - Attempt to exchange unauthorized or unverified request token %s for an access token.",
255                      $rt->tok
256                 )
257             );
258             return null;
259         }
260     }
261
262     /**
263      * Revoke specified access token
264      *
265      * Revokes the token specified by $token_key.
266      * Throws exceptions in case of error.
267      *
268      * @param string $token_key the token to be revoked
269      * @param int    $type      type of token (0 = req, 1 = access)
270      *
271      * @access public
272      *
273      * @return void
274      */
275     public function revoke_token($token_key, $type = 0) {
276         $rt        = new Token();
277         $rt->tok   = $token_key;
278         $rt->type  = $type;
279         $rt->state = 0;
280
281         if (!$rt->find(true)) {
282             // TRANS: Exception thrown when an attempt is made to revoke an unknown token.
283             throw new Exception(_('Tried to revoke unknown token.'));
284         }
285
286         if (!$rt->delete()) {
287             // TRANS: Exception thrown when an attempt is made to remove a revoked token.
288             throw new Exception(_('Failed to delete revoked token.'));
289         }
290     }
291
292     /*
293      * Create a new request token. Overrided to support OAuth 1.0a callback
294      *
295      * @param OAuthConsumer $consumer the OAuth Consumer for this token
296      * @param string        $callback the verified OAuth callback URL
297      *
298      * @return OAuthToken   $token a new unauthorized OAuth request token
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 }