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