]> git.mxchange.org Git - friendica.git/blob - library/oauth.php
FR update to the strings THX Perig
[friendica.git] / library / oauth.php
1 <?php
2
3 //ini_set('display_errors', 1);
4 //error_reporting(E_ALL | E_STRICT);
5
6 // Regex to filter out the client identifier
7 // (described in Section 2 of IETF draft)
8 // IETF draft does not prescribe a format for these, however
9 // I've arbitrarily chosen alphanumeric strings with hyphens and underscores, 3-12 characters long
10 // Feel free to change.
11 define("REGEX_CLIENT_ID", "/^[a-z0-9-_]{3,12}$/i");
12
13 // Used to define the name of the OAuth access token parameter (POST/GET/etc.)
14 // IETF Draft sections 5.2 and 5.3 specify that it should be called "oauth_token"
15 // but other implementations use things like "access_token"
16 // I won't be heartbroken if you change it, but it might be better to adhere to the spec
17 define("OAUTH_TOKEN_PARAM_NAME", "oauth_token");
18
19 // Client types (for client authorization)
20 //define("WEB_SERVER_CLIENT_TYPE", "web_server");
21 //define("USER_AGENT_CLIENT_TYPE", "user_agent");
22 //define("REGEX_CLIENT_TYPE", "/^(web_server|user_agent)$/");
23 define("ACCESS_TOKEN_AUTH_RESPONSE_TYPE", "token");
24 define("AUTH_CODE_AUTH_RESPONSE_TYPE", "code");
25 define("CODE_AND_TOKEN_AUTH_RESPONSE_TYPE", "code-and-token");
26 define("REGEX_AUTH_RESPONSE_TYPE", "/^(token|code|code-and-token)$/");
27
28 // Grant Types (for token obtaining)
29 define("AUTH_CODE_GRANT_TYPE", "authorization-code");
30 define("USER_CREDENTIALS_GRANT_TYPE", "basic-credentials");
31 define("ASSERTION_GRANT_TYPE", "assertion");
32 define("REFRESH_TOKEN_GRANT_TYPE", "refresh-token");
33 define("NONE_GRANT_TYPE", "none");
34 define("REGEX_TOKEN_GRANT_TYPE", "/^(authorization-code|basic-credentials|assertion|refresh-token|none)$/");
35
36 /* Error handling constants */
37
38 // HTTP status codes
39 define("ERROR_NOT_FOUND", "404 Not Found");
40 define("ERROR_BAD_REQUEST", "400 Bad Request");
41
42 // TODO: Extend for i18n
43
44 // "Official" OAuth 2.0 errors
45 define("ERROR_REDIRECT_URI_MISMATCH", "redirect-uri-mismatch");
46 define("ERROR_INVALID_CLIENT_CREDENTIALS", "invalid-client-credentials");
47 define("ERROR_UNAUTHORIZED_CLIENT", "unauthorized-client");
48 define("ERROR_USER_DENIED", "access-denied");
49 define("ERROR_INVALID_REQUEST", "invalid-request");
50 define("ERROR_INVALID_CLIENT_ID", "invalid-client-id");
51 define("ERROR_UNSUPPORTED_RESPONSE_TYPE", "unsupported-response-type");
52 define("ERROR_INVALID_SCOPE", "invalid-scope");
53 define("ERROR_INVALID_GRANT", "invalid-grant");
54
55 // Protected resource errors
56 define("ERROR_INVALID_TOKEN", "invalid-token");
57 define("ERROR_EXPIRED_TOKEN", "expired-token");
58 define("ERROR_INSUFFICIENT_SCOPE", "insufficient-scope");
59
60 // Messages
61 define("ERROR_INVALID_RESPONSE_TYPE", "Invalid response type.");
62
63 // Errors that we made up
64
65 // Error for trying to use a grant type that we haven't implemented
66 define("ERROR_UNSUPPORTED_GRANT_TYPE", "unsupported-grant-type");
67
68 abstract class OAuth2 {
69
70     /* Subclasses must implement the following functions */
71
72     // Make sure that the client id is valid
73     // If a secret is required, check that they've given the right one
74     // Must return false if the client credentials are invalid
75     abstract protected function auth_client_credentials($client_id, $client_secret = null);
76
77     // OAuth says we should store request URIs for each registered client
78     // Implement this function to grab the stored URI for a given client id
79     // Must return false if the given client does not exist or is invalid
80     abstract protected function get_redirect_uri($client_id);
81
82     // We need to store and retrieve access token data as we create and verify tokens
83     // Implement these functions to do just that
84
85     // Look up the supplied token id from storage, and return an array like:
86     //
87     //  array(
88     //      "client_id" => <stored client id>,
89     //      "expires" => <stored expiration timestamp>,
90     //      "scope" => <stored scope (may be null)
91     //  )
92     //
93     //  Return null if the supplied token is invalid
94     //
95     abstract protected function get_access_token($token_id);
96
97     // Store the supplied values
98     abstract protected function store_access_token($token_id, $client_id, $expires, $scope = null);
99
100     /*
101      *
102      * Stuff that should get overridden by subclasses
103      *
104      * I don't want to make these abstract, because then subclasses would have
105      * to implement all of them, which is too much work.
106      *
107      * So they're just stubs.  Override the ones you need.
108      *
109      */
110
111     // You should override this function with something,
112     // or else your OAuth provider won't support any grant types!
113     protected function get_supported_grant_types() {
114         // If you support all grant types, then you'd do:
115         // return array(
116         //             AUTH_CODE_GRANT_TYPE,
117         //             USER_CREDENTIALS_GRANT_TYPE,
118         //             ASSERTION_GRANT_TYPE,
119         //             REFRESH_TOKEN_GRANT_TYPE,
120         //             NONE_GRANT_TYPE
121         //     );
122
123         return array();
124     }
125
126     // You should override this function with your supported response types
127     protected function get_supported_auth_response_types() {
128         return array(
129             AUTH_CODE_AUTH_RESPONSE_TYPE,
130             ACCESS_TOKEN_AUTH_RESPONSE_TYPE,
131             CODE_AND_TOKEN_AUTH_RESPONSE_TYPE
132         );
133     }
134
135     // If you want to support scope use, then have this function return a list
136     // of all acceptable scopes (used to throw the invalid-scope error)
137     protected function get_supported_scopes() {
138         //  Example:
139         //  return array("my-friends", "photos", "whatever-else");
140         return array();
141     }
142
143     // If you want to restrict clients to certain authorization response types,
144     // override this function
145     // Given a client identifier and auth type, return true or false
146     // (auth type would be one of the values contained in REGEX_AUTH_RESPONSE_TYPE)
147     protected function authorize_client_response_type($client_id, $response_type) {
148         return true;
149     }
150
151     // If you want to restrict clients to certain grant types, override this function
152     // Given a client identifier and grant type, return true or false
153     protected function authorize_client($client_id, $grant_type) {
154         return true;
155     }
156
157     /* Functions that help grant access tokens for various grant types */
158
159     // Fetch authorization code data (probably the most common grant type)
160     // IETF Draft 4.1.1: http://tools.ietf.org/html/draft-ietf-oauth-v2-08#section-4.1.1
161     // Required for AUTH_CODE_GRANT_TYPE
162     protected function get_stored_auth_code($code) {
163         // Retrieve the stored data for the given authorization code
164         // Should return:
165         //
166         // array (
167         //  "client_id" => <stored client id>,
168         //  "redirect_uri" => <stored redirect URI>,
169         //  "expires" => <stored code expiration time>,
170         //  "scope" => <stored scope values (space-separated string), or can be omitted if scope is unused>
171         // )
172         //
173         // Return null if the code is invalid.
174
175         return null;
176     }
177
178     // Take the provided authorization code values and store them somewhere (db, etc.)
179     // Required for AUTH_CODE_GRANT_TYPE
180     protected function store_auth_code($code, $client_id, $redirect_uri, $expires, $scope) {
181         // This function should be the storage counterpart to get_stored_auth_code
182
183         // If storage fails for some reason, we're not currently checking
184         // for any sort of success/failure, so you should bail out of the
185         // script and provide a descriptive fail message
186     }
187
188     // Grant access tokens for basic user credentials
189     // IETF Draft 4.1.2: http://tools.ietf.org/html/draft-ietf-oauth-v2-08#section-4.1.2
190     // Required for USER_CREDENTIALS_GRANT_TYPE
191     protected function check_user_credentials($client_id, $username, $password) {
192         // Check the supplied username and password for validity
193         // You can also use the $client_id param to do any checks required
194         // based on a client, if you need that
195         // If the username and password are invalid, return false
196
197         // If the username and password are valid, and you want to verify the scope of
198         // a user's access, return an array with the scope values, like so:
199         //
200         // array (
201         //  "scope" => <stored scope values (space-separated string)>
202         // )
203         //
204         // We'll check the scope you provide against the requested scope before
205         // providing an access token.
206         //
207         // Otherwise, just return true.
208
209         return false;
210     }
211
212     // Grant access tokens for assertions
213     // IETF Draft 4.1.3: http://tools.ietf.org/html/draft-ietf-oauth-v2-08#section-4.1.3
214     // Required for ASSERTION_GRANT_TYPE
215     protected function check_assertion($client_id, $assertion_type, $assertion) {
216         // Check the supplied assertion for validity
217         // You can also use the $client_id param to do any checks required
218         // based on a client, if you need that
219         // If the assertion is invalid, return false
220
221         // If the assertion is valid, and you want to verify the scope of
222         // an access request, return an array with the scope values, like so:
223         //
224         // array (
225         //  "scope" => <stored scope values (space-separated string)>
226         // )
227         //
228         // We'll check the scope you provide against the requested scope before
229         // providing an access token.
230         //
231         // Otherwise, just return true.
232
233         return false;
234     }
235
236     // Grant refresh access tokens
237     // IETF Draft 4.1.4: http://tools.ietf.org/html/draft-ietf-oauth-v2-08#section-4.1.4
238     // Required for REFRESH_TOKEN_GRANT_TYPE
239     protected function get_refresh_token($refresh_token) {
240         // Retrieve the stored data for the given refresh token
241         // Should return:
242         //
243         // array (
244         //  "client_id" => <stored client id>,
245         //  "expires" => <refresh token expiration time>,
246         //  "scope" => <stored scope values (space-separated string), or can be omitted if scope is unused>
247         // )
248         //
249         // Return null if the token id is invalid.
250
251         return null;
252     }
253
254     // Store refresh access tokens
255     // Required for REFRESH_TOKEN_GRANT_TYPE
256     protected function store_refresh_token($token, $client_id, $expires, $scope = null) {
257         // If storage fails for some reason, we're not currently checking
258         // for any sort of success/failure, so you should bail out of the
259         // script and provide a descriptive fail message
260
261         return;
262     }
263
264     // Grant access tokens for the "none" grant type
265     // Not really described in the IETF Draft, so I just left a method stub...do whatever you want!
266     // Required for NONE_GRANT_TYPE
267     protected function check_none_access($client_id) {
268         return false;
269     }
270
271     protected function get_default_authentication_realm() {
272         // Change this to whatever authentication realm you want to send in a WWW-Authenticate header
273         return "Service";
274     }
275
276     /* End stuff that should get overridden */
277
278     private $access_token_lifetime = 3600;
279     private $auth_code_lifetime = 30;
280     private $refresh_token_lifetime = 1209600; // Two weeks
281
282     public function __construct($access_token_lifetime = 3600, $auth_code_lifetime = 30, $refresh_token_lifetime = 1209600) {
283         $this->access_token_lifetime = $access_token_lifetime;
284         $this->auth_code_lifetime = $auth_code_lifetime;
285         $this->refresh_token_lifetime = $refresh_token_lifetime;
286     }
287
288     /* Resource protecting (Section 5) */
289
290     // Check that a valid access token has been provided
291     //
292     // The scope parameter defines any required scope that the token must have
293     // If a scope param is provided and the token does not have the required scope,
294     // we bounce the request
295     //
296     // Some implementations may choose to return a subset of the protected resource
297     // (i.e. "public" data) if the user has not provided an access token
298     // or if the access token is invalid or expired
299     //
300     // The IETF spec says that we should send a 401 Unauthorized header and bail immediately
301     // so that's what the defaults are set to
302     //
303     // Here's what each parameter does:
304     // $scope = A space-separated string of required scope(s), if you want to check for scope
305     // $exit_not_present = If true and no access token is provided, send a 401 header and exit, otherwise return false
306     // $exit_invalid = If true and the implementation of get_access_token returns null, exit, otherwise return false
307     // $exit_expired = If true and the access token has expired, exit, otherwise return false
308     // $exit_scope = If true the access token does not have the required scope(s), exit, otherwise return false
309     // $realm = If you want to specify a particular realm for the WWW-Authenticate header, supply it here
310     public function verify_access_token($scope = null, $exit_not_present = true, $exit_invalid = true, $exit_expired = true, $exit_scope = true, $realm = null) {
311         $token_param = $this->get_access_token_param();
312         if ($token_param === false) // Access token was not provided
313             return $exit_not_present ? $this->send_401_unauthorized($realm, $scope) : false;
314
315         // Get the stored token data (from the implementing subclass)
316         $token = $this->get_access_token($token_param);
317         if ($token === null)
318             return $exit_invalid ? $this->send_401_unauthorized($realm, $scope, ERROR_INVALID_TOKEN) : false;
319
320         // Check token expiration (I'm leaving this check separated, later we'll fill in better error messages)
321         if (isset($token["expires"]) && time() > $token["expires"])
322             return $exit_expired ? $this->send_401_unauthorized($realm, $scope, ERROR_EXPIRED_TOKEN) : false;
323
324         // Check scope, if provided
325         // If token doesn't have a scope, it's null/empty, or it's insufficient, then throw an error
326         if ($scope &&
327                 (!isset($token["scope"]) || !$token["scope"] || !$this->check_scope($scope, $token["scope"])))
328             return $exit_scope ? $this->send_401_unauthorized($realm, $scope, ERROR_INSUFFICIENT_SCOPE) : false;
329
330         return true;
331     }
332
333
334     // Returns true if everything in required scope is contained in available scope
335     // False if something in required scope is not in available scope
336     private function check_scope($required_scope, $available_scope) {
337         // The required scope should match or be a subset of the available scope
338         if (!is_array($required_scope))
339             $required_scope = explode(" ", $required_scope);
340
341         if (!is_array($available_scope))
342             $available_scope = explode(" ", $available_scope);
343
344         return (count(array_diff($required_scope, $available_scope)) == 0);
345     }
346
347     // Send a 401 unauthorized header with the given realm
348     // and an error, if provided
349     private function send_401_unauthorized($realm, $scope, $error = null) {
350         $realm = $realm === null ? $this->get_default_authentication_realm() : $realm;
351
352         $auth_header = "WWW-Authenticate: Token realm='".$realm."'";
353
354         if ($scope)
355             $auth_header .= ", scope='".$scope."'";
356
357         if ($error !== null)
358             $auth_header .= ", error='".$error."'";
359
360         header("HTTP/1.1 401 Unauthorized");
361         header($auth_header);
362
363         exit;
364     }
365
366     // Pulls the access token out of the HTTP request
367     // Either from the Authorization header or GET/POST/etc.
368     // Returns false if no token is present
369     // TODO: Support POST or DELETE
370     private function get_access_token_param() {
371         $auth_header = $this->get_authorization_header();
372
373         if ($auth_header !== false) {
374             // Make sure only the auth header is set
375             if (isset($_GET[OAUTH_TOKEN_PARAM_NAME]) || isset($_POST[OAUTH_TOKEN_PARAM_NAME]))
376                 $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST);
377
378             $auth_header = trim($auth_header);
379
380             // Make sure it's Token authorization
381             if (strcmp(substr($auth_header, 0, 6),"Token ") !== 0)
382                 $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST);
383
384             // Parse the rest of the header
385             if (preg_match('/\s*token\s*="(.+)"/', substr($auth_header, 6), $matches) == 0 || count($matches) < 2)
386                 $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST);
387
388             return $matches[1];
389         }
390
391         if (isset($_GET[OAUTH_TOKEN_PARAM_NAME]))  {
392             if (isset($_POST[OAUTH_TOKEN_PARAM_NAME])) // Both GET and POST are not allowed
393                 $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST);
394
395             return $_GET[OAUTH_TOKEN_PARAM_NAME];
396         }
397
398         if (isset($_POST[OAUTH_TOKEN_PARAM_NAME]))
399             return $_POST[OAUTH_TOKEN_PARAM_NAME];
400
401         return false;
402     }
403
404     /* Access token granting (Section 4) */
405
406     // Grant or deny a requested access token
407     // This would be called from the "/token" endpoint as defined in the spec
408     // Obviously, you can call your endpoint whatever you want
409     public function grant_access_token() {
410         $filters = array(
411             "grant_type" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => REGEX_TOKEN_GRANT_TYPE), "flags" => FILTER_REQUIRE_SCALAR),
412             "scope" => array("flags" => FILTER_REQUIRE_SCALAR),
413             "code" => array("flags" => FILTER_REQUIRE_SCALAR),
414             "redirect_uri" => array("filter" => FILTER_VALIDATE_URL, "flags" => array(FILTER_FLAG_SCHEME_REQUIRED, FILTER_REQUIRE_SCALAR)),
415             "username" => array("flags" => FILTER_REQUIRE_SCALAR),
416             "password" => array("flags" => FILTER_REQUIRE_SCALAR),
417             "assertion_type" => array("flags" => FILTER_REQUIRE_SCALAR),
418             "assertion" => array("flags" => FILTER_REQUIRE_SCALAR),
419             "refresh_token" => array("flags" => FILTER_REQUIRE_SCALAR),
420         );
421
422         $input = filter_input_array(INPUT_POST, $filters);
423
424         // Grant Type must be specified.
425         if (!$input["grant_type"])
426             $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST);
427
428         // Make sure we've implemented the requested grant type
429         if (!in_array($input["grant_type"], $this->get_supported_grant_types()))
430             $this->error(ERROR_BAD_REQUEST, ERROR_UNSUPPORTED_GRANT_TYPE);
431
432         // Authorize the client
433         $client = $this->get_client_credentials();
434
435         if ($this->auth_client_credentials($client[0], $client[1]) === false)
436             $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_CLIENT_CREDENTIALS);
437
438         if (!$this->authorize_client($client[0], $input["grant_type"]))
439             $this->error(ERROR_BAD_REQUEST, ERROR_UNAUTHORIZED_CLIENT);
440
441         // Do the granting
442         switch ($input["grant_type"]) {
443             case AUTH_CODE_GRANT_TYPE:
444                 if (!$input["code"] || !$input["redirect_uri"])
445                     $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST);
446
447                 $stored = $this->get_stored_auth_code($input["code"]);
448
449                 if ($stored === null || $input["redirect_uri"] != $stored["redirect_uri"] || $client[0] != $stored["client_id"])
450                     $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_GRANT);
451
452                 if ($stored["expires"] > time())
453                     $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_GRANT);
454
455                 break;
456             case USER_CREDENTIALS_GRANT_TYPE:
457                 if (!$input["username"] || !$input["password"])
458                     $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST);
459
460                 $stored = $this->check_user_credentials($client[0], $input["username"], $input["password"]);
461
462                 if ($stored === false)
463                     $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_GRANT);
464
465                 break;
466             case ASSERTION_GRANT_TYPE:
467                 if (!$input["assertion_type"] || !$input["assertion"])
468                     $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST);
469
470                 $stored = $this->check_assertion($client[0], $input["assertion_type"], $input["assertion"]);
471
472                 if ($stored === false)
473                     $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_GRANT);
474
475                 break;
476             case REFRESH_TOKEN_GRANT_TYPE:
477                 if (!$input["refresh_token"])
478                     $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST);
479
480                 $stored = $this->get_refresh_token($input["refresh_token"]);
481
482                 if ($stored === null || $client[0] != $stored["client_id"])
483                     $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_GRANT);
484
485                 if ($stored["expires"] > time())
486                     $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_GRANT);
487
488                 break;
489             case NONE_GRANT_TYPE:
490                 $stored = $this->check_none_access($client[0]);
491
492                 if ($stored === false)
493                     $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST);
494         }
495
496         // Check scope, if provided
497         if ($input["scope"] && (!is_array($stored) || !isset($stored["scope"]) || !$this->check_scope($input["scope"], $stored["scope"])))
498             $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_SCOPE);
499
500         if (!$input["scope"])
501             $input["scope"] = null;
502
503         $token = $this->create_access_token($client[0], $input["scope"]);
504
505         $this->send_json_headers();
506         echo json_encode($token);
507     }
508
509     // Internal function used to get the client credentials from HTTP basic auth or POST data
510     // See http://tools.ietf.org/html/draft-ietf-oauth-v2-08#section-2
511     private function get_client_credentials() {
512         if (isset($_SERVER["PHP_AUTH_USER"]) && $_POST && isset($_POST["client_id"]))
513             $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_CLIENT_CREDENTIALS);
514
515         // Try basic auth
516         if (isset($_SERVER["PHP_AUTH_USER"]))
517             return array($_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]);
518
519         // Try POST
520         if ($_POST && isset($_POST["client_id"])) {
521             if (isset($_POST["client_secret"]))
522                 return array($_POST["client_id"], $_POST["client_secret"]);
523
524             return array($_POST["client_id"], NULL);
525         }
526
527         // No credentials were specified
528         $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_CLIENT_CREDENTIALS);
529     }
530
531     /* End-user/client Authorization (Section 3 of IETF Draft) */
532
533     // Pull the authorization request data out of the HTTP request
534     // and return it so the authorization server can prompt the user
535     // for approval
536     public function get_authorize_params() {
537         $filters = array(
538             "client_id" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => REGEX_CLIENT_ID), "flags" => FILTER_REQUIRE_SCALAR),
539             "response_type" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => REGEX_AUTH_RESPONSE_TYPE), "flags" => FILTER_REQUIRE_SCALAR),
540             "redirect_uri" => array("filter" => FILTER_VALIDATE_URL, "flags" => array(FILTER_FLAG_SCHEME_REQUIRED, FILTER_REQUIRE_SCALAR)),
541             "state" => array("flags" => FILTER_REQUIRE_SCALAR),
542             "scope" => array("flags" => FILTER_REQUIRE_SCALAR),
543         );
544
545         $input = filter_input_array(INPUT_GET, $filters);
546
547         // Make sure a valid client id was supplied
548         if (!$input["client_id"]) {
549             if ($input["redirect_uri"])
550                 $this->callback_error($input["redirect_uri"], ERROR_INVALID_CLIENT_ID, $input["state"]);
551
552             $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_CLIENT_ID); // We don't have a good URI to use
553         }
554
555         // redirect_uri is not required if already established via other channels
556         // check an existing redirect URI against the one supplied
557         $redirect_uri = $this->get_redirect_uri($input["client_id"]);
558
559         // At least one of: existing redirect URI or input redirect URI must be specified
560         if (!$redirect_uri && !$input["redirect_uri"])
561             $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST);
562
563         // get_redirect_uri should return false if the given client ID is invalid
564         // this probably saves us from making a separate db call, and simplifies the method set
565         if ($redirect_uri === false)
566             $this->callback_error($input["redirect_uri"], ERROR_INVALID_CLIENT_ID, $input["state"]);
567
568         // If there's an existing uri and one from input, verify that they match
569         if ($redirect_uri && $input["redirect_uri"]) {
570             // Ensure that the input uri starts with the stored uri
571             if (strcasecmp(substr($input["redirect_uri"], 0, strlen($redirect_uri)),$redirect_uri) !== 0)
572                 $this->callback_error($input["redirect_uri"], ERROR_REDIRECT_URI_MISMATCH, $input["state"]);
573         } elseif ($redirect_uri) { // They did not provide a uri from input, so use the stored one
574             $input["redirect_uri"] = $redirect_uri;
575         }
576
577         // type and client_id are required
578         if (!$input["response_type"])
579             $this->callback_error($input["redirect_uri"], ERROR_INVALID_REQUEST, $input["state"], ERROR_INVALID_RESPONSE_TYPE);
580
581         // Check requested auth response type against the list of supported types
582         if (array_search($input["response_type"], $this->get_supported_auth_response_types()) === false)
583             $this->callback_error($input["redirect_uri"], ERROR_UNSUPPORTED_RESPONSE_TYPE, $input["state"]);
584
585         // Validate that the requested scope is supported
586         if ($input["scope"] && !$this->check_scope($input["scope"], $this->get_supported_scopes()))
587             $this->callback_error($input["redirect_uri"], ERROR_INVALID_SCOPE, $input["state"]);
588
589         return $input;
590     }
591
592     // After the user has approved or denied the access request
593     // the authorization server should call this function to redirect
594     // the user appropriately
595
596     // The params all come from the results of get_authorize_params
597     // except for $is_authorized -- this is true or false depending on whether
598     // the user authorized the access
599     public function finish_client_authorization($is_authorized, $type, $client_id, $redirect_uri, $state, $scope = null) {
600         if ($state !== null)
601             $result["query"]["state"] = $state;
602
603         if ($is_authorized === false) {
604             $result["query"]["error"] = ERROR_USER_DENIED;
605         } else {
606             if ($type == AUTH_CODE_AUTH_RESPONSE_TYPE || $type == CODE_AND_TOKEN_AUTH_RESPONSE_TYPE)
607                 $result["query"]["code"] = $this->create_auth_code($client_id, $redirect_uri, $scope);
608
609             if ($type == ACCESS_TOKEN_AUTH_RESPONSE_TYPE || $type == CODE_AND_TOKEN_AUTH_RESPONSE_TYPE)
610                 $result["fragment"] = $this->create_access_token($client_id, $scope);
611         }
612
613         $this->do_redirect_uri_callback($redirect_uri, $result);
614     }
615
616     /* Other/utility functions */
617
618     private function do_redirect_uri_callback($redirect_uri, $result) {
619         header("HTTP/1.1 302 Found");
620         header("Location: " . $this->build_uri($redirect_uri, $result));
621         exit;
622     }
623
624     private function build_uri($uri, $data) {
625         $parse_url = parse_url($uri);
626
627         // Add our data to the parsed uri
628         foreach ($data as $k => $v) {
629             if (isset($parse_url[$k]))
630                 $parse_url[$k] .= "&" . http_build_query($v);
631             else
632                 $parse_url[$k] = http_build_query($v);
633         }
634
635         // Put humpty dumpty back together
636         return
637              ((isset($parse_url["scheme"])) ? $parse_url["scheme"] . "://" : "")
638             .((isset($parse_url["user"])) ? $parse_url["user"] . ((isset($parse_url["pass"])) ? ":" . $parse_url["pass"] : "") ."@" : "")
639             .((isset($parse_url["host"])) ? $parse_url["host"] : "")
640             .((isset($parse_url["port"])) ? ":" . $parse_url["port"] : "")
641             .((isset($parse_url["path"])) ? $parse_url["path"] : "")
642             .((isset($parse_url["query"])) ? "?" . $parse_url["query"] : "")
643             .((isset($parse_url["fragment"])) ? "#" . $parse_url["fragment"] : "");
644     }
645
646     // This belongs in a separate factory, but to keep it simple, I'm just keeping it here.
647     private function create_access_token($client_id, $scope) {
648         $token = array(
649             "access_token" => $this->gen_access_token(),
650             "expires_in" => $this->access_token_lifetime,
651             "scope" => $scope
652         );
653
654         $this->store_access_token($token["access_token"], $client_id, time() + $this->access_token_lifetime, $scope);
655
656         // Issue a refresh token also, if we support them
657         if (in_array(REFRESH_TOKEN_GRANT_TYPE, $this->get_supported_grant_types())) {
658             $token["refresh_token"] = $this->gen_access_token();
659             $this->store_refresh_token($token["refresh_token"], $client_id, time() + $this->refresh_token_lifetime, $scope);
660         }
661
662         return $token;
663     }
664
665     private function create_auth_code($client_id, $redirect_uri, $scope) {
666         $code = $this->gen_auth_code();
667         $this->store_auth_code($code, $client_id, $redirect_uri, time() + $this->auth_code_lifetime, $scope);
668         return $code;
669     }
670
671     // Implementing classes may want to override these two functions
672     // to implement other access token or auth code generation schemes
673     private function gen_access_token() {
674         return base64_encode(pack('N6', mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand()));
675     }
676
677     private function gen_auth_code() {
678         return base64_encode(pack('N6', mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand()));
679     }
680
681     // Implementing classes may need to override this function for use on non-Apache web servers
682     // Just pull out the Authorization HTTP header and return it
683     // Return false if the Authorization header does not exist
684     private function get_authorization_header() {
685         if (array_key_exists("HTTP_AUTHORIZATION", $_SERVER))
686             return $_SERVER["HTTP_AUTHORIZATION"];
687
688         if (function_exists("apache_request_headers")) {
689             $headers = apache_request_headers();
690
691             if (array_key_exists("Authorization", $headers))
692                 return $headers["Authorization"];
693         }
694
695         return false;
696     }
697
698     private function send_json_headers() {
699         header("Content-Type: application/json");
700         header("Cache-Control: no-store");
701     }
702
703     public function error($code, $message = null) {
704         header("HTTP/1.1 " . $code);
705
706         if ($message) {
707             $this->send_json_headers();
708             echo json_encode(array("error" => $message));
709         }
710
711         exit;
712     }
713
714     public function callback_error($redirect_uri, $error, $state, $message = null, $error_uri = null) {
715         $result["query"]["error"] = $error;
716
717         if ($state)
718             $result["query"]["state"] = $state;
719
720         if ($message)
721             $result["query"]["error_description"] = $message;
722
723         if ($error_uri)
724             $result["query"]["error_uri"] = $error_uri;
725
726         $this->do_redirect_uri_callback($redirect_uri, $result);
727     }
728 }