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