]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/apiauth.php
Merge branch 'master' of gitorious.org:statusnet/mainline
[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/apioauth.php';
42
43 /**
44  * Actions extending this class will require auth
45  *
46  * @category API
47  * @package  StatusNet
48  * @author   Zach Copley <zach@status.net>
49  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
50  * @link     http://status.net/
51  */
52
53 class ApiAuthAction extends ApiAction
54 {
55     var $auth_user_nickname = null;
56     var $auth_user_password = null;
57
58     /**
59      * Take arguments for running, looks for an OAuth request,
60      * and outputs basic auth header if needed
61      *
62      * @param array $args $_REQUEST args
63      *
64      * @return boolean success flag
65      *
66      */
67
68     function prepare($args)
69     {
70         parent::prepare($args);
71
72         // NOTE: $this->auth_user has to get set in prepare(), not handle(),
73         // because subclasses do stuff with it in their prepares.
74
75         $oauthReq = $this->getOAuthRequest();
76
77         if (!$oauthReq) {
78             if ($this->requiresAuth()) {
79                 $this->checkBasicAuthUser(true);
80             } else {
81                 // Check to see if a basic auth user is there even
82                 // if one's not required
83                 $this->checkBasicAuthUser(false);
84             }
85         } else {
86             $this->checkOAuthRequest($oauthReq);
87         }
88
89         // Reject API calls with the wrong access level
90
91         if ($this->isReadOnly($args) == false) {
92             if ($this->access != self::READ_WRITE) {
93                 $msg = _('API resource requires read-write access, ' .
94                          'but you only have read access.');
95                 $this->clientError($msg, 401, $this->format);
96                 exit;
97             }
98         }
99
100         return true;
101     }
102
103     /**
104      * Determine whether the request is an OAuth request.
105      * This is to avoid doign any unnecessary DB lookups.
106      *
107      * @return mixed the OAuthRequest or false
108      */
109
110     function getOAuthRequest()
111     {
112         ApiOauthAction::cleanRequest();
113
114         $req  = OAuthRequest::from_request();
115
116         $consumer    = $req->get_parameter('oauth_consumer_key');
117         $accessToken = $req->get_parameter('oauth_token');
118
119         // XXX: Is it good enough to assume it's not meant to be an
120         // OAuth request if there is no consumer or token? --Z
121
122         if (empty($consumer) || empty($accessToken)) {
123             return false;
124         }
125
126         return $req;
127     }
128
129     /**
130      * Verifies the OAuth request signature, sets the auth user
131      * and access type (read-only or read-write)
132      *
133      * @param OAuthRequest $request the OAuth Request
134      *
135      * @return nothing
136      */
137
138     function checkOAuthRequest($request)
139     {
140         $datastore   = new ApiStatusNetOAuthDataStore();
141         $server      = new OAuthServer($datastore);
142         $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
143
144         $server->add_signature_method($hmac_method);
145
146         try {
147
148             $server->verify_request($request);
149
150             $consumer     = $request->get_parameter('oauth_consumer_key');
151             $access_token = $request->get_parameter('oauth_token');
152
153             $app = Oauth_application::getByConsumerKey($consumer);
154
155             if (empty($app)) {
156                 common_log(LOG_WARNING,
157                            'Couldn\'t find the OAuth app for consumer key: ' .
158                            $consumer);
159                 throw new OAuthException('No application for that consumer key.');
160             }
161
162             // set the source attr
163
164             $this->source = $app->name;
165
166             $appUser = Oauth_application_user::staticGet('token', $access_token);
167
168             if (!empty($appUser)) {
169
170                 // If access_type == 0 we have either a request token
171                 // or a bad / revoked access token
172
173                 if ($appUser->access_type != 0) {
174
175                     // Set the access level for the api call
176
177                     $this->access = ($appUser->access_type & Oauth_application::$writeAccess)
178                       ? self::READ_WRITE : self::READ_ONLY;
179
180                     // Set the auth user
181
182                     if (Event::handle('StartSetApiUser', array(&$user))) {
183                         $this->auth_user = User::staticGet('id', $appUser->profile_id);
184                         Event::handle('EndSetApiUser', array($user));
185                     }
186
187                     $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
188                       "application '%s' (id: %d) with %s access.";
189
190                     common_log(LOG_INFO, sprintf($msg,
191                                                  $this->auth_user->nickname,
192                                                  $this->auth_user->id,
193                                                  $app->name,
194                                                  $app->id,
195                                                  ($this->access = self::READ_WRITE) ?
196                                                  'read-write' : 'read-only'
197                                                  ));
198                 } else {
199                     throw new OAuthException('Bad access token.');
200                 }
201             } else {
202
203                 // Also should not happen
204
205                 throw new OAuthException('No user for that token.');
206             }
207
208         } catch (OAuthException $e) {
209             common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
210             $this->showAuthError();
211             exit;
212         }
213     }
214
215     /**
216      * Does this API resource require authentication?
217      *
218      * @return boolean true
219      */
220
221     function requiresAuth()
222     {
223         return true;
224     }
225
226     /**
227      * Check for a user specified via HTTP basic auth. If there isn't
228      * one, try to get one by outputting the basic auth header.
229      *
230      * @return boolean true or false
231      */
232
233     function checkBasicAuthUser($required = true)
234     {
235         $this->basicAuthProcessHeader();
236
237         $realm = common_config('api', 'realm');
238
239         if (empty($realm)) {
240             $realm = common_config('site', 'name') . ' API';
241         }
242
243         if (empty($this->auth_user_nickname) && $required) {
244             header('WWW-Authenticate: Basic realm="' . $realm . '"');
245
246             // show error if the user clicks 'cancel'
247
248             $this->showAuthError();
249             exit;
250
251         } else {
252
253             $user = common_check_user($this->auth_user_nickname,
254                                       $this->auth_user_password);
255
256             if (Event::handle('StartSetApiUser', array(&$user))) {
257
258                 if (!empty($user)) {
259                     $this->auth_user = $user;
260                 }
261
262                 Event::handle('EndSetApiUser', array($user));
263             }
264
265             // By default, basic auth users have rw access
266
267             $this->access = self::READ_WRITE;
268
269             if (empty($this->auth_user) && ($required || isset($_SERVER['PHP_AUTH_USER']))) {
270
271                 // basic authentication failed
272
273                 list($proxy, $ip) = common_client_ip();
274
275                 $msg = sprintf(_('Failed API auth attempt, nickname = %1$s, ' .
276                          'proxy = %2$s, ip = %3$s'),
277                                $this->auth_user_nickname,
278                                $proxy,
279                                $ip);
280                 common_log(LOG_WARNING, $msg);
281                 $this->showAuthError();
282                 exit;
283             }
284         }
285     }
286
287     /**
288      * Read the HTTP headers and set the auth user.  Decodes HTTP_AUTHORIZATION
289      * param to support basic auth when PHP is running in CGI mode.
290      *
291      * @return void
292      */
293
294     function basicAuthProcessHeader()
295     {
296         $authHeaders = array('AUTHORIZATION',
297                              'HTTP_AUTHORIZATION',
298                              'REDIRECT_HTTP_AUTHORIZATION'); // rewrite for CGI
299         $authorization_header = null;
300         foreach ($authHeaders as $header) {
301             if (isset($_SERVER[$header])) {
302                 $authorization_header = $_SERVER[$header];
303                 break;
304             }
305         }
306
307         if (isset($_SERVER['PHP_AUTH_USER'])) {
308             $this->auth_user_nickname = $_SERVER['PHP_AUTH_USER'];
309             $this->auth_user_password = $_SERVER['PHP_AUTH_PW'];
310         } elseif (isset($authorization_header)
311             && strstr(substr($authorization_header, 0, 5), 'Basic')) {
312
313             // Decode the HTTP_AUTHORIZATION header on php-cgi server self
314             // on fcgid server the header name is AUTHORIZATION
315
316             $auth_hash = base64_decode(substr($authorization_header, 6));
317             list($this->auth_user_nickname,
318                  $this->auth_user_password) = explode(':', $auth_hash);
319
320             // Set all to null on a empty basic auth request
321
322             if (empty($this->auth_user_nickname)) {
323                 $this->auth_user_nickname = null;
324                 $this->auth_password = null;
325             }
326         }
327     }
328
329     /**
330      * Output an authentication error message.  Use XML or JSON if one
331      * of those formats is specified, otherwise output plain text
332      *
333      * @return void
334      */
335
336     function showAuthError()
337     {
338         header('HTTP/1.1 401 Unauthorized');
339         $msg = 'Could not authenticate you.';
340
341         if ($this->format == 'xml') {
342             header('Content-Type: application/xml; charset=utf-8');
343             $this->startXML();
344             $this->elementStart('hash');
345             $this->element('error', null, $msg);
346             $this->element('request', null, $_SERVER['REQUEST_URI']);
347             $this->elementEnd('hash');
348             $this->endXML();
349         } elseif ($this->format == 'json') {
350             header('Content-Type: application/json; charset=utf-8');
351             $error_array = array('error' => $msg,
352                                  'request' => $_SERVER['REQUEST_URI']);
353             print(json_encode($error_array));
354         } else {
355             header('Content-type: text/plain');
356             print "$msg\n";
357         }
358     }
359
360 }