use correct table name
[authserver.git] / app / api.php
1 <?php
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/. */
5
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.
9
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']);
18 }
19
20 $errors = $utils->checkForSecureConnection();
21 $utils->sendSecurityHeaders();
22
23 if (!count($errors)) {
24   // Handle a request to a resource and authenticate the access token
25   $token_OK = $server->verifyResourceRequest(OAuth2\Request::createFromGlobals());
26   if (!$token_OK) {
27     $server->getResponse()->send();
28     if ($settings['piwik_enabled']) { $piwikTracker->doTrackPageView('API Request: Bad Token'); }
29     exit();
30   }
31   $token = $server->getAccessTokenData(OAuth2\Request::createFromGlobals());
32   // API request successful, return requested resource.
33   if (array_key_exists('email', $_GET)) {
34     if ($token['scope'] == 'email') {
35       if (intval(@$token['user_id'])) {
36         $result = $db->prepare('SELECT `id`,`email` FROM `auth_users` WHERE `id` = :userid;');
37         $result->execute(array(':userid' => $token['user_id']));
38         $user = $result->fetch(PDO::FETCH_ASSOC);
39         if (!$user['id']) {
40           $utils->log('user_token_failure', 'token: '.$token['access_token']);
41           print(json_encode(array('error' => 'unknown_user',
42                                   'error_description' => 'The user the access token is connected to was not recognized.')));
43         }
44         else {
45           print(json_encode(array('success' => true, 'email' => $user['email'])));
46         }
47       }
48       else {
49         print(json_encode(array('error' => 'no_user',
50                                 'error_description' => 'The access token is not connected to a user.')));
51       }
52     }
53     else {
54       print(json_encode(array('error' => 'insufficient_scope',
55                               'error_description' => 'The scope of the token you used in this API request is insufficient to access this resource.')));
56     }
57   }
58   elseif (array_key_exists('newclient', $_GET)) {
59     if ($token['scope'] == 'clientreg') {
60       if (intval(@$token['user_id'])) {
61         $result = $db->prepare('SELECT `id`,`email` FROM `auth_users` WHERE `id` = :userid;');
62         $result->execute(array(':userid' => $token['user_id']));
63         $user = $result->fetch(PDO::FETCH_ASSOC);
64         if (!$user['id']) {
65           $utils->log('user_token_failure', 'token: '.$token['access_token']);
66           print(json_encode(array('error' => 'unknown_user',
67                                   'error_description' => 'The user the access token is connected to was not recognized.')));
68         }
69         else {
70           if (($utils->client_reg_email_whitelist === false) || (in_array($user['email'], $utils->client_reg_email_whitelist))) {
71             if (strlen(@$_GET['client_id']) >= 5) {
72               $result = $db->prepare('SELECT `client_id`,`user_id` FROM `oauth_clients` WHERE `client_id` = :clientid;');
73               $result->execute(array(':clientid' => $_GET['client_id']));
74               $client = $result->fetch(PDO::FETCH_ASSOC);
75               if (!$client['client_id']) {
76                 // Set new client ID.
77                 $clientsecret = $utils->createClientSecret();
78                 $result = $db->prepare('INSERT INTO `oauth_clients` (`client_id`, `client_secret`, `redirect_uri`, `scope`, `user_id`) VALUES (:clientid, :secret, :rediruri, :scope, :userid);');
79                 if ($result->execute(array(':clientid' => $_GET['client_id'],
80                                            ':secret' => $clientsecret,
81                                            ':rediruri' => (strlen(@$_GET['redirect_uri']) ? $_GET['redirect_uri'] : ''),
82                                            ':scope' => (strlen(@$_GET['scope']) ? $_GET['scope'] : ''),
83                                            ':userid' => $user['id']))) {
84                   print(json_encode(array('success' => true, 'client_secret' => $clientsecret)));
85                 }
86                 else {
87                   $utils->log('client_save_failure', 'client: '.$client['client_id']);
88                   print(json_encode(array('error' => 'unexpected_save_failure',
89                                           'error_description' => 'Unexpectedly failed to save new client information.')));
90                 }
91               }
92               elseif ($client['user_id'] == $user['id']) {
93                 // The client ID was set by this user, set new secret and return.
94                 $clientsecret = $utils->createClientSecret();
95                 $result = $db->prepare('UPDATE `oauth_clients` SET `client_secret` = :secret WHERE `client_id` = :clientid;');
96                 if (!$result->execute(array(':secret' => $clientsecret,':clientid' => $client['client_id']))) {
97                   $utils->log('client_save_failure', 'client: '.$client['client_id'].', new secret - '.$result->errorInfo()[2]);
98                   print(json_encode(array('error' => 'unexpected_save_failure',
99                                           'error_description' => 'Unexpectedly failed to save new secret.')));
100                 }
101                 else {
102                   if (strlen(@$_GET['redirect_uri'])) {
103                     $result = $db->prepare('UPDATE `oauth_clients` SET `redirect_uri` = :rediruri WHERE `client_id` = :clientid;');
104                     if (!$result->execute(array(':rediruri' => $_GET['redirect_uri'],':clientid' => $client['client_id']))) {
105                       $utils->log('client_save_failure', 'client: '.$client['client_id'].', new redirect_uri: '.$_GET['redirect_uri'].' - '.$result->errorInfo()[2]);
106                     }
107                   }
108                   if (strlen(@$_GET['scope'])) {
109                     $result = $db->prepare('UPDATE `oauth_clients` SET `scope` = :scope WHERE `client_id` = :clientid;');
110                     if (!$result->execute(array(':scope' => $_GET['scope'],':clientid' => $client['client_id']))) {
111                       $utils->log('client_save_failure', 'client: '.$client['client_id'].', new scope: '.$_GET['scope'].' - '.$result->errorInfo()[2]);
112                     }
113                   }
114                   print(json_encode(array('success' => true, 'client_secret' => $clientsecret)));
115                 }
116               }
117               else {
118                 print(json_encode(array('error' => 'client_id_used',
119                                         'error_description' => 'This client ID is in use by a different user.')));
120               }
121             }
122             else {
123               print(json_encode(array('error' => 'invalid_client_id_',
124                                       'error_description' => 'A client ID of at least 5 characters needs to be supplied.')));
125             }
126           }
127           else {
128             print(json_encode(array('error' => 'insufficient_privileges',
129                                     'error_description' => 'This user is not allowed to register new clients.')));
130           }
131         }
132       }
133       else {
134         print(json_encode(array('error' => 'no_user',
135                                 'error_description' => 'The access token is not connected to a user.')));
136       }
137     }
138     else {
139       print(json_encode(array('error' => 'insufficient_scope',
140                               'error_description' => 'The scope of the token you used in this API request is insufficient to access this resource.')));
141     }
142   }
143   else {
144     print(json_encode(array('error' => 'invalid_resource',
145                             'error_description' => 'The resource requested from the API is unknown.')));
146   }
147 }
148 else {
149   print(json_encode(array('error' => 'insecure_connection',
150                           'error_description' => 'Your connection is insecure. The API can only be accessed on secure connections.')));
151 }
152 if ($settings['piwik_enabled']) {
153   $piwikTracker->doTrackPageView('API Request'.(strlen($token['scope'])?': '.$token['scope']:''));
154 }
155 ?>