]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/apiauth.php
- Check for read-only vs. read-write access to protected API resources (OAuth)
[quix0rs-gnu-social.git] / lib / apiauth.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  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
34  * @link      http://status.net/
35  */
36
37 if (!defined('STATUSNET')) {
38     exit(1);
39 }
40
41 require_once INSTALLDIR . '/lib/api.php';
42 require_once INSTALLDIR . '/lib/apioauth.php';
43
44 /**
45  * Actions extending this class will require auth
46  *
47  * @category API
48  * @package  StatusNet
49  * @author   Zach Copley <zach@status.net>
50  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
51  * @link     http://status.net/
52  */
53
54 class ApiAuthAction extends ApiAction
55 {
56     var $auth_user_nickname = null;
57     var $auth_user_password = null;
58     var $access_token       = null;
59     var $oauth_source       = null;
60     var $auth_user          = null;
61
62     /**
63      * Take arguments for running, and output basic auth header if needed
64      *
65      * @param array $args $_REQUEST args
66      *
67      * @return boolean success flag
68      *
69      */
70
71     function prepare($args)
72     {
73         parent::prepare($args);
74
75         $this->consumer_key = $this->arg('oauth_consumer_key');
76         $this->access_token = $this->arg('oauth_token');
77
78         // NOTE: $this->auth_user has to get set in prepare(), not handle(),
79         // because subclasses do stuff with it in their prepares.
80
81         if ($this->requiresAuth()) {
82             if (!empty($this->access_token)) {
83                 $this->checkOAuthRequest();
84             } else {
85                 $this->checkBasicAuthUser();
86             }
87
88             // Reject API calls with the wrong access level
89
90             if ($this->isReadOnly($args) == false) {
91                 if ($this->access != self::READ_WRITE) {
92                     $msg = 'API resource requires read-write access, ' .
93                       'but you only have read access.';
94                     $this->clientError($msg, 401, $this->format);
95                     exit();
96                 }
97             }
98         }
99
100         return true;
101     }
102
103     function handle($args)
104     {
105         parent::handle($args);
106     }
107
108     function checkOAuthRequest()
109     {
110         $datastore   = new ApiStatusNetOAuthDataStore();
111         $server      = new OAuthServer($datastore);
112         $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
113
114         $server->add_signature_method($hmac_method);
115
116         ApiOauthAction::cleanRequest();
117
118         try {
119
120             $req  = OAuthRequest::from_request();
121             $server->verify_request($req);
122
123             $app = Oauth_application::getByConsumerKey($this->consumer_key);
124
125             if (empty($app)) {
126
127                 // this should probably not happen
128                 common_log(LOG_WARNING,
129                            'Couldn\'t find the OAuth app for consumer key: ' .
130                            $this->consumer_key);
131
132                 throw new OAuthException('No application for that consumer key.');
133             }
134
135             // set the source attr
136
137             $this->oauth_source = $app->name;
138
139             $appUser = Oauth_application_user::staticGet('token',
140                                                          $this->access_token);
141
142             // XXX: Check that app->id and appUser->application_id and consumer all
143             // match?
144
145             if (!empty($appUser)) {
146
147                 // If access_type == 0 we have either a request token
148                 // or a bad / revoked access token
149
150                 if ($appUser->access_type != 0) {
151
152                     // Set the access level for the api call
153
154                     $this->access = ($appUser->access_type & Oauth_application::$writeAccess)
155                       ? self::READ_WRITE : self::READ_ONLY;
156
157                     if (Event::handle('StartSetApiUser', array(&$user))) {
158                         $this->auth_user = User::staticGet('id', $appUser->profile_id);
159                         Event::handle('EndSetApiUser', array($user));
160                     }
161
162                     $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
163                       "application '%s' (id: %d) with %s access.";
164
165                     common_log(LOG_INFO, sprintf($msg,
166                                                  $this->auth_user->nickname,
167                                                  $this->auth_user->id,
168                                                  $app->name,
169                                                  $app->id,
170                                                  ($this->access = self::READ_WRITE) ?
171                                                  'read-write' : 'read-only'
172                                                  ));
173                     return true;
174                 } else {
175                     throw new OAuthException('Bad access token.');
176                 }
177             } else {
178
179                 // Also should not happen
180
181                 throw new OAuthException('No user for that token.');
182             }
183
184         } catch (OAuthException $e) {
185             common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
186             $this->showAuthError();
187             exit;
188         }
189     }
190
191     /**
192      * Does this API resource require authentication?
193      *
194      * @return boolean true
195      */
196
197     function requiresAuth()
198     {
199         return true;
200     }
201
202     /**
203      * Check for a user specified via HTTP basic auth. If there isn't
204      * one, try to get one by outputting the basic auth header.
205      *
206      * @return boolean true or false
207      */
208
209     function checkBasicAuthUser()
210     {
211         $this->basicAuthProcessHeader();
212
213         $realm = common_config('site', 'name') . ' API';
214
215         if (!isset($this->auth_user_nickname)) {
216             header('WWW-Authenticate: Basic realm="' . $realm . '"');
217
218             // show error if the user clicks 'cancel'
219
220             $this->showAuthError();
221             exit;
222
223         } else {
224
225             $user = common_check_user($this->auth_user_nickname,
226                                       $this->auth_user_password);
227
228             if (Event::handle('StartSetApiUser', array(&$user))) {
229                 $this->auth_user = $user;
230                 Event::handle('EndSetApiUser', array($user));
231             }
232
233             // By default, basic auth users have rw access
234
235             $this->access = self::READ_WRITE;
236
237             if (empty($this->auth_user)) {
238
239                 // basic authentication failed
240
241                 list($proxy, $ip) = common_client_ip();
242
243                 common_log(
244                     LOG_WARNING,
245                     'Failed API auth attempt, nickname = ' .
246                     "$nickname, proxy = $proxy, ip = $ip."
247                 );
248
249                 $this->showAuthError();
250                 exit;
251             }
252         }
253     }
254
255     /**
256      * Read the HTTP headers and set the auth user.  Decodes HTTP_AUTHORIZATION
257      * param to support basic auth when PHP is running in CGI mode.
258      *
259      * @return void
260      */
261
262     function basicAuthProcessHeader()
263     {
264         if (isset($_SERVER['AUTHORIZATION'])
265             || isset($_SERVER['HTTP_AUTHORIZATION'])
266             ) {
267             $authorization_header = isset($_SERVER['HTTP_AUTHORIZATION'])
268               ? $_SERVER['HTTP_AUTHORIZATION'] : $_SERVER['AUTHORIZATION'];
269         }
270
271         if (isset($_SERVER['PHP_AUTH_USER'])) {
272             $this->auth_user_nickname = $_SERVER['PHP_AUTH_USER'];
273             $this->auth_user_password = $_SERVER['PHP_AUTH_PW'];
274         } elseif (isset($authorization_header)
275             && strstr(substr($authorization_header, 0, 5), 'Basic')) {
276
277             // Decode the HTTP_AUTHORIZATION header on php-cgi server self
278             // on fcgid server the header name is AUTHORIZATION
279
280             $auth_hash = base64_decode(substr($authorization_header, 6));
281             list($this->auth_user_nickname,
282                  $this->auth_user_password) = explode(':', $auth_hash);
283
284             // Set all to null on a empty basic auth request
285
286             if (empty($this->auth_user_nickname)) {
287                 $this->auth_user_nickname = null;
288                 $this->auth_password = null;
289             }
290         }
291     }
292
293     /**
294      * Output an authentication error message.  Use XML or JSON if one
295      * of those formats is specified, otherwise output plain text
296      *
297      * @return void
298      */
299
300     function showAuthError()
301     {
302         header('HTTP/1.1 401 Unauthorized');
303         $msg = 'Could not authenticate you.';
304
305         if ($this->format == 'xml') {
306             header('Content-Type: application/xml; charset=utf-8');
307             $this->startXML();
308             $this->elementStart('hash');
309             $this->element('error', null, $msg);
310             $this->element('request', null, $_SERVER['REQUEST_URI']);
311             $this->elementEnd('hash');
312             $this->endXML();
313         } elseif ($this->format == 'json') {
314             header('Content-Type: application/json; charset=utf-8');
315             $error_array = array('error' => $msg,
316                                  'request' => $_SERVER['REQUEST_URI']);
317             print(json_encode($error_array));
318         } else {
319             header('Content-type: text/plain');
320             print "$msg\n";
321         }
322     }
323
324 }