Updated packages and code to python3. Won't work with python 2
[twitter-api-cdsw-solutions] / oauthlib / oauth2 / rfc6749 / clients / mobile_application.py
1 # -*- coding: utf-8 -*-
2 """
3 oauthlib.oauth2.rfc6749
4 ~~~~~~~~~~~~~~~~~~~~~~~
5
6 This module is an implementation of various logic needed
7 for consuming and providing OAuth 2.0 RFC6749.
8 """
9 from __future__ import absolute_import, unicode_literals
10
11 from .base import Client
12 from ..parameters import prepare_grant_uri
13 from ..parameters import parse_implicit_response
14
15
16 class MobileApplicationClient(Client):
17
18     """A public client utilizing the implicit code grant workflow.
19
20     A user-agent-based application is a public client in which the
21     client code is downloaded from a web server and executes within a
22     user-agent (e.g. web browser) on the device used by the resource
23     owner.  Protocol data and credentials are easily accessible (and
24     often visible) to the resource owner.  Since such applications
25     reside within the user-agent, they can make seamless use of the
26     user-agent capabilities when requesting authorization.
27
28     The implicit grant type is used to obtain access tokens (it does not
29     support the issuance of refresh tokens) and is optimized for public
30     clients known to operate a particular redirection URI.  These clients
31     are typically implemented in a browser using a scripting language
32     such as JavaScript.
33
34     As a redirection-based flow, the client must be capable of
35     interacting with the resource owner's user-agent (typically a web
36     browser) and capable of receiving incoming requests (via redirection)
37     from the authorization server.
38
39     Unlike the authorization code grant type in which the client makes
40     separate requests for authorization and access token, the client
41     receives the access token as the result of the authorization request.
42
43     The implicit grant type does not include client authentication, and
44     relies on the presence of the resource owner and the registration of
45     the redirection URI.  Because the access token is encoded into the
46     redirection URI, it may be exposed to the resource owner and other
47     applications residing on the same device.
48     """
49
50     def prepare_request_uri(self, uri, redirect_uri=None, scope=None,
51                             state=None, **kwargs):
52         """Prepare the implicit grant request URI.
53
54         The client constructs the request URI by adding the following
55         parameters to the query component of the authorization endpoint URI
56         using the "application/x-www-form-urlencoded" format, per `Appendix B`_:
57
58         :param redirect_uri:  OPTIONAL. The redirect URI must be an absolute URI
59                               and it should have been registerd with the OAuth
60                               provider prior to use. As described in `Section 3.1.2`_.
61
62         :param scope:  OPTIONAL. The scope of the access request as described by
63                        Section 3.3`_. These may be any string but are commonly
64                        URIs or various categories such as ``videos`` or ``documents``.
65
66         :param state:   RECOMMENDED.  An opaque value used by the client to maintain
67                         state between the request and callback.  The authorization
68                         server includes this value when redirecting the user-agent back
69                         to the client.  The parameter SHOULD be used for preventing
70                         cross-site request forgery as described in `Section 10.12`_.
71
72         :param kwargs:  Extra arguments to include in the request URI.
73
74         In addition to supplied parameters, OAuthLib will append the ``client_id``
75         that was provided in the constructor as well as the mandatory ``response_type``
76         argument, set to ``token``::
77
78             >>> from oauthlib.oauth2 import MobileApplicationClient
79             >>> client = MobileApplicationClient('your_id')
80             >>> client.prepare_request_uri('https://example.com')
81             'https://example.com?client_id=your_id&response_type=token'
82             >>> client.prepare_request_uri('https://example.com', redirect_uri='https://a.b/callback')
83             'https://example.com?client_id=your_id&response_type=token&redirect_uri=https%3A%2F%2Fa.b%2Fcallback'
84             >>> client.prepare_request_uri('https://example.com', scope=['profile', 'pictures'])
85             'https://example.com?client_id=your_id&response_type=token&scope=profile+pictures'
86             >>> client.prepare_request_uri('https://example.com', foo='bar')
87             'https://example.com?client_id=your_id&response_type=token&foo=bar'
88
89         .. _`Appendix B`: http://tools.ietf.org/html/rfc6749#appendix-B
90         .. _`Section 2.2`: http://tools.ietf.org/html/rfc6749#section-2.2
91         .. _`Section 3.1.2`: http://tools.ietf.org/html/rfc6749#section-3.1.2
92         .. _`Section 3.3`: http://tools.ietf.org/html/rfc6749#section-3.3
93         .. _`Section 10.12`: http://tools.ietf.org/html/rfc6749#section-10.12
94         """
95         return prepare_grant_uri(uri, self.client_id, 'token',
96                                  redirect_uri=redirect_uri, state=state, scope=scope, **kwargs)
97
98     def parse_request_uri_response(self, uri, state=None, scope=None):
99         """Parse the response URI fragment.
100
101         If the resource owner grants the access request, the authorization
102         server issues an access token and delivers it to the client by adding
103         the following parameters to the fragment component of the redirection
104         URI using the "application/x-www-form-urlencoded" format:
105
106         :param uri: The callback URI that resulted from the user being redirected
107                     back from the provider to you, the client.
108         :param state: The state provided in the authorization request.
109         :param scope: The scopes provided in the authorization request.
110         :return: Dictionary of token parameters.
111         :raises: OAuth2Error if response is invalid.
112
113         A successful response should always contain
114
115         **access_token**
116                 The access token issued by the authorization server. Often
117                 a random string.
118
119         **token_type**
120             The type of the token issued as described in `Section 7.1`_.
121             Commonly ``Bearer``.
122
123         **state**
124             If you provided the state parameter in the authorization phase, then
125             the provider is required to include that exact state value in the
126             response.
127
128         While it is not mandated it is recommended that the provider include
129
130         **expires_in**
131             The lifetime in seconds of the access token.  For
132             example, the value "3600" denotes that the access token will
133             expire in one hour from the time the response was generated.
134             If omitted, the authorization server SHOULD provide the
135             expiration time via other means or document the default value.
136
137         **scope**
138             Providers may supply this in all responses but are required to only
139             if it has changed since the authorization request.
140
141         A few example responses can be seen below::
142
143             >>> response_uri = 'https://example.com/callback#access_token=sdlfkj452&state=ss345asyht&token_type=Bearer&scope=hello+world'
144             >>> from oauthlib.oauth2 import MobileApplicationClient
145             >>> client = MobileApplicationClient('your_id')
146             >>> client.parse_request_uri_response(response_uri)
147             {
148                 'access_token': 'sdlfkj452',
149                 'token_type': 'Bearer',
150                 'state': 'ss345asyht',
151                 'scope': [u'hello', u'world']
152             }
153             >>> client.parse_request_uri_response(response_uri, state='other')
154             Traceback (most recent call last):
155                 File "<stdin>", line 1, in <module>
156                 File "oauthlib/oauth2/rfc6749/__init__.py", line 598, in parse_request_uri_response
157                     **scope**
158                 File "oauthlib/oauth2/rfc6749/parameters.py", line 197, in parse_implicit_response
159                     raise ValueError("Mismatching or missing state in params.")
160             ValueError: Mismatching or missing state in params.
161             >>> def alert_scope_changed(message, old, new):
162             ...     print(message, old, new)
163             ...
164             >>> oauthlib.signals.scope_changed.connect(alert_scope_changed)
165             >>> client.parse_request_body_response(response_body, scope=['other'])
166             ('Scope has changed from "other" to "hello world".', ['other'], ['hello', 'world'])
167
168         .. _`Section 7.1`: http://tools.ietf.org/html/rfc6749#section-7.1
169         .. _`Section 3.3`: http://tools.ietf.org/html/rfc6749#section-3.3
170         """
171         self.token = parse_implicit_response(uri, state=state, scope=scope)
172         self._populate_attributes(self.token)
173         return self.token

Benjamin Mako Hill || Want to submit a patch?