source: sandbox/2.4-expresso-api/prototype/library/oauth2/lib/OAuth2.php @ 5888

Revision 5888, 51.6 KB checked in by cristiano, 12 years ago (diff)

Ticket #2598 - implementação base REST + oauth

  • Property svn:executable set to *
Line 
1<?php
2require_once ROOTPATH . '/library/oauth2/lib/OAuth2ServerException.php';
3require_once ROOTPATH . '/library/oauth2/lib/OAuth2AuthenticateException.php';
4require_once ROOTPATH . '/library/oauth2/lib/OAuth2RedirectException.php';
5
6/**
7 * @mainpage
8 * OAuth 2.0 server in PHP, originally written for
9 * <a href="http://www.opendining.net/"> Open Dining</a>. Supports
10 * <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-20">IETF draft v20</a>.
11 *
12 * Source repo has sample servers implementations for
13 * <a href="http://php.net/manual/en/book.pdo.php"> PHP Data Objects</a> and
14 * <a href="http://www.mongodb.org/">MongoDB</a>. Easily adaptable to other
15 * storage engines.
16 *
17 * PHP Data Objects supports a variety of databases, including MySQL,
18 * Microsoft SQL Server, SQLite, and Oracle, so you can try out the sample
19 * to see how it all works.
20 *
21 * We're expanding the wiki to include more helpful documentation, but for
22 * now, your best bet is to view the oauth.php source - it has lots of
23 * comments.
24 *
25 * @author Tim Ridgely <tim.ridgely@gmail.com>
26 * @author Aaron Parecki <aaron@parecki.com>
27 * @author Edison Wong <hswong3i@pantarei-design.com>
28 * @author David Rochwerger <catch.dave@gmail.com>
29 *
30 * @see http://code.google.com/p/oauth2-php/
31 * @see https://github.com/quizlet/oauth2-php
32 */
33
34/**
35 * OAuth2.0 draft v20 server-side implementation.
36 *
37 * @todo Add support for Message Authentication Code (MAC) token type.
38 *
39 * @author Originally written by Tim Ridgely <tim.ridgely@gmail.com>.
40 * @author Updated to draft v10 by Aaron Parecki <aaron@parecki.com>.
41 * @author Debug, coding style clean up and documented by Edison Wong <hswong3i@pantarei-design.com>.
42 * @author Refactored (including separating from raw POST/GET) and updated to draft v20 by David Rochwerger <catch.dave@gmail.com>.
43 */
44class OAuth2 {
45       
46        /**
47         * Array of persistent variables stored.
48         */
49        protected $conf = array();
50       
51        /**
52         * Storage engine for authentication server
53         *
54         * @var IOAuth2Storage
55         */
56        protected $storage;
57       
58        /**
59         * Keep track of the old refresh token. So we can unset
60         * the old refresh tokens when a new one is issued.
61         *
62         * @var string
63         */
64        protected $oldRefreshToken;
65       
66        /**
67         * Default values for configuration options.
68         *
69         * @var int
70         * @see OAuth2::setDefaultOptions()
71         */
72        const DEFAULT_ACCESS_TOKEN_LIFETIME = 3600;
73        const DEFAULT_REFRESH_TOKEN_LIFETIME = 1209600;
74        const DEFAULT_AUTH_CODE_LIFETIME = 3600;
75        const DEFAULT_WWW_REALM = 'Service';
76       
77        /**
78         * Configurable options.
79         *
80         * @var string
81         */
82        const CONFIG_ACCESS_LIFETIME = 3600; // The lifetime of access token in seconds.
83        const CONFIG_REFRESH_LIFETIME = 3600; // The lifetime of refresh token in seconds.
84        const CONFIG_AUTH_LIFETIME = 3600; // The lifetime of auth code in seconds.
85        const CONFIG_SUPPORTED_SCOPES = 'supported_scopes'; // Array of scopes you want to support
86        const CONFIG_TOKEN_TYPE = 'token_type'; // Token type to respond with. Currently only "Bearer" supported.
87        const CONFIG_WWW_REALM = 'realm';
88        const CONFIG_ENFORCE_INPUT_REDIRECT = 'enforce_redirect'; // Set to true to enforce redirect_uri on input for both authorize and token steps.
89        const CONFIG_ENFORCE_STATE = 'enforce_state'; // Set to true to enforce state to be passed in authorization (see http://tools.ietf.org/html/draft-ietf-oauth-v2-21#section-10.12)
90       
91
92        /**
93         * Regex to filter out the client identifier (described in Section 2 of IETF draft).
94         *
95         * IETF draft does not prescribe a format for these, however I've arbitrarily
96         * chosen alphanumeric strings with hyphens and underscores, 3-32 characters
97         * long.
98         *
99         * Feel free to change.
100         */
101        const CLIENT_ID_REGEXP = '/^[a-z0-9-_]{3,32}$/i';
102       
103        /**
104         * @defgroup oauth2_section_5 Accessing a Protected Resource
105         * @{
106         *
107         * Clients access protected resources by presenting an access token to
108         * the resource server. Access tokens act as bearer tokens, where the
109         * token string acts as a shared symmetric secret. This requires
110         * treating the access token with the same care as other secrets (e.g.
111         * end-user passwords). Access tokens SHOULD NOT be sent in the clear
112         * over an insecure channel.
113         *
114         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-7
115         */
116       
117        /**
118         * Used to define the name of the OAuth access token parameter
119         * (POST & GET). This is for the "bearer" token type.
120         * Other token types may use different methods and names.
121         *
122         * IETF Draft section 2 specifies that it should be called "access_token"
123         *
124         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-06#section-2.2
125         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-06#section-2.3
126         */
127        const TOKEN_PARAM_NAME = 'access_token';
128       
129        /**
130         * When using the bearer token type, there is a specifc Authorization header
131         * required: "Bearer"
132         *
133         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-04#section-2.1
134         */
135        const TOKEN_BEARER_HEADER_NAME = 'Bearer';
136       
137        /**
138         * @}
139         */
140       
141        /**
142         * @defgroup oauth2_section_4 Obtaining Authorization
143         * @{
144         *
145         * When the client interacts with an end-user, the end-user MUST first
146         * grant the client authorization to access its protected resources.
147         * Once obtained, the end-user authorization grant is expressed as an
148         * authorization code which the client uses to obtain an access token.
149         * To obtain an end-user authorization, the client sends the end-user to
150         * the end-user authorization endpoint.
151         *
152         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4
153         */
154       
155        /**
156         * List of possible authentication response types.
157         * The "authorization_code" mechanism exclusively supports 'code'
158         * and the "implicit" mechanism exclusively supports 'token'.
159         *
160         * @var string
161         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.1
162         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.1
163         */
164        const RESPONSE_TYPE_AUTH_CODE = 'code';
165        const RESPONSE_TYPE_ACCESS_TOKEN = 'token';
166       
167        /**
168         * @}
169         */
170       
171        /**
172         * @defgroup oauth2_section_5 Obtaining an Access Token
173         * @{
174         *
175         * The client obtains an access token by authenticating with the
176         * authorization server and presenting its authorization grant (in the form of
177         * an authorization code, resource owner credentials, an assertion, or a
178         * refresh token).
179         *
180         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4
181         */
182       
183        /**
184         * Grant types support by draft 20
185         */
186        const GRANT_TYPE_AUTH_CODE = 'authorization_code';
187        const GRANT_TYPE_IMPLICIT = 'token';
188        const GRANT_TYPE_USER_CREDENTIALS = 'password';
189        const GRANT_TYPE_CLIENT_CREDENTIALS = 'client_credentials';
190        const GRANT_TYPE_REFRESH_TOKEN = 'refresh_token';
191        const GRANT_TYPE_EXTENSIONS = 'extensions';
192       
193        /**
194         * Regex to filter out the grant type.
195         * NB: For extensibility, the grant type can be a URI
196         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.5
197         */
198        const GRANT_TYPE_REGEXP = '#^(authorization_code|token|password|client_credentials|refresh_token|http://.*)$#';
199       
200        /**
201         * @}
202         */
203       
204        /**
205         * Possible token types as defined by draft 20.
206         *
207         * TODO: Add support for mac (and maybe other types?)
208         *
209         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-7.1
210         */
211        const TOKEN_TYPE_BEARER = 'bearer';
212        const TOKEN_TYPE_MAC = 'mac'; // Currently unsupported
213       
214
215        /**
216         * @defgroup self::HTTP_status HTTP status code
217         * @{
218         */
219       
220        /**
221         * HTTP status codes for successful and error states as specified by draft 20.
222         *
223         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2
224         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
225         */
226        const HTTP_FOUND = '302 Found';
227        const HTTP_BAD_REQUEST = '400 Bad Request';
228        const HTTP_UNAUTHORIZED = '401 Unauthorized';
229        const HTTP_FORBIDDEN = '403 Forbidden';
230        const HTTP_UNAVAILABLE = '503 Service Unavailable';
231       
232        /**
233         * @}
234         */
235       
236        /**
237         * @defgroup oauth2_error Error handling
238         * @{
239         *
240         * @todo Extend for i18n.
241         * @todo Consider moving all error related functionality into a separate class.
242         */
243       
244        /**
245         * The request is missing a required parameter, includes an unsupported
246         * parameter or parameter value, or is otherwise malformed.
247         *
248         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
249         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
250         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
251         */
252        const ERROR_INVALID_REQUEST = 'invalid_request';
253       
254        /**
255         * The client identifier provided is invalid.
256         *
257         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
258         */
259        const ERROR_INVALID_CLIENT = 'invalid_client';
260       
261        /**
262         * The client is not authorized to use the requested response type.
263         *
264         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
265         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
266         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
267         */
268        const ERROR_UNAUTHORIZED_CLIENT = 'unauthorized_client';
269       
270        /**
271         * The redirection URI provided does not match a pre-registered value.
272         *
273         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-3.1.2.4
274         */
275        const ERROR_REDIRECT_URI_MISMATCH = 'redirect_uri_mismatch';
276       
277        /**
278         * The end-user or authorization server denied the request.
279         * This could be returned, for example, if the resource owner decides to reject
280         * access to the client at a later point.
281         *
282         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
283         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
284         */
285        const ERROR_USER_DENIED = 'access_denied';
286       
287        /**
288         * The requested response type is not supported by the authorization server.
289         *
290         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
291         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
292         */
293        const ERROR_UNSUPPORTED_RESPONSE_TYPE = 'unsupported_response_type';
294       
295        /**
296         * The requested scope is invalid, unknown, or malformed.
297         *
298         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
299         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
300         */
301        const ERROR_INVALID_SCOPE = 'invalid_scope';
302       
303        /**
304         * The provided authorization grant is invalid, expired,
305         * revoked, does not match the redirection URI used in the
306         * authorization request, or was issued to another client.
307         *
308         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
309         */
310        const ERROR_INVALID_GRANT = 'invalid_grant';
311       
312        /**
313         * The authorization grant is not supported by the authorization server.
314         *
315         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
316         */
317        const ERROR_UNSUPPORTED_GRANT_TYPE = 'unsupported_grant_type';
318       
319        /**
320         * The request requires higher privileges than provided by the access token.
321         * The resource server SHOULD respond with the HTTP 403 (Forbidden) status
322         * code and MAY include the "scope" attribute with the scope necessary to
323         * access the protected resource.
324         *
325         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
326         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
327         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
328         */
329        const ERROR_INSUFFICIENT_SCOPE = 'invalid_scope';
330
331        /**
332         * @}
333         */
334       
335        /**
336         * Creates an OAuth2.0 server-side instance.
337         *
338         * @param $config - An associative array as below of config options. See CONFIG_* constants.
339         */
340        public function __construct(IOAuth2Storage $storage, $config = array()) {
341                $this->storage = $storage;
342               
343                // Configuration options
344                $this->setDefaultOptions();
345                foreach ( $config as $name => $value ) {
346                        $this->setVariable($name, $value);
347                }
348        }
349
350        /**
351         * Default configuration options are specified here.
352         */
353        protected function setDefaultOptions() {
354                $this->conf = array(
355                        self::CONFIG_ACCESS_LIFETIME => self::DEFAULT_ACCESS_TOKEN_LIFETIME,
356                        self::CONFIG_REFRESH_LIFETIME => self::DEFAULT_REFRESH_TOKEN_LIFETIME,
357                        self::CONFIG_AUTH_LIFETIME => self::DEFAULT_AUTH_CODE_LIFETIME,
358                        self::CONFIG_WWW_REALM => self::DEFAULT_WWW_REALM,
359                        self::CONFIG_TOKEN_TYPE => self::TOKEN_TYPE_BEARER,
360                        self::CONFIG_ENFORCE_INPUT_REDIRECT => FALSE,
361                        self::CONFIG_ENFORCE_STATE => FALSE,
362                        self::CONFIG_SUPPORTED_SCOPES => array() // This is expected to be passed in on construction. Scopes can be an aribitrary string.
363                ); 
364        }
365
366        /**
367         * Returns a persistent variable.
368         *
369         * @param $name
370         * The name of the variable to return.
371         * @param $default
372         * The default value to use if this variable has never been set.
373         *
374         * @return
375         * The value of the variable.
376         */
377        public function getVariable($name, $default = NULL) {
378                $name = strtolower($name);
379               
380                return isset($this->conf[$name]) ? $this->conf[$name] : $default;
381        }
382
383        /**
384         * Sets a persistent variable.
385         *
386         * @param $name
387         * The name of the variable to set.
388         * @param $value
389         * The value to set.
390         */
391        public function setVariable($name, $value) {
392                $name = strtolower($name);
393               
394                $this->conf[$name] = $value;
395                return $this;
396        }
397
398        // Resource protecting (Section 5).
399       
400
401        /**
402         * Check that a valid access token has been provided.
403         * The token is returned (as an associative array) if valid.
404         *
405         * The scope parameter defines any required scope that the token must have.
406         * If a scope param is provided and the token does not have the required
407         * scope, we bounce the request.
408         *
409         * Some implementations may choose to return a subset of the protected
410         * resource (i.e. "public" data) if the user has not provided an access
411         * token or if the access token is invalid or expired.
412         *
413         * The IETF spec says that we should send a 401 Unauthorized header and
414         * bail immediately so that's what the defaults are set to. You can catch
415         * the exception thrown and behave differently if you like (log errors, allow
416         * public access for missing tokens, etc)
417         *
418         * @param $scope
419         * A space-separated string of required scope(s), if you want to check
420         * for scope.
421         * @return array
422         * Token
423         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-7
424         *
425         * @ingroup oauth2_section_7
426         */
427        public function verifyAccessToken($token_param, $scope = NULL) {
428                $tokenType = $this->getVariable(self::CONFIG_TOKEN_TYPE);
429                $realm = $this->getVariable(self::CONFIG_WWW_REALM);
430               
431                if (!$token_param) { // Access token was not provided
432                        throw new OAuth2AuthenticateException(self::HTTP_BAD_REQUEST, $tokenType, $realm, self::ERROR_INVALID_REQUEST, 'The request is missing a required parameter, includes an unsupported parameter or parameter value, repeats the same parameter, uses more than one method for including an access token, or is otherwise malformed.', $scope);
433                }
434               
435                // Get the stored token data (from the implementing subclass)
436                $token = $this->storage->getAccessToken($token_param);
437                if ($token === NULL) {
438                        throw new OAuth2AuthenticateException(self::HTTP_UNAUTHORIZED, $tokenType, $realm, self::ERROR_INVALID_GRANT, 'The access token provided is invalid.', $scope);
439                }
440               
441                // Check we have a well formed token
442                if (!isset($token["expires"]) || !isset($token["client_id"])) {
443                        throw new OAuth2AuthenticateException(self::HTTP_UNAUTHORIZED, $tokenType, $realm, self::ERROR_INVALID_GRANT, 'Malformed token (missing "expires" or "client_id")', $scope);
444                }
445               
446                // Check token expiration (expires is a mandatory paramter)
447                if (isset($token["expires"]) && time() > $token["expires"]) {
448                        throw new OAuth2AuthenticateException(self::HTTP_UNAUTHORIZED, $tokenType, $realm, self::ERROR_INVALID_GRANT, 'The access token provided has expired.', $scope);
449                }
450               
451                // Check scope, if provided
452                // If token doesn't have a scope, it's NULL/empty, or it's insufficient, then throw an error
453                if ($scope && (!isset($token["scope"]) || !$token["scope"] || !$this->checkScope($scope, $token["scope"]))) {
454                        throw new OAuth2AuthenticateException(self::HTTP_FORBIDDEN, $tokenType, $realm, self::ERROR_INSUFFICIENT_SCOPE, 'The request requires higher privileges than provided by the access token.', $scope);
455                }
456               
457               
458               
459                session_write_close(); //Fecha session anterior
460                session_id($token['refresh_token']); //Define o id da session o mesmo do resfresh token
461                session_start();
462               
463                return $token;
464        }
465
466        /**
467         * This is a convenience function that can be used to get the token, which can then
468         * be passed to verifyAccessToken(). The constraints specified by the draft are
469         * attempted to be adheared to in this method.
470         *
471         * As per the Bearer spec (draft 8, section 2) - there are three ways for a client
472         * to specify the bearer token, in order of preference: Authorization Header,
473         * POST and GET.
474         *
475         * NB: Resource servers MUST accept tokens via the Authorization scheme
476         * (http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-08#section-2).
477         *
478         * @todo Should we enforce TLS/SSL in this function?
479         *
480         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-08#section-2.1
481         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-08#section-2.2
482         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-08#section-2.3
483         *
484         * Old Android version bug (at least with version 2.2)
485         * @see http://code.google.com/p/android/issues/detail?id=6684
486         *
487         * We don't want to test this functionality as it relies on superglobals and headers:
488         * @codeCoverageIgnoreStart
489         */
490        public function getBearerToken() {
491           
492                if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
493                        $headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
494                } elseif (function_exists('apache_request_headers')) {
495                        $requestHeaders = apache_request_headers();
496                       
497                        // Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
498                        $requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
499                       
500                        if (isset($requestHeaders['Authorization'])) {
501                                $headers = trim($requestHeaders['Authorization']);
502                        }
503                }
504               
505                $tokenType = $this->getVariable(self::CONFIG_TOKEN_TYPE);
506                $realm = $this->getVariable(self::CONFIG_WWW_REALM);
507                // Check that exactly one method was used
508                $methodsUsed = !empty($headers) + isset($_GET[self::TOKEN_PARAM_NAME]) + isset($_POST[self::TOKEN_PARAM_NAME]);
509                if ($methodsUsed > 1) {
510                        throw new OAuth2AuthenticateException(self::HTTP_BAD_REQUEST, $tokenType, $realm, self::ERROR_INVALID_REQUEST, 'Only one method may be used to authenticate at a time (Auth header, GET or POST).');
511                } elseif ($methodsUsed == 0) {
512                        throw new OAuth2AuthenticateException(self::HTTP_BAD_REQUEST, $tokenType, $realm, self::ERROR_INVALID_REQUEST, 'The access token was not found.');
513                }
514               
515                // HEADER: Get the access token from the header
516                if (!empty($headers)) {
517                        if (!preg_match('/' . self::TOKEN_BEARER_HEADER_NAME . '\s(\S+)/', $headers, $matches)) {
518                                throw new OAuth2AuthenticateException(self::HTTP_BAD_REQUEST, $tokenType, $realm, self::ERROR_INVALID_REQUEST, 'Malformed auth header');
519                        }
520                       
521                        return $matches[1];
522                }               
523                // POST: Get the token from POST data
524                if (isset($_POST[self::TOKEN_PARAM_NAME])) {
525                        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
526                                throw new OAuth2AuthenticateException(self::HTTP_BAD_REQUEST, $tokenType, $realm, self::ERROR_INVALID_REQUEST, 'When putting the token in the body, the method must be POST.');
527                        }
528                       
529                        // IETF specifies content-type. NB: Not all webservers populate this _SERVER variable
530                        if (isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] != 'application/x-www-form-urlencoded') {
531                                throw new OAuth2AuthenticateException(self::HTTP_BAD_REQUEST, $tokenType, $realm, self::ERROR_INVALID_REQUEST, 'The content type for POST requests must be "application/x-www-form-urlencoded"');
532                        }
533                       
534                        return $_POST[self::TOKEN_PARAM_NAME];
535                }
536               
537                // GET method
538                return $_GET[self::TOKEN_PARAM_NAME];
539        }
540
541        /** @codeCoverageIgnoreEnd */
542       
543        /**
544         * Check if everything in required scope is contained in available scope.
545         *
546         * @param $required_scope
547         * Required scope to be check with.
548         *
549         * @return
550         * TRUE if everything in required scope is contained in available scope,
551         * and False if it isn't.
552         *
553         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-7
554         *
555         * @ingroup oauth2_section_7
556         */
557        private function checkScope($required_scope, $available_scope) {
558                // The required scope should match or be a subset of the available scope
559                if (!is_array($required_scope)) {
560                        $required_scope = explode(' ', trim($required_scope));
561                }
562               
563                if (!is_array($available_scope)) {
564                        $available_scope = explode(' ', trim($available_scope));
565                }
566               
567                return (count(array_diff($required_scope, $available_scope)) == 0);
568        }
569
570        // Access token granting (Section 4).
571       
572
573        /**
574         * Grant or deny a requested access token.
575         * This would be called from the "/token" endpoint as defined in the spec.
576         * Obviously, you can call your endpoint whatever you want.
577         *
578         * @param $inputData - The draft specifies that the parameters should be
579         * retrieved from POST, but you can override to whatever method you like.
580         * @throws OAuth2ServerException
581         *
582         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4
583         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-21#section-10.6
584         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-21#section-4.1.3
585         *
586         * @ingroup oauth2_section_4
587         */
588//ORIGINAL URI 
589//      public function grantAccessToken(array $inputData = NULL, array $authHeaders = NULL) {
590//              $filters = array(
591//                      "grant_type" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => self::GRANT_TYPE_REGEXP), "flags" => FILTER_REQUIRE_SCALAR),
592//                      "scope" => array("flags" => FILTER_REQUIRE_SCALAR),
593//                      "code" => array("flags" => FILTER_REQUIRE_SCALAR),
594//                      "redirect_uri" => array("filter" => FILTER_SANITIZE_URL),
595//                      "username" => array("flags" => FILTER_REQUIRE_SCALAR),
596//                      "password" => array("flags" => FILTER_REQUIRE_SCALAR),
597//                      "refresh_token" => array("flags" => FILTER_REQUIRE_SCALAR),
598//              );
599//             
600//              // Input data by default can be either POST or GET
601//              if (!isset($inputData)) {
602//                      $inputData = ($_SERVER['REQUEST_METHOD'] == 'POST') ? $_POST : $_GET;
603//              }
604//             
605//              // Basic authorization header
606//              $authHeaders = isset($authHeaders) ? $authHeaders : $this->getAuthorizationHeader();
607//             
608//               
609//               
610//              // Filter input data
611//              $input = filter_var_array($inputData, $filters);
612//             
613//             
614//               
615//              // Grant Type must be specified.
616//              if (!$input["grant_type"]) {
617//                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Invalid grant_type parameter or parameter missing');
618//              }
619//             
620//              // Authorize the client
621//              $client = $this->getClientCredentials($inputData, $authHeaders);
622//         
623//              if ($this->storage->checkClientCredentials($client[0], $client[1]) === FALSE) {
624//                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, 'The client credentials are invalid');
625//              }
626//             
627//              if (!$this->storage->checkRestrictedGrantType($client[0], $input["grant_type"])) {
628//                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNAUTHORIZED_CLIENT, 'The grant type is unauthorized for this client_id');
629//              }
630//             
631//              // Do the granting
632//              //
633//              switch ($input["grant_type"]) {
634//                      case self::GRANT_TYPE_AUTH_CODE:
635//                              if (!($this->storage instanceof IOAuth2GrantCode)) {
636//                                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
637//                              }
638//                             
639//                              if (!$input["code"]) {
640//                                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Missing parameter. "code" is required');
641//                              }
642//                             
643//                              if ($this->getVariable(self::CONFIG_ENFORCE_INPUT_REDIRECT) && !$input["redirect_uri"]) {
644//                                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, "The redirect URI parameter is required.");
645//                              }
646//                             
647//                              $stored = $this->storage->getAuthCode($input["code"]);
648//                             
649//                              // Check the code exists
650//                              if ($stored === NULL || $client[0] != $stored["client_id"]) {
651//                                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, "Refresh token doesn't exist or is invalid for the client");
652//                              }
653//                             
654//                              // Validate the redirect URI. If a redirect URI has been provided on input, it must be validated
655//                              if ($input["redirect_uri"] && !$this->validateRedirectUri($input["redirect_uri"], $stored["redirect_uri"])) {
656//                                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_REDIRECT_URI_MISMATCH, "The redirect URI is missing or do not match");
657//                              }
658//                             
659//                              if ($stored["expires"] < time()) {
660//                                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, "The authorization code has expired");
661//                              }
662//                              break;
663//                     
664//                      case self::GRANT_TYPE_USER_CREDENTIALS:
665//                              if (!($this->storage instanceof IOAuth2GrantUser)) {
666//                                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
667//                              }
668//                             
669//                              if (!$input["username"] || !$input["password"]) {
670//                                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Missing parameters. "username" and "password" required');
671//                              }
672//                             
673//                              $stored = $this->storage->checkUserCredentials($client[0], $input["username"], $input["password"]);
674//
675//                              if ($stored === FALSE) {
676//                                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT);
677//                              }
678//                              break;
679//                     
680//                      case self::GRANT_TYPE_CLIENT_CREDENTIALS:
681//                              if (!($this->storage instanceof IOAuth2GrantClient)) {
682//                                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
683//                              }
684//                             
685//                              if (empty($client[1])) {
686//                                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, 'The client_secret is mandatory for the "client_credentials" grant type');
687//                              }
688//                              // NB: We don't need to check for $stored==false, because it was checked above already
689//                              $stored = $this->storage->checkClientCredentialsGrant($client[0], $client[1]);
690//                              break;
691//                     
692//                      case self::GRANT_TYPE_REFRESH_TOKEN:
693//                              if (!($this->storage instanceof IOAuth2RefreshTokens)) {
694//                                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
695//                              }
696//                             
697//                              if (!$input["refresh_token"]) {
698//                                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'No "refresh_token" parameter found');
699//                              }
700//                             
701//                              $stored = $this->storage->getRefreshToken($input["refresh_token"]);
702//                             
703//                              if ($stored === NULL || $client[0] != $stored["client_id"]) {
704//                                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, 'Invalid refresh token');
705//                              }
706//                             
707//                              if ($stored["expires"] < time()) {
708//                                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, 'Refresh token has expired');
709//                              }
710//                             
711//                              // store the refresh token locally so we can delete it when a new refresh token is generated
712//                              $this->oldRefreshToken = $stored["refresh_token"];
713//                              break;
714//                     
715//                      case self::GRANT_TYPE_IMPLICIT:
716//                              /* TODO: NOT YET IMPLEMENTED */
717//                              throw new OAuth2ServerException('501 Not Implemented', 'This OAuth2 library is not yet complete. This functionality is not implemented yet.');
718//                              if (!($this->storage instanceof IOAuth2GrantImplicit)) {
719//                                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
720//                              }
721//                             
722//                              break;
723//                     
724//                      // Extended grant types:
725//                      case filter_var($input["grant_type"], FILTER_VALIDATE_URL):
726//                              if (!($this->storage instanceof IOAuth2GrantExtension)) {
727//                                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
728//                              }
729//                              $uri = filter_var($input["grant_type"], FILTER_VALIDATE_URL);
730//                              $stored = $this->storage->checkGrantExtension($uri, $inputData, $authHeaders);
731//                             
732//                              if ($stored === FALSE) {
733//                                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT);
734//                              }
735//                              break;
736//                     
737//                      default :
738//                              throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Invalid grant_type parameter or parameter missing');
739//              }
740//             
741//              if (!isset($stored["scope"])) {
742//                      $stored["scope"] = NULL;
743//              }
744//             
745//              // Check scope, if provided
746//              if ($input["scope"] && (!is_array($stored) || !isset($stored["scope"]) || !$this->checkScope($input["scope"], $stored["scope"]))) {
747//                      throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_SCOPE, 'An unsupported scope was requested.');
748//              }
749//             
750//              $user_id = isset($stored['user_id']) ? $stored['user_id'] : null;
751//              $token = $this->createAccessToken($client[0], $user_id, $stored['scope']);
752//             
753//     
754//              // Send response
755//              $this->sendJsonHeaders();
756//              echo json_encode($token);
757//      }
758       
759        public function grantAccessToken(array $inputData = NULL, array $authHeaders = NULL) {
760                $filters = array(
761                        "grant_type" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => self::GRANT_TYPE_REGEXP), "flags" => FILTER_REQUIRE_SCALAR),
762                        "scope" => array("flags" => FILTER_REQUIRE_SCALAR),
763                        "code" => array("flags" => FILTER_REQUIRE_SCALAR),
764                        "redirect_uri" => array("filter" => FILTER_SANITIZE_URL),
765                        "username" => array("flags" => FILTER_REQUIRE_SCALAR),
766                        "password" => array("flags" => FILTER_REQUIRE_SCALAR),
767                        "refresh_token" => array("flags" => FILTER_REQUIRE_SCALAR),
768                );
769               
770                // Input data by default can be either POST or GET
771                if (!isset($inputData)) {
772                        $inputData = ($_SERVER['REQUEST_METHOD'] == 'POST') ? $_POST : $_GET;
773                }
774               
775                // Basic authorization header
776                $authHeaders = isset($authHeaders) ? $authHeaders : $this->getAuthorizationHeader();
777               
778               
779               
780                // Filter input data
781                $input = filter_var_array($inputData, $filters);
782               
783             
784               
785                // Grant Type must be specified.
786                if (!$input["grant_type"]) {
787                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Invalid grant_type parameter or parameter missing');
788                }
789               
790                // Authorize the client
791                $client = $this->getClientCredentials($inputData, $authHeaders);
792         
793                if ($this->storage->checkClientCredentials($client[0], $client[1]) === FALSE) {
794                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, 'The client credentials are invalid');
795                }
796               
797                if (!$this->storage->checkRestrictedGrantType($client[0], $input["grant_type"])) {
798                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNAUTHORIZED_CLIENT, 'The grant type is unauthorized for this client_id');
799                }
800               
801                // Do the granting
802                //
803                switch ($input["grant_type"]) {
804                        case self::GRANT_TYPE_AUTH_CODE:
805                                if (!($this->storage instanceof IOAuth2GrantCode)) {
806                                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
807                                }
808                               
809                                if (!$input["code"]) {
810                                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Missing parameter. "code" is required');
811                                }
812                               
813                                if ($this->getVariable(self::CONFIG_ENFORCE_INPUT_REDIRECT) && !$input["redirect_uri"]) {
814                                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, "The redirect URI parameter is required.");
815                                }
816                               
817                                $stored = $this->storage->getAuthCode($input["code"]);
818                               
819                                // Check the code exists
820                                if ($stored === NULL || $client[0] != $stored["client_id"]) {
821                                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, "Refresh token doesn't exist or is invalid for the client");
822                                }
823                               
824                                // Validate the redirect URI. If a redirect URI has been provided on input, it must be validated
825                                if ($input["redirect_uri"] && !$this->validateRedirectUri($input["redirect_uri"], $stored["redirect_uri"])) {
826                                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_REDIRECT_URI_MISMATCH, "The redirect URI is missing or do not match");
827                                }
828                               
829                                if ($stored["expires"] < time()) {
830                                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, "The authorization code has expired");
831                                }
832                                break;
833                       
834                        case self::GRANT_TYPE_USER_CREDENTIALS:
835                                if (!($this->storage instanceof IOAuth2GrantUser)) {
836                                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
837                                }
838                               
839                                if (!$input["username"] || !$input["password"]) {
840                                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Missing parameters. "username" and "password" required');
841                                }
842                               
843                                $stored = $this->storage->checkUserCredentials($client[0], $input["username"], $input["password"]);
844
845                                if ($stored === FALSE) {
846                                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT);
847                                }
848                                break;
849                       
850                        case self::GRANT_TYPE_CLIENT_CREDENTIALS:
851                                if (!($this->storage instanceof IOAuth2GrantClient)) {
852                                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
853                                }
854                               
855                                if (empty($client[1])) {
856                                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, 'The client_secret is mandatory for the "client_credentials" grant type');
857                                }
858                                // NB: We don't need to check for $stored==false, because it was checked above already
859                                $stored = $this->storage->checkClientCredentialsGrant($client[0], $client[1]);
860                                break;
861                       
862                        case self::GRANT_TYPE_REFRESH_TOKEN:
863                                if (!($this->storage instanceof IOAuth2RefreshTokens)) {
864                                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
865                                }
866                               
867                                if (!$input["refresh_token"]) {
868                                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'No "refresh_token" parameter found');
869                                }
870                               
871                                $stored = $this->storage->getRefreshToken($input["refresh_token"]);
872                               
873                                if ($stored === NULL || $client[0] != $stored["client_id"]) {
874                                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, 'Invalid refresh token');
875                                }
876                               
877                                if ($stored["expires"] < time()) {
878                                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, 'Refresh token has expired');
879                                }
880                               
881                                // store the refresh token locally so we can delete it when a new refresh token is generated
882                                $this->oldRefreshToken = $stored["refresh_token"];
883                               
884                                session_write_close(); //Fecha session anterior
885                                session_id($stored['refresh_token']); //Define o id da session o mesmo do resfresh token
886                                session_start();
887                               
888                                break;
889                       
890                        case self::GRANT_TYPE_IMPLICIT:
891                                /* TODO: NOT YET IMPLEMENTED */
892                                throw new OAuth2ServerException('501 Not Implemented', 'This OAuth2 library is not yet complete. This functionality is not implemented yet.');
893                                if (!($this->storage instanceof IOAuth2GrantImplicit)) {
894                                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
895                                }
896                               
897                                break;
898                       
899                        // Extended grant types:
900                        case filter_var($input["grant_type"], FILTER_VALIDATE_URL):
901                                if (!($this->storage instanceof IOAuth2GrantExtension)) {
902                                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
903                                }
904                                $uri = filter_var($input["grant_type"], FILTER_VALIDATE_URL);
905                                $stored = $this->storage->checkGrantExtension($uri, $inputData, $authHeaders);
906                               
907                                if ($stored === FALSE) {
908                                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT);
909                                }
910                                break;
911                       
912                        default :
913                                throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Invalid grant_type parameter or parameter missing');
914                }
915               
916                if (!isset($stored["scope"])) {
917                        $stored["scope"] = NULL;
918                }
919               
920                // Check scope, if provided
921                if ($input["scope"] && (!is_array($stored) || !isset($stored["scope"]) || !$this->checkScope($input["scope"], $stored["scope"]))) {
922                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_SCOPE, 'An unsupported scope was requested.');
923                }
924               
925                $user_id = isset($stored['user_id']) ? $stored['user_id'] : null;
926                $token = $this->createAccessToken($client[0], $user_id, $stored['scope']);
927               
928                //Gerando Session Para o refresh_token
929                session_write_close(); //Fecha session anterior
930                session_start();
931                session_id($token['refresh_token']); //Define o id da session o mesmo do resfresh token
932                session_cache_expire(self::CONFIG_REFRESH_LIFETIME); //Define o tempo da session o mesmo do Refresh token       
933               
934                if(isset($input["username"]) && isset($input["password"]))
935                {
936                    $_SESSION['wallet']['user']['uid'] =     $input["username"];
937                    $_SESSION['wallet']['user']['password']       =  $input["password"];
938                    $_SESSION['wallet']['user']['uidNumber']       =  $user_id;
939                }
940               
941               
942               
943                //session_write_close(); //Fecha nova session
944               
945                // Send response
946                $this->sendJsonHeaders();
947                echo json_encode($token);
948        }
949
950        /**
951         * Internal function used to get the client credentials from HTTP basic
952         * auth or POST data.
953         *
954         * According to the spec (draft 20), the client_id can be provided in
955         * the Basic Authorization header (recommended) or via GET/POST.
956         *
957         * @return
958         * A list containing the client identifier and password, for example
959         * @code
960         * return array(
961         * CLIENT_ID,
962         * CLIENT_SECRET
963         * );
964         * @endcode
965         *
966         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-2.4.1
967         *
968         * @ingroup oauth2_section_2
969         */
970        protected function getClientCredentials(array $inputData, array $authHeaders) {
971               
972                // Basic Authentication is used
973                if (!empty($authHeaders['PHP_AUTH_USER'])) {
974                        return array($authHeaders['PHP_AUTH_USER'], $authHeaders['PHP_AUTH_PW']);
975                } elseif (empty($inputData['client_id'])) { // No credentials were specified
976                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, 'Client id was not found in the headers or body');
977                } else {
978                        // This method is not recommended, but is supported by specification
979                        return array($inputData['client_id'], $inputData['client_secret']);
980                }
981        }
982
983        // End-user/client Authorization (Section 2 of IETF Draft).
984       
985
986        /**
987         * Pull the authorization request data out of the HTTP request.
988         * - The redirect_uri is OPTIONAL as per draft 20. But your implementation can enforce it
989         * by setting CONFIG_ENFORCE_INPUT_REDIRECT to true.
990         * - The state is OPTIONAL but recommended to enforce CSRF. Draft 21 states, however, that
991         * CSRF protection is MANDATORY. You can enforce this by setting the CONFIG_ENFORCE_STATE to true.
992         *
993         * @param $inputData - The draft specifies that the parameters should be
994         * retrieved from GET, but you can override to whatever method you like.
995         * @return
996         * The authorization parameters so the authorization server can prompt
997         * the user for approval if valid.
998         *
999         * @throws OAuth2ServerException
1000         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.1
1001         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-21#section-10.12
1002         *
1003         * @ingroup oauth2_section_3
1004         */
1005        public function getAuthorizeParams(array $inputData = NULL) {
1006                $filters = array(
1007                        "client_id" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => self::CLIENT_ID_REGEXP), "flags" => FILTER_REQUIRE_SCALAR),
1008                        "response_type" => array("flags" => FILTER_REQUIRE_SCALAR),
1009                        "redirect_uri" => array("filter" => FILTER_SANITIZE_URL),
1010                        "state" => array("flags" => FILTER_REQUIRE_SCALAR),
1011                        "scope" => array("flags" => FILTER_REQUIRE_SCALAR)
1012                );
1013               
1014                if (!isset($inputData)) {
1015                        $inputData = $_GET;
1016                }
1017                $input = filter_var_array($inputData, $filters);
1018               
1019                // Make sure a valid client id was supplied (we can not redirect because we were unable to verify the URI)
1020                if (!$input["client_id"]) {
1021                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, "No client id supplied"); // We don't have a good URI to use
1022                }
1023               
1024                // Get client details
1025                $stored = $this->storage->getClientDetails($input["client_id"]);
1026                if ($stored === FALSE) {
1027                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, "Client id does not exist");
1028                }
1029               
1030                // Make sure a valid redirect_uri was supplied. If specified, it must match the stored URI.
1031                // @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-3.1.2
1032                // @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
1033                // @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
1034                if (!$input["redirect_uri"] && !$stored["redirect_uri"]) {
1035                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_REDIRECT_URI_MISMATCH, 'No redirect URL was supplied or stored.');
1036                }
1037                if ($this->getVariable(self::CONFIG_ENFORCE_INPUT_REDIRECT) && !$input["redirect_uri"]) {
1038                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_REDIRECT_URI_MISMATCH, 'The redirect URI is mandatory and was not supplied.');
1039                }
1040                // Only need to validate if redirect_uri provided on input and stored.
1041                if ($stored["redirect_uri"] && $input["redirect_uri"] && !$this->validateRedirectUri($input["redirect_uri"], $stored["redirect_uri"])) {
1042                        throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_REDIRECT_URI_MISMATCH, 'The redirect URI provided is missing or does not match');
1043                }
1044               
1045                // Select the redirect URI
1046                $input["redirect_uri"] = isset($input["redirect_uri"]) ? $input["redirect_uri"] : $stored["redirect_uri"];
1047               
1048                // type and client_id are required
1049                if (!$input["response_type"]) {
1050                        throw new OAuth2RedirectException($input["redirect_uri"], self::ERROR_INVALID_REQUEST, 'Invalid or missing response type.', $input["state"]);
1051                }
1052               
1053                // Check requested auth response type against interfaces of storage engine
1054                $reflect = new ReflectionClass($this->storage);
1055                if (!$reflect->hasConstant('RESPONSE_TYPE_' . strtoupper($input['response_type']))) {
1056                        throw new OAuth2RedirectException($input["redirect_uri"], self::ERROR_UNSUPPORTED_RESPONSE_TYPE, NULL, $input["state"]);
1057                }
1058               
1059                // Validate that the requested scope is supported
1060                if ($input["scope"] && !$this->checkScope($input["scope"], $this->getVariable(self::CONFIG_SUPPORTED_SCOPES))) {
1061                        throw new OAuth2RedirectException($input["redirect_uri"], self::ERROR_INVALID_SCOPE, 'An unsupported scope was requested.', $input["state"]);
1062                }
1063               
1064                // Validate state parameter exists (if configured to enforce this)
1065                if ($this->getVariable(self::CONFIG_ENFORCE_STATE) && !$input["state"]) {
1066                        throw new OAuth2RedirectException($input["redirect_uri"], self::ERROR_INVALID_REQUEST, "The state parameter is required.");
1067                }
1068               
1069                // Return retrieved client details together with input
1070                return ($input + $stored);
1071        }
1072
1073        /**
1074         * Redirect the user appropriately after approval.
1075         *
1076         * After the user has approved or denied the access request the
1077         * authorization server should call this function to redirect the user
1078         * appropriately.
1079         *
1080         * @param $is_authorized
1081         * TRUE or FALSE depending on whether the user authorized the access.
1082         * @param $user_id
1083         * Identifier of user who authorized the client
1084         * @param $params
1085         * An associative array as below:
1086         * - response_type: The requested response: an access token, an
1087         * authorization code, or both.
1088         * - client_id: The client identifier as described in Section 2.
1089         * - redirect_uri: An absolute URI to which the authorization server
1090         * will redirect the user-agent to when the end-user authorization
1091         * step is completed.
1092         * - scope: (optional) The scope of the access request expressed as a
1093         * list of space-delimited strings.
1094         * - state: (optional) An opaque value used by the client to maintain
1095         * state between the request and callback.
1096         *
1097         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4
1098         *
1099         * @ingroup oauth2_section_4
1100         */
1101        public function finishClientAuthorization($is_authorized, $user_id = NULL, $params = array()) {
1102               
1103                // We repeat this, because we need to re-validate. In theory, this could be POSTed
1104                // by a 3rd-party (because we are not internally enforcing NONCEs, etc)
1105                $params = $this->getAuthorizeParams($params);
1106               
1107                $params += array('scope' => NULL, 'state' => NULL);
1108                extract($params);
1109               
1110                if ($state !== NULL) {
1111                        $result["query"]["state"] = $state;
1112                }
1113               
1114                if ($is_authorized === FALSE) {
1115                        throw new OAuth2RedirectException($redirect_uri, self::ERROR_USER_DENIED, "The user denied access to your application", $state);
1116                } else {
1117                        if ($response_type == self::RESPONSE_TYPE_AUTH_CODE) {
1118                                $result["query"]["code"] = $this->createAuthCode($client_id, $user_id, $redirect_uri, $scope);
1119                        } elseif ($response_type == self::RESPONSE_TYPE_ACCESS_TOKEN) {
1120                                $result["fragment"] = $this->createAccessToken($client_id, $user_id, $scope);
1121                        }
1122                }
1123               
1124                $this->doRedirectUriCallback($redirect_uri, $result);
1125        }
1126
1127        // Other/utility functions.
1128       
1129
1130        /**
1131         * Redirect the user agent.
1132         *
1133         * Handle both redirect for success or error response.
1134         *
1135         * @param $redirect_uri
1136         * An absolute URI to which the authorization server will redirect
1137         * the user-agent to when the end-user authorization step is completed.
1138         * @param $params
1139         * Parameters to be pass though buildUri().
1140         *
1141         * @ingroup oauth2_section_4
1142         */
1143        private function doRedirectUriCallback($redirect_uri, $params) {
1144                header("HTTP/1.1 " . self::HTTP_FOUND);
1145                header("Location: " . $this->buildUri($redirect_uri, $params));
1146                exit();
1147        }
1148
1149        /**
1150         * Build the absolute URI based on supplied URI and parameters.
1151         *
1152         * @param $uri
1153         * An absolute URI.
1154         * @param $params
1155         * Parameters to be append as GET.
1156         *
1157         * @return
1158         * An absolute URI with supplied parameters.
1159         *
1160         * @ingroup oauth2_section_4
1161         */
1162        private function buildUri($uri, $params) {
1163                $parse_url = parse_url($uri);
1164               
1165                // Add our params to the parsed uri
1166                foreach ( $params as $k => $v ) {
1167                        if (isset($parse_url[$k])) {
1168                                $parse_url[$k] .= "&" . http_build_query($v);
1169                        } else {
1170                                $parse_url[$k] = http_build_query($v);
1171                        }
1172                }
1173               
1174                // Put humpty dumpty back together
1175                return
1176                        ((isset($parse_url["scheme"])) ? $parse_url["scheme"] . "://" : "")
1177                        . ((isset($parse_url["user"])) ? $parse_url["user"]
1178                        . ((isset($parse_url["pass"])) ? ":" . $parse_url["pass"] : "") . "@" : "")
1179                        . ((isset($parse_url["host"])) ? $parse_url["host"] : "")
1180                        . ((isset($parse_url["port"])) ? ":" . $parse_url["port"] : "")
1181                        . ((isset($parse_url["path"])) ? $parse_url["path"] : "")
1182                        . ((isset($parse_url["query"])) ? "?" . $parse_url["query"] : "")
1183                        . ((isset($parse_url["fragment"])) ? "#" . $parse_url["fragment"] : "")
1184                ;
1185        }
1186
1187        /**
1188         * Handle the creation of access token, also issue refresh token if support.
1189         *
1190         * This belongs in a separate factory, but to keep it simple, I'm just
1191         * keeping it here.
1192         *
1193         * @param $client_id
1194         * Client identifier related to the access token.
1195         * @param $scope
1196         * (optional) Scopes to be stored in space-separated string.
1197         *
1198         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5
1199         * @ingroup oauth2_section_5
1200         */
1201// Função ORIGINAL;   
1202//      protected function createAccessToken($client_id, $user_id, $scope = NULL) {
1203//             
1204//              $token = array(
1205//                      "access_token" => $this->genAccessToken(),
1206//                      "expires_in" => $this->getVariable(self::CONFIG_ACCESS_LIFETIME),
1207//                      "token_type" => $this->getVariable(self::CONFIG_TOKEN_TYPE),
1208//                      "scope" => $scope
1209//              );
1210//             
1211//              $this->storage->setAccessToken($token["access_token"], $client_id, $user_id, time() + $this->getVariable(self::CONFIG_ACCESS_LIFETIME), $scope);
1212//             
1213//              // Issue a refresh token also, if we support them
1214//              if ($this->storage instanceof IOAuth2RefreshTokens) {
1215//                      $token["refresh_token"] = $this->genAccessToken();
1216//                      $this->storage->setRefreshToken($token["refresh_token"], $client_id, $user_id, time() + $this->getVariable(self::CONFIG_REFRESH_LIFETIME), $scope);
1217//                     
1218//                      // If we've granted a new refresh token, expire the old one
1219//                      if ($this->oldRefreshToken) {
1220//                              $this->storage->unsetRefreshToken($this->oldRefreshToken);
1221//                              unset($this->oldRefreshToken);
1222//                      }
1223//              }
1224//             
1225//              return $token;
1226//      }
1227        protected function createAccessToken($client_id, $user_id, $scope = NULL) {
1228               
1229                $token = array(
1230                        "access_token" => $this->genAccessToken(),
1231                        "expires_in" => $this->getVariable(self::CONFIG_ACCESS_LIFETIME),
1232                        "token_type" => $this->getVariable(self::CONFIG_TOKEN_TYPE),
1233                        "scope" => $scope
1234                );
1235                $token["refresh_token"] = $this->genAccessToken();
1236               
1237                $this->storage->setAccessToken($token["access_token"], $client_id, $user_id, time() + $this->getVariable(self::CONFIG_ACCESS_LIFETIME), $scope , $token['refresh_token']);
1238               
1239                // Issue a refresh token also, if we support them
1240                if ($this->storage instanceof IOAuth2RefreshTokens) {
1241                        $this->storage->setRefreshToken($token["refresh_token"], $client_id, $user_id, time() + $this->getVariable(self::CONFIG_REFRESH_LIFETIME), $scope);
1242                       
1243                        // If we've granted a new refresh token, expire the old one
1244                        if ($this->oldRefreshToken) {
1245                                $this->storage->unsetRefreshToken($this->oldRefreshToken);
1246                                unset($this->oldRefreshToken);
1247                        }
1248                }
1249               
1250                return $token;
1251        }
1252
1253        /**
1254         * Handle the creation of auth code.
1255         *
1256         * This belongs in a separate factory, but to keep it simple, I'm just
1257         * keeping it here.
1258         *
1259         * @param $client_id
1260         * Client identifier related to the access token.
1261         * @param $redirect_uri
1262         * An absolute URI to which the authorization server will redirect the
1263         * user-agent to when the end-user authorization step is completed.
1264         * @param $scope
1265         * (optional) Scopes to be stored in space-separated string.
1266         *
1267         * @ingroup oauth2_section_4
1268         */
1269        private function createAuthCode($client_id, $user_id, $redirect_uri, $scope = NULL) {
1270                $code = $this->genAuthCode();
1271                $this->storage->setAuthCode($code, $client_id, $user_id, $redirect_uri, time() + $this->getVariable(self::CONFIG_AUTH_LIFETIME), $scope);
1272                return $code;
1273        }
1274
1275        /**
1276         * Generates an unique access token.
1277         *
1278         * Implementing classes may want to override this function to implement
1279         * other access token generation schemes.
1280         *
1281         * @return
1282         * An unique access token.
1283         *
1284         * @ingroup oauth2_section_4
1285         * @see OAuth2::genAuthCode()
1286         */
1287        protected function genAccessToken() {
1288                $tokenLen = 40;
1289                if (file_exists('/dev/urandom')) { // Get 100 bytes of random data
1290                        $randomData = file_get_contents('/dev/urandom', false, null, 0, 100) . uniqid(mt_rand(), true);
1291                } else {
1292                        $randomData = mt_rand() . mt_rand() . mt_rand() . mt_rand() . microtime(true) . uniqid(mt_rand(), true);
1293                }
1294                return substr(hash('sha512', $randomData), 0, $tokenLen);
1295        }
1296
1297        /**
1298         * Generates an unique auth code.
1299         *
1300         * Implementing classes may want to override this function to implement
1301         * other auth code generation schemes.
1302         *
1303         * @return
1304         * An unique auth code.
1305         *
1306         * @ingroup oauth2_section_4
1307         * @see OAuth2::genAccessToken()
1308         */
1309        protected function genAuthCode() {
1310                return $this->genAccessToken(); // let's reuse the same scheme for token generation
1311        }
1312
1313        /**
1314         * Pull out the Authorization HTTP header and return it.
1315         * According to draft 20, standard basic authorization is the only
1316         * header variable required (this does not apply to extended grant types).
1317         *
1318         * Implementing classes may need to override this function if need be.
1319         *
1320         * @todo We may need to re-implement pulling out apache headers to support extended grant types
1321         *
1322         * @return
1323         * An array of the basic username and password provided.
1324         *
1325         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-2.4.1
1326         * @ingroup oauth2_section_2
1327         */
1328        protected function getAuthorizationHeader() {
1329                return array(
1330                        'PHP_AUTH_USER' => isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '',
1331                        'PHP_AUTH_PW' => isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : ''
1332                );
1333        }
1334
1335        /**
1336         * Send out HTTP headers for JSON.
1337         *
1338         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.1
1339         * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
1340         *
1341         * @ingroup oauth2_section_5
1342         */
1343        private function sendJsonHeaders() {
1344                if (php_sapi_name() === 'cli' || headers_sent()) {
1345                        return;
1346                }
1347               
1348                header("Content-Type: application/json");
1349                header("Cache-Control: no-store");
1350        }
1351
1352        /**
1353         * Internal method for validating redirect URI supplied
1354         * @param string $inputUri
1355         * @param string $storedUri
1356         */
1357        protected function validateRedirectUri($inputUri, $storedUri) {
1358                if (!$inputUri || !$storedUri) {
1359                        return false; // if either one is missing, assume INVALID
1360                }
1361                return strcasecmp(substr($inputUri, 0, strlen($storedUri)), $storedUri) === 0;
1362        }
1363}
Note: See TracBrowser for help on using the repository browser.