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