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