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