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