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