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