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