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