2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
4 * You can obtain one at http://mozilla.org/MPL/2.0/. */
6 // Called e.g. as /api?access_token=...&whatever_api_parameters
7 // access_token can be handed via GET or POST or an 'Authorization: Bearer' header.
8 // Response is always JSON.
10 // Include the common auth system files (including the OAuth2 Server object).
11 require_once(__DIR__.'/authsystem.inc.php');
12 if ($settings['piwik_enabled']) {
13 // We do not send out an HTML file, so we need to do the Piwik tracking ourselves.
14 // Init is done here, actual tracking before exit.
15 require_once($settings['piwik_tracker_path'].'PiwikTracker.php');
16 PiwikTracker::$URL = ((strpos($settings['piwik_url'], '://') === false) ? 'http://localhost' : '' ).$settings['piwik_url'];
17 $piwikTracker = new PiwikTracker($idSite = $settings['piwik_site_id']);
20 $errors = $utils->checkForSecureConnection();
21 $utils->sendSecurityHeaders();
23 if (!count($errors)) {
24 // Handle a request to a resource and authenticate the access token
25 $token_OK = $server->verifyResourceRequest(OAuth2\Request::createFromGlobals());
27 $response = $server->getResponse();
28 if (!count($response->getParameters())) {
29 // We get an empty response if we don't get any auth header. Let's actually note that explicitly.
30 $response->setError($response->getStatusCode(), 'auth_missing', 'Authentication missing');
33 if ($settings['piwik_enabled']) { $piwikTracker->doTrackPageView('API Request: Bad Token'); }
36 $token = $server->getAccessTokenData(OAuth2\Request::createFromGlobals());
37 // API request successful, return requested resource.
38 if (array_key_exists('email', $_GET)) {
39 if ($token['scope'] == 'email') {
40 if (intval(@$token['user_id'])) {
41 $result = $db->prepare('SELECT `id`,`email` FROM `auth_users` WHERE `id` = :userid;');
42 $result->execute(array(':userid' => $token['user_id']));
43 $user = $result->fetch(PDO::FETCH_ASSOC);
45 $utils->log('user_token_failure', 'token: '.$token['access_token']);
46 print(json_encode(array('error' => 'unknown_user',
47 'error_description' => 'The user the access token is connected to was not recognized.')));
50 print(json_encode(array('success' => true, 'email' => $user['email'])));
54 print(json_encode(array('error' => 'no_user',
55 'error_description' => 'The access token is not connected to a user.')));
59 print(json_encode(array('error' => 'insufficient_scope',
60 'error_description' => 'The scope of the token you used in this API request is insufficient to access this resource.')));
63 elseif (array_key_exists('newclient', $_GET)) {
64 if ($token['scope'] == 'clientreg') {
65 if (intval(@$token['user_id'])) {
66 $result = $db->prepare('SELECT `id`,`email` FROM `auth_users` WHERE `id` = :userid;');
67 $result->execute(array(':userid' => $token['user_id']));
68 $user = $result->fetch(PDO::FETCH_ASSOC);
70 $utils->log('user_token_failure', 'token: '.$token['access_token']);
71 print(json_encode(array('error' => 'unknown_user',
72 'error_description' => 'The user the access token is connected to was not recognized.')));
75 if (($utils->client_reg_email_whitelist === false) || (in_array($user['email'], $utils->client_reg_email_whitelist))) {
76 if (strlen(@$_GET['client_id']) >= 5) {
77 $result = $db->prepare('SELECT `client_id`,`user_id` FROM `oauth_clients` WHERE `client_id` = :clientid;');
78 $result->execute(array(':clientid' => $_GET['client_id']));
79 $client = $result->fetch(PDO::FETCH_ASSOC);
80 if (!$client['client_id']) {
82 $clientsecret = $utils->createClientSecret();
83 $result = $db->prepare('INSERT INTO `oauth_clients` (`client_id`, `client_secret`, `redirect_uri`, `scope`, `user_id`) VALUES (:clientid, :secret, :rediruri, :scope, :userid);');
84 if ($result->execute(array(':clientid' => $_GET['client_id'],
85 ':secret' => $clientsecret,
86 ':rediruri' => (strlen(@$_GET['redirect_uri']) ? $_GET['redirect_uri'] : ''),
87 ':scope' => (strlen(@$_GET['scope']) ? $_GET['scope'] : ''),
88 ':userid' => $user['id']))) {
89 print(json_encode(array('success' => true, 'client_secret' => $clientsecret)));
92 $utils->log('client_save_failure', 'client: '.$client['client_id']);
93 print(json_encode(array('error' => 'unexpected_save_failure',
94 'error_description' => 'Unexpectedly failed to save new client information.')));
97 elseif ($client['user_id'] == $user['id']) {
98 // The client ID was set by this user, set new secret and return.
99 $clientsecret = $utils->createClientSecret();
100 $result = $db->prepare('UPDATE `oauth_clients` SET `client_secret` = :secret WHERE `client_id` = :clientid;');
101 if (!$result->execute(array(':secret' => $clientsecret,':clientid' => $client['client_id']))) {
102 $utils->log('client_save_failure', 'client: '.$client['client_id'].', new secret - '.$result->errorInfo()[2]);
103 print(json_encode(array('error' => 'unexpected_save_failure',
104 'error_description' => 'Unexpectedly failed to save new secret.')));
107 if (strlen(@$_GET['redirect_uri'])) {
108 $result = $db->prepare('UPDATE `oauth_clients` SET `redirect_uri` = :rediruri WHERE `client_id` = :clientid;');
109 if (!$result->execute(array(':rediruri' => $_GET['redirect_uri'],':clientid' => $client['client_id']))) {
110 $utils->log('client_save_failure', 'client: '.$client['client_id'].', new redirect_uri: '.$_GET['redirect_uri'].' - '.$result->errorInfo()[2]);
113 if (strlen(@$_GET['scope'])) {
114 $result = $db->prepare('UPDATE `oauth_clients` SET `scope` = :scope WHERE `client_id` = :clientid;');
115 if (!$result->execute(array(':scope' => $_GET['scope'],':clientid' => $client['client_id']))) {
116 $utils->log('client_save_failure', 'client: '.$client['client_id'].', new scope: '.$_GET['scope'].' - '.$result->errorInfo()[2]);
119 print(json_encode(array('success' => true, 'client_secret' => $clientsecret)));
123 print(json_encode(array('error' => 'client_id_used',
124 'error_description' => 'This client ID is in use by a different user.')));
128 print(json_encode(array('error' => 'invalid_client_id_',
129 'error_description' => 'A client ID of at least 5 characters needs to be supplied.')));
133 print(json_encode(array('error' => 'insufficient_privileges',
134 'error_description' => 'This user is not allowed to register new clients.')));
139 print(json_encode(array('error' => 'no_user',
140 'error_description' => 'The access token is not connected to a user.')));
144 print(json_encode(array('error' => 'insufficient_scope',
145 'error_description' => 'The scope of the token you used in this API request is insufficient to access this resource.')));
149 print(json_encode(array('error' => 'invalid_resource',
150 'error_description' => 'The resource requested from the API is unknown.')));
154 print(json_encode(array('error' => 'insecure_connection',
155 'error_description' => 'Your connection is insecure. The API can only be accessed on secure connections.')));
157 if ($settings['piwik_enabled']) {
158 $piwikTracker->doTrackPageView('API Request'.(strlen($token['scope'])?': '.$token['scope']:''));