]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/apiauth.php
Remove debugging statement
[quix0rs-gnu-social.git] / lib / apiauth.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Base class for API actions that require authentication
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  API
23  * @package   StatusNet
24  * @author    Adrian Lang <mail@adrianlang.de>
25  * @author    Brenda Wallace <shiny@cpan.org>
26  * @author    Craig Andrews <candrews@integralblue.com>
27  * @author    Dan Moore <dan@moore.cx>
28  * @author    Evan Prodromou <evan@status.net>
29  * @author    mEDI <medi@milaro.net>
30  * @author    Sarven Capadisli <csarven@status.net>
31  * @author    Zach Copley <zach@status.net>
32  * @copyright 2009-2010 StatusNet, Inc.
33  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
34  * @link      http://status.net/
35  */
36
37 if (!defined('STATUSNET')) {
38     exit(1);
39 }
40
41 require_once INSTALLDIR . '/lib/api.php';
42 require_once INSTALLDIR . '/lib/apioauth.php';
43
44 /**
45  * Actions extending this class will require auth
46  *
47  * @category API
48  * @package  StatusNet
49  * @author   Zach Copley <zach@status.net>
50  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
51  * @link     http://status.net/
52  */
53
54 class ApiAuthAction extends ApiAction
55 {
56     var $auth_user_nickname = null;
57     var $auth_user_password = null;
58     var $access_token       = null;
59     var $oauth_source       = null;
60
61     /**
62      * Take arguments for running, and output basic auth header if needed
63      *
64      * @param array $args $_REQUEST args
65      *
66      * @return boolean success flag
67      *
68      */
69
70     function prepare($args)
71     {
72         parent::prepare($args);
73
74         $this->consumer_key = $this->arg('oauth_consumer_key');
75         $this->access_token = $this->arg('oauth_token');
76
77         // NOTE: $this->auth_user has to get set in prepare(), not handle(),
78         // because subclasses do stuff with it in their prepares.
79
80         if ($this->requiresAuth()) {
81             if (!empty($this->access_token)) {
82                 $this->checkOAuthRequest();
83             } else {
84                 $this->checkBasicAuthUser(true);
85             }
86         } else {
87
88             // Check to see if a basic auth user is there even
89             // if one's not required
90
91             if (empty($this->access_token)) {
92                 $this->checkBasicAuthUser(false);
93             }
94         }
95
96         // Reject API calls with the wrong access level
97
98         if ($this->isReadOnly($args) == false) {
99             if ($this->access != self::READ_WRITE) {
100                 $msg = _('API resource requires read-write access, ' .
101                          'but you only have read access.');
102                 $this->clientError($msg, 401, $this->format);
103                 exit;
104             }
105         }
106
107         return true;
108     }
109
110     function handle($args)
111     {
112         parent::handle($args);
113     }
114
115     function checkOAuthRequest()
116     {
117         $datastore   = new ApiStatusNetOAuthDataStore();
118         $server      = new OAuthServer($datastore);
119         $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
120
121         $server->add_signature_method($hmac_method);
122
123         ApiOauthAction::cleanRequest();
124
125         try {
126
127             $req  = OAuthRequest::from_request();
128             $server->verify_request($req);
129
130             $app = Oauth_application::getByConsumerKey($this->consumer_key);
131
132             if (empty($app)) {
133
134                 // this should probably not happen
135                 common_log(LOG_WARNING,
136                            'Couldn\'t find the OAuth app for consumer key: ' .
137                            $this->consumer_key);
138
139                 throw new OAuthException('No application for that consumer key.');
140             }
141
142             // set the source attr
143
144             $this->oauth_source = $app->name;
145
146             $appUser = Oauth_application_user::staticGet('token',
147                                                          $this->access_token);
148
149             // XXX: Check that app->id and appUser->application_id and consumer all
150             // match?
151
152             if (!empty($appUser)) {
153
154                 // If access_type == 0 we have either a request token
155                 // or a bad / revoked access token
156
157                 if ($appUser->access_type != 0) {
158
159                     // Set the access level for the api call
160
161                     $this->access = ($appUser->access_type & Oauth_application::$writeAccess)
162                       ? self::READ_WRITE : self::READ_ONLY;
163
164                     if (Event::handle('StartSetApiUser', array(&$user))) {
165                         $this->auth_user = User::staticGet('id', $appUser->profile_id);
166                         Event::handle('EndSetApiUser', array($user));
167                     }
168
169                     $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
170                       "application '%s' (id: %d) with %s access.";
171
172                     common_log(LOG_INFO, sprintf($msg,
173                                                  $this->auth_user->nickname,
174                                                  $this->auth_user->id,
175                                                  $app->name,
176                                                  $app->id,
177                                                  ($this->access = self::READ_WRITE) ?
178                                                  'read-write' : 'read-only'
179                                                  ));
180                     return;
181                 } else {
182                     throw new OAuthException('Bad access token.');
183                 }
184             } else {
185
186                 // Also should not happen
187
188                 throw new OAuthException('No user for that token.');
189             }
190
191         } catch (OAuthException $e) {
192             common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
193             $this->showAuthError();
194             exit;
195         }
196     }
197
198     /**
199      * Does this API resource require authentication?
200      *
201      * @return boolean true
202      */
203
204     function requiresAuth()
205     {
206         return true;
207     }
208
209     /**
210      * Check for a user specified via HTTP basic auth. If there isn't
211      * one, try to get one by outputting the basic auth header.
212      *
213      * @return boolean true or false
214      */
215
216     function checkBasicAuthUser($required = true)
217     {
218         $this->basicAuthProcessHeader();
219
220         $realm = common_config('site', 'name') . ' API';
221
222         if (!isset($this->auth_user_nickname) && $required) {
223             header('WWW-Authenticate: Basic realm="' . $realm . '"');
224
225             // show error if the user clicks 'cancel'
226
227             $this->showAuthError();
228             exit;
229
230         } else {
231
232             $user = common_check_user($this->auth_user_nickname,
233                                       $this->auth_user_password);
234
235             if (Event::handle('StartSetApiUser', array(&$user))) {
236
237                 if (!empty($user)) {
238                     $this->auth_user = $user;
239                 }
240
241                 Event::handle('EndSetApiUser', array($user));
242             }
243
244             // By default, basic auth users have rw access
245
246             $this->access = self::READ_WRITE;
247
248             if (empty($this->auth_user) && $required) {
249
250                 // basic authentication failed
251
252                 list($proxy, $ip) = common_client_ip();
253
254                 $msg = sprintf(_('Failed API auth attempt, nickname = %1$s, ' .
255                          'proxy = %2$s, ip = %3$s'),
256                                $this->auth_user_nickname,
257                                $proxy,
258                                $ip);
259                 common_log(LOG_WARNING, $msg);
260                 $this->showAuthError();
261                 exit;
262             }
263         }
264     }
265
266     /**
267      * Read the HTTP headers and set the auth user.  Decodes HTTP_AUTHORIZATION
268      * param to support basic auth when PHP is running in CGI mode.
269      *
270      * @return void
271      */
272
273     function basicAuthProcessHeader()
274     {
275         if (isset($_SERVER['AUTHORIZATION'])
276             || isset($_SERVER['HTTP_AUTHORIZATION'])
277             ) {
278             $authorization_header = isset($_SERVER['HTTP_AUTHORIZATION'])
279               ? $_SERVER['HTTP_AUTHORIZATION'] : $_SERVER['AUTHORIZATION'];
280         }
281
282         if (isset($_SERVER['PHP_AUTH_USER'])) {
283             $this->auth_user_nickname = $_SERVER['PHP_AUTH_USER'];
284             $this->auth_user_password = $_SERVER['PHP_AUTH_PW'];
285         } elseif (isset($authorization_header)
286             && strstr(substr($authorization_header, 0, 5), 'Basic')) {
287
288             // Decode the HTTP_AUTHORIZATION header on php-cgi server self
289             // on fcgid server the header name is AUTHORIZATION
290
291             $auth_hash = base64_decode(substr($authorization_header, 6));
292             list($this->auth_user_nickname,
293                  $this->auth_user_password) = explode(':', $auth_hash);
294
295             // Set all to null on a empty basic auth request
296
297             if (empty($this->auth_user_nickname)) {
298                 $this->auth_user_nickname = null;
299                 $this->auth_password = null;
300             }
301         }
302     }
303
304     /**
305      * Output an authentication error message.  Use XML or JSON if one
306      * of those formats is specified, otherwise output plain text
307      *
308      * @return void
309      */
310
311     function showAuthError()
312     {
313         header('HTTP/1.1 401 Unauthorized');
314         $msg = 'Could not authenticate you.';
315
316         if ($this->format == 'xml') {
317             header('Content-Type: application/xml; charset=utf-8');
318             $this->startXML();
319             $this->elementStart('hash');
320             $this->element('error', null, $msg);
321             $this->element('request', null, $_SERVER['REQUEST_URI']);
322             $this->elementEnd('hash');
323             $this->endXML();
324         } elseif ($this->format == 'json') {
325             header('Content-Type: application/json; charset=utf-8');
326             $error_array = array('error' => $msg,
327                                  'request' => $_SERVER['REQUEST_URI']);
328             print(json_encode($error_array));
329         } else {
330             header('Content-type: text/plain');
331             print "$msg\n";
332         }
333     }
334
335 }