]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/apiauthaction.php
*** Privacy Leak fixed: ***
[quix0rs-gnu-social.git] / lib / apiauthaction.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     GNU social 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('GNUSOCIAL')) { exit(1); }
57
58 /**
59  * Actions extending this class will require auth
60  *
61  * @category API
62  * @package  StatusNet
63  * @author   Zach Copley <zach@status.net>
64  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
65  * @link     http://status.net/
66  */
67 class ApiAuthAction extends ApiAction
68 {
69     var $auth_user_nickname = null;
70     var $auth_user_password = null;
71
72     /**
73      * Take arguments for running, looks for an OAuth request,
74      * and outputs basic auth header if needed
75      *
76      * @param array $args $_REQUEST args
77      *
78      * @return boolean success flag
79      *
80      */
81     protected function prepare(array $args=array())
82     {
83         parent::prepare($args);
84
85         // NOTE: $this->scoped and $this->auth_user has to get set in
86         // prepare(), not handle(), as subclasses use them in prepares.
87
88         // Allow regular login session, but we have to double-check the
89         // HTTP_REFERER value to avoid cross domain POSTing since the API
90         // doesn't use the "token" form field.
91         if (common_logged_in() && common_local_referer()) {
92             $this->scoped = Profile::current();
93             $this->auth_user = $this->scoped->getUser();
94             if (!$this->auth_user->hasRight(Right::API)) {
95                 // TRANS: Authorization exception thrown when a user without API access tries to access the API.
96                 throw new AuthorizationException(_('Not allowed to use API.'));
97             }
98             // Let's run this in the same way as if we've just authenticated the user (basic/oauth auth)
99             Event::handle('EndSetApiUser', array($this->auth_user));
100             $this->access = self::READ_WRITE;
101         } else {
102             $oauthReq = $this->getOAuthRequest();
103
104             if ($oauthReq instanceof OAuthRequest) {
105                 $this->checkOAuthRequest($oauthReq);
106             } else {
107                 // If not using OAuth, check if there is a basic auth
108                 // and require it if the current action requires it.
109                 $this->checkBasicAuthUser($this->requiresAuth());
110             }
111
112             // NOTE: Make sure we're scoped properly based on the auths!
113             if (isset($this->auth_user) && $this->auth_user instanceof User) {
114                 $this->scoped = $this->auth_user->getProfile();
115             } else {
116                 $this->scoped = null;
117             }
118         }
119
120         // legacy user transferral
121         // TODO: remove when sure no extended classes need it
122         $this->user = $this->auth_user;
123
124         // Reject API calls with the wrong access level
125
126         if ($this->isReadOnly($args) == false) {
127             if ($this->access != self::READ_WRITE) {
128                 // TRANS: Client error 401.
129                 $msg = _('API resource requires read-write access, ' .
130                          'but you only have read access.');
131                 $this->clientError($msg, 401);
132             }
133         }
134
135         return true;
136     }
137
138     /**
139      * Determine whether the request is an OAuth request.
140      * This is to avoid doign any unnecessary DB lookups.
141      *
142      * @return mixed the OAuthRequest or false
143      */
144     function getOAuthRequest()
145     {
146         ApiOAuthAction::cleanRequest();
147
148         $req  = OAuthRequest::from_request();
149
150         $consumer    = $req->get_parameter('oauth_consumer_key');
151         $accessToken = $req->get_parameter('oauth_token');
152
153         // XXX: Is it good enough to assume it's not meant to be an
154         // OAuth request if there is no consumer or token? --Z
155
156         if (empty($consumer) || empty($accessToken)) {
157             return false;
158         }
159
160         return $req;
161     }
162
163     /**
164      * Verifies the OAuth request signature, sets the auth user
165      * and access type (read-only or read-write)
166      *
167      * @param OAuthRequest $request the OAuth Request
168      *
169      * @return nothing
170      */
171     function checkOAuthRequest($request)
172     {
173         $datastore   = new ApiGNUsocialOAuthDataStore();
174         $server      = new OAuthServer($datastore);
175         $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
176
177         $server->add_signature_method($hmac_method);
178
179         try {
180             $server->verify_request($request);
181
182             $consumer     = $request->get_parameter('oauth_consumer_key');
183             $access_token = $request->get_parameter('oauth_token');
184
185             $app = Oauth_application::getByConsumerKey($consumer);
186
187             if (empty($app)) {
188                 common_log(
189                     LOG_WARNING,
190                     'API OAuth - Couldn\'t find the OAuth app for consumer key: ' .
191                     $consumer
192                 );
193                 // TRANS: OAuth exception thrown when no application is found for a given consumer key.
194                 throw new OAuthException(_('No application for that consumer key.'));
195             }
196
197             // set the source attr
198             if ($app->name != 'anonymous') {
199                 $this->source = $app->name;
200             }
201
202
203             $appUser = Oauth_application_user::getKV('token', $access_token);
204
205             if (!empty($appUser)) {
206                 // If access_type == 0 we have either a request token
207                 // or a bad / revoked access token
208
209                 if ($appUser->access_type != 0) {
210                     // Set the access level for the api call
211                     $this->access = ($appUser->access_type & Oauth_application::$writeAccess)
212                       ? self::READ_WRITE : self::READ_ONLY;
213
214                     // Set the auth user
215                     if (Event::handle('StartSetApiUser', array(&$user))) {
216                         $user = User::getKV('id', $appUser->profile_id);
217                     }
218                     if ($user instanceof User) {
219                         if (!$user->hasRight(Right::API)) {
220                             // TRANS: Authorization exception thrown when a user without API access tries to access the API.
221                             throw new AuthorizationException(_('Not allowed to use API.'));
222                         }
223                         $this->auth_user = $user;
224                         Event::handle('EndSetApiUser', array($this->auth_user));
225                     } else {
226                         // If $user is not a real User, let's force it to null.
227                         $this->auth_user = null;
228                     }
229
230                     // FIXME: setting the value returned by common_current_user()
231                     // There should probably be a better method for this. common_set_user()
232                     // does lots of session stuff.
233                     global $_cur;
234                     $_cur = $this->auth_user;
235
236                     $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
237                         "application '%s' (id: %d) with %s access.";
238
239                     common_log(
240                         LOG_INFO,
241                         sprintf(
242                             $msg,
243                             $this->auth_user->nickname,
244                             $this->auth_user->id,
245                             $app->name,
246                             $app->id,
247                             ($this->access = self::READ_WRITE) ? 'read-write' : 'read-only'
248                         )
249                     );
250                 } else {
251                     // TRANS: OAuth exception given when an incorrect access token was given for a user.
252                     throw new OAuthException(_('Bad access token.'));
253                 }
254             } else {
255                 // Also should not happen.
256                 // TRANS: OAuth exception given when no user was found for a given token (no token was found).
257                 throw new OAuthException(_('No user for that token.'));
258             }
259
260         } catch (OAuthException $e) {
261             $this->logAuthFailure($e->getMessage());
262             common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
263             $this->clientError($e->getMessage(), 401);
264         }
265     }
266
267     /**
268      * Does this API resource require authentication?
269      *
270      * @return boolean true
271      */
272     public function requiresAuth()
273     {
274         return true;
275     }
276
277     /**
278      * Check for a user specified via HTTP basic auth. If there isn't
279      * one, try to get one by outputting the basic auth header.
280      *
281      * @return boolean true or false
282      */
283     function checkBasicAuthUser($required = true)
284     {
285         $this->basicAuthProcessHeader();
286
287         $realm = common_config('api', 'realm');
288
289         if (empty($realm)) {
290             $realm = common_config('site', 'name') . ' API';
291         }
292
293         if (empty($this->auth_user_nickname) && $required) {
294             header('WWW-Authenticate: Basic realm="' . $realm . '"');
295
296             // show error if the user clicks 'cancel'
297             // TRANS: Client error thrown when authentication fails because a user clicked "Cancel".
298             $this->clientError(_('Could not authenticate you.'), 401);
299
300         } else {
301             // $this->auth_user_nickname - i.e. PHP_AUTH_USER - will have a value since it was not empty
302
303             $user = common_check_user($this->auth_user_nickname,
304                                       $this->auth_user_password);
305
306             Event::handle('StartSetApiUser', array(&$user));
307             if ($user instanceof User) {
308                 if (!$user->hasRight(Right::API)) {
309                     // TRANS: Authorization exception thrown when a user without API access tries to access the API.
310                     throw new AuthorizationException(_('Not allowed to use API.'));
311                 }
312                 $this->auth_user = $user;
313
314                 Event::handle('EndSetApiUser', array($this->auth_user));
315             } else {
316                 $this->auth_user = null;
317             }
318
319             if ($required && $this->auth_user instanceof User) {
320                 // By default, basic auth users have rw access
321                 $this->access = self::READ_WRITE;
322             } elseif ($required) {
323                 $msg = sprintf(
324                     "basic auth nickname = %s",
325                     $this->auth_user_nickname
326                 );
327                 $this->logAuthFailure($msg);
328
329                 // We must present WWW-Authenticate in accordance to HTTP status code 401
330                 header('WWW-Authenticate: Basic realm="' . $realm . '"');
331                 // TRANS: Client error thrown when authentication fails.
332                 $this->clientError(_('Could not authenticate you.'), 401);
333             } else {
334                 // all get rw access for actions that don't require auth
335                 $this->access = self::READ_WRITE;
336             }
337         }
338     }
339
340     /**
341      * Read the HTTP headers and set the auth user.  Decodes HTTP_AUTHORIZATION
342      * param to support basic auth when PHP is running in CGI mode.
343      *
344      * @return void
345      */
346     function basicAuthProcessHeader()
347     {
348         $authHeaders = array('AUTHORIZATION',
349                              'HTTP_AUTHORIZATION',
350                              'REDIRECT_HTTP_AUTHORIZATION'); // rewrite for CGI
351         $authorization_header = null;
352         foreach ($authHeaders as $header) {
353             if (isset($_SERVER[$header])) {
354                 $authorization_header = $_SERVER[$header];
355                 break;
356             }
357         }
358
359         if (isset($_SERVER['PHP_AUTH_USER'])) {
360             $this->auth_user_nickname = $_SERVER['PHP_AUTH_USER'];
361             $this->auth_user_password = $_SERVER['PHP_AUTH_PW'];
362         } elseif (isset($authorization_header)
363             && strstr(substr($authorization_header, 0, 5), 'Basic')) {
364
365             // Decode the HTTP_AUTHORIZATION header on php-cgi server self
366             // on fcgid server the header name is AUTHORIZATION
367             $auth_hash = base64_decode(substr($authorization_header, 6));
368             list($this->auth_user_nickname,
369                  $this->auth_user_password) = explode(':', $auth_hash);
370
371             // Set all to null on a empty basic auth request
372
373             if (empty($this->auth_user_nickname)) {
374                 $this->auth_user_nickname = null;
375                 $this->auth_password = null;
376             }
377         }
378     }
379
380     /**
381      * Log an API authentication failure. Collect the proxy and IP
382      * and log them
383      *
384      * @param string $logMsg additional log message
385      */
386      function logAuthFailure($logMsg)
387      {
388         list($proxy, $ip) = common_client_ip();
389
390         $msg = sprintf(
391             'API auth failure (proxy = %1$s, ip = %2$s) - ',
392             $proxy,
393             $ip
394         );
395
396         common_log(LOG_WARNING, $msg . $logMsg);
397      }
398 }