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