def refresh(self, refresh_token=None): """Get a new access token from the supplied refresh token https://svn.tools.ietf.org/html/draft-hammer-oauth2-00#section-4 """ endpoint = 'access_token' refresh_token = refresh_token or self.refresh_token if not refresh_token: raise ValueError("refresh_token can't be empty") args = { 'grant_type': 'refresh_token', 'client_id': self._api_key, 'refresh_token': refresh_token, } uri = urlparse.urljoin(self.BASE_URL, endpoint) body = urlencode(args) headers = { 'Content-Type': 'application/x-www-form-urlencoded', } req = Request(uri, body, headers) resp = urlopen(req) content = resp.read() if not resp.code == 200: raise Error(content) response_args = dict(parse_qsl(content)) self.access_token = response_args.get("access_token", None) self.refresh_token = response_args.get("refresh_token", None) return response_args
def request(self, method, url, bearer_auth=True, **req_kwargs): ''' A loose wrapper around Requests' :class:`~requests.sessions.Session` which injects OAuth 2.0 parameters. :param method: A string representation of the HTTP method to be used. :type method: str :param url: The resource to be requested. :type url: str :param bearer_auth: Whether to use Bearer Authentication or not, defaults to `True`. :type bearer_auth: bool :param \*\*req_kwargs: Keyworded args to be passed down to Requests. :type \*\*req_kwargs: dict ''' req_kwargs.setdefault('params', {}) url = self._set_url(url) if is_basestring(req_kwargs['params']): req_kwargs['params'] = dict(parse_qsl(req_kwargs['params'])) if bearer_auth and self.access_token is not None: req_kwargs['auth'] = OAuth2Auth(self.access_token) else: req_kwargs['params'].update( {self.access_token_key: self.access_token}) req_kwargs.setdefault('timeout', OAUTH2_DEFAULT_TIMEOUT) return super(OAuth2Session, self).request(method, url, **req_kwargs)
def get_query_args(url): """ given a url like: http://nursingdegreesguide.elearners.com/cu.htm?°ID=10268&foo=bar returns a dictionary: {'degID': 10268, 'foo': 'bar'} """ return dict(parse_qsl(url))
def get_access_token(self, code): """user code to access token Get an access token from the supplied code https://svn.tools.ietf.org/html/draft-hammer-oauth2-00#section-3.5.2.2 """ if code is None: raise ValueError("Code must be set.") endpoint='access_token' params = {} if 'state' in self.params: params['state'] = self.params['state'] args = { 'grant_type': 'authorization_code', 'client_id': self._api_key, 'client_secret': self._api_secret, 'code': code, 'redirect_uri': self.callback, } args.update(params or {}) uri = urlparse.urljoin(self.BASE_URL, endpoint) body = urlencode(args) headers = { 'Content-Type': 'application/x-www-form-urlencoded', } req = Request(uri, body, headers) resp = urlopen(req) content = resp.read() if not resp.code == 200: print (resp, resp.code, content) raise Error(content) response_args = dict(parse_qsl(content)) error = response_args.get('error', None) if error is not None: msg = "%s:%s" % (error, response_args.get('error_description', '')) raise Error(msg) refresh_token = response_args.get('refresh_token', None) access_token = response_args.get('access_token', None) openid = response_args.get('openid', None) self.refresh_token = refresh_token self.access_token = access_token self.openid = openid if refresh_token is not None: response_args = self.refresh(refresh_token) return response_args
def get_signature_base_string(self, oauth_parameters): # RFC 5849 3.4.1 method, uri, http_params = self.request.get_base_string_parts() base_string = [method] # Base String URI (3.4.1.2) scheme, host, path, query, _ = urlparse.urlsplit(uri) scheme = scheme.lower() default_port = ':%d' % {'http': 80, 'https': 443}[scheme] host = host.lower() if host.endswith(default_port): host = host[:-len(default_port)] path = path or '/' base_string.append( util.oauth_encode( urlparse.urlunsplit((scheme, host, path, '', '')))) # Request Parameters (3.4.1.3) params = compat.parse_qsl(query) oauth_params = dict(oauth_parameters) oauth_params.pop('realm', None) params.extend(oauth_params.items()) if http_params: if hasattr(http_params, 'split'): http_params = compat.parse_qsl( http_params, keep_blank_values=True) elif hasattr(http_params, 'items'): http_params = http_params.items() params.extend(http_params) encoded_params = sorted( (util.oauth_encode(k), util.oauth_encode(v)) for k, v in params) base_string.append( util.oauth_encode('&'.join('%s=%s' % p for p in encoded_params))) return '&'.join(base_string)
def get_access_token(self, code): """user code to access token Get an access token from the supplied code https://svn.tools.ietf.org/html/draft-hammer-oauth2-00#section-3.5.2.2 """ if code is None: raise ValueError("Code must be set.") endpoint = 'access_token' params = {} if 'state' in self.params: params['state'] = self.params['state'] args = { 'grant_type': 'authorization_code', 'client_id': self._api_key, 'client_secret': self._api_secret, 'code': code, 'redirect_uri': self.callback, } args.update(params or {}) uri = urlparse.urljoin(self.BASE_URL, endpoint) body = urlencode(args) headers = { 'Content-Type': 'application/x-www-form-urlencoded', } req = Request(uri, body, headers) resp = urlopen(req) content = resp.read() if not resp.code == 200: print(resp, resp.code, content) raise Error(content) response_args = dict(parse_qsl(content)) error = response_args.get('error', None) if error is not None: msg = "%s:%s" % (error, response_args.get('error_description', '')) raise Error(msg) refresh_token = response_args.get('refresh_token', None) access_token = response_args.get('access_token', None) openid = response_args.get('openid', None) self.refresh_token = refresh_token self.access_token = access_token self.openid = openid if refresh_token is not None: response_args = self.refresh(refresh_token) return response_args
def build(cls, token, secret=None): if secret: return cls(token, secret) elif isinstance(token, cls): return token elif isinstance(token, (list, tuple)) and len(token) == 2: return cls(*token) else: if hasattr(token, 'split'): token = dict(compat.parse_qsl(token)) return cls(token['oauth_token'], token['oauth_token_secret'])
def parse_utf8_qsl(s): d = dict(parse_qsl(s)) for k, v in d.items(): # pragma: no cover if not isinstance(k, bytes) and not isinstance(v, bytes): # skip this iteration if we have no keys or values to update continue d.pop(k) if isinstance(k, bytes): k = k.decode('utf-8') if isinstance(v, bytes): v = v.decode('utf-8') d[k] = v return d
def request(self, method, url, user_id=None, hash_meth='sha1', **req_kwargs): ''' A loose wrapper around Requests' :class:`~requests.sessions.Session` which injects Ofly parameters. :param method: A string representation of the HTTP method to be used. :type method: str :param url: The resource to be requested. :type url: str :param hash_meth: The hash method to use for signing, defaults to "sha1". :type hash_meth: str :param user_id: The oflyUserid, defaults to `None`. :type user_id: str :param \*\*req_kwargs: Keyworded args to be passed down to Requests. :type \*\*req_kwargs: dict ''' req_kwargs.setdefault('params', {}) req_kwargs.setdefault('timeout', OFLY_DEFAULT_TIMEOUT) url = self._set_url(url) user_id = user_id or self.user_id assert user_id is not None, \ 'An oflyUserid must be provided as `user_id`.' if is_basestring(req_kwargs['params']): req_kwargs['params'] = dict(parse_qsl(req_kwargs['params'])) req_kwargs['params'].update({'oflyUserid': user_id}) params = OflySession.sign(url, self.app_id, self.app_secret, hash_meth=hash_meth, **req_kwargs['params']) # NOTE: Requests can't seem to handle unicode objects, instead we can # encode a string here. req_kwargs['params'] = params if not isinstance(req_kwargs['params'], bytes): req_kwargs['params'] = req_kwargs['params'].encode('utf-8') return super(OflySession, self).request(method, url, **req_kwargs)
def request(self, method, url, header_auth=False, realm='', **req_kwargs): ''' A loose wrapper around Requests' :class:`~requests.sessions.Session` which injects OAuth 1.0/a parameters. :param method: A string representation of the HTTP method to be used. :type method: str :param url: The resource to be requested. :type url: str :param header_auth: Authentication via header, defaults to `False.` :type header_auth: bool :param realm: The auth header realm, defaults to ``""``. :type realm: str :param \*\*req_kwargs: Keyworded args to be passed down to Requests. :type \*\*req_kwargs: dict ''' req_kwargs.setdefault('headers', {}) req_kwargs['headers'] = CaseInsensitiveDict(req_kwargs['headers']) url = self._set_url(url) entity_method = method.upper() in ENTITY_METHODS if entity_method and not req_kwargs.get('files', None): req_kwargs['headers'].setdefault('Content-Type', FORM_URLENCODED) form_urlencoded = \ req_kwargs['headers'].get('Content-Type') == FORM_URLENCODED # inline string conversion if is_basestring(req_kwargs.get('params')): req_kwargs['params'] = dict(parse_qsl(req_kwargs['params'])) if is_basestring(req_kwargs.get('data')) and form_urlencoded: req_kwargs['data'] = dict(parse_qsl(req_kwargs['data'])) req_kwargs.setdefault('timeout', OAUTH1_DEFAULT_TIMEOUT) oauth_params = self._get_oauth_params(req_kwargs) # ensure we always create new instances of dictionary elements for key, value in req_kwargs.items(): if isinstance(value, dict): req_kwargs[key] = deepcopy(value) # sign the request oauth_params['oauth_signature'] = \ self.signature.sign(self.consumer_secret, self.access_token_secret, method, url, oauth_params, req_kwargs) if header_auth and 'oauth_signature' not in \ req_kwargs['headers'].get('Authorization', ''): req_kwargs['auth'] = OAuth1Auth(oauth_params, realm) elif entity_method and 'oauth_signature' not in \ (req_kwargs.get('data') or {}): req_kwargs['data'] = req_kwargs.get('data') or {} # If we have a urlencoded entity-body we should pass the OAuth # parameters on this body. However, if we do not, then we need to # pass these over the request URI, i.e. on params. # # See: # # http://tools.ietf.org/html/rfc5849#section-3.5.2 # # and: # # http://tools.ietf.org/html/rfc5849#section-3.5.3 if form_urlencoded: req_kwargs['data'].update(oauth_params) else: req_kwargs.setdefault('params', {}) req_kwargs['params'].update(oauth_params) elif 'oauth_signature' not in url: req_kwargs.setdefault('params', {}) req_kwargs['params'].update(oauth_params) return super(OAuth1Session, self).request(method, url, **req_kwargs)