Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def extract_client_data(self):
"""Helper method for extracting client ID and secret from the
authorization header.
"""
_, b64encoded_data = self.authorization.split(' ')
decoded_data = to_unicode(
base64.b64decode(b64encoded_data.encode('utf-8')), 'ascii')
self.client_id, self.client_secret = decoded_data.split(':')
Method is used by:
- Authorization Code Grant
- Resource Owner Password Credentials Grant (may be disabled)
- Client Credentials Grant
- Refresh Token Grant
.. _`HTTP Basic Authentication Scheme`: http://tools.ietf.org/html/rfc1945#section-11.1 # noqa
"""
auth = request.headers.get('Authorization', None)
log.debug('Authenticate client %r', auth)
if auth:
try:
_, s = auth.split(' ')
client_id, client_secret = decode_base64(s).split(':')
client_id = to_unicode(client_id, 'utf-8')
client_secret = to_unicode(client_secret, 'utf-8')
except Exception as e:
log.debug('Authenticate client failed with exception: %r', e)
return False
else:
client_id = request.client_id
client_secret = request.client_secret
client = self._clientgetter(client_id)
if not client:
return False
if client.client_secret != client_secret:
log.debug('Authenticate client failed, secret not match.')
return False
request.client = client
def decorated(*args, **kwargs):
auth = request.headers.get('Authorization', None)
if not auth:
raise NotConfidential()
try:
_, s = auth.split(' ')
client_id, client_secret = decode_base64(s).split(':')
client_id = to_unicode(client_id, 'utf-8')
client_secret = to_unicode(client_secret, 'utf-8')
except:
raise NotConfidential()
client = oauth._clientgetter(client_id)
if not client or client.client_secret != client_secret:
raise NotConfidential()
if not client.is_confidential:
raise NotConfidential()
return f(*args, **kwargs)
return decorated
def get_request_token(self, base_auth_url=None, callback_url=None, auto_set_token=True, **kwargs):
if callback_url:
self.session._client.client.callback_uri = to_unicode(callback_url, 'utf-8')
try:
token = self.session.fetch_request_token(self.request_token_url)
except requests.RequestException as e:
raise TwitterClientError(str(e))
except ValueError as e:
raise TwitterClientError('Response does not contain a token.')
if base_auth_url:
token['auth_url'] = self.session.authorization_url(base_auth_url, **kwargs)
if auto_set_token:
self.auto_set_token(token)
return JSONObject(token)
for attr in ('iss', 'aud', 'sub'):
if claim[attr] is None:
raise ValueError(
'Claim must include %s but none was given.' % attr)
if 'not_before' in kwargs:
claim['nbf'] = kwargs.pop('not_before')
if 'jwt_id' in kwargs:
claim['jti'] = kwargs.pop('jwt_id')
claim.update(extra_claims or {})
assertion = jwt.encode(claim, key, 'RS256')
assertion = to_unicode(assertion)
return prepare_token_request(self.grant_type,
body=body,
assertion=assertion,
scope=scope,
**kwargs)
# flow even though the entire request will be deemed invalid
# in the end.
secret = request.app._client.auth.secret
now = datetime.datetime.utcnow()
data = {
'iss': request.app.href,
'sub': client_id,
'iat': now,
'exp': now + datetime.timedelta(seconds=request.expires_in),
}
if hasattr(request, 'scope'):
data['scope'] = request.scope
token = jwt.encode(data, secret, 'HS256')
token = to_unicode(token, "UTF-8")
return token
pageid = int(data['pageid'])
type = data['type']
lat = float(data['lat'])
lng = float(data['lng'])
app.logger.info('Received request %s', str(data))
r1 = mwoauth_request({
'action': 'query',
'pageids': pageid,
'prop': 'revisions',
'rvprop': 'content',
'meta': 'tokens'
})
try:
wikitext = r1['query']['pages'][str(pageid)]['revisions'][0]['*']
wikitext = to_unicode(wikitext)
except KeyError:
abort(404)
try:
token = r1['query']['tokens']['csrftoken']
except KeyError:
abort(401)
app.logger.info('Obtained token=%s for pageid=%d', token, pageid)
from location_to_wikitext import add_location_to_wikitext
new_wikitext = add_location_to_wikitext(type, lat, lng, wikitext)
r2 = mwoauth_request({
'action': 'edit',
'pageid': str(pageid),
'summary': '{{%s}}' % type,
'text': new_wikitext,
if sp_token is not None:
body['sp_token'] = sp_token
if organization_name_key is not None:
body['onk'] = organization_name_key
if use_subdomain:
body['usd'] = True
if path:
body['path'] = path
if state:
body['state'] = state
jwt_signature = to_unicode(jwt.encode(body, api_key_secret, 'HS256'), 'UTF-8')
url_params = {'jwtRequest': jwt_signature}
return endpoint + '?' + urlencode(url_params)
def decode_base64(text, encoding='utf-8'):
"""Decode base64 string."""
text = to_bytes(text, encoding)
return to_unicode(base64.b64decode(text), encoding)
def get_access_token(self, oauth_verifier, auto_set_token=True):
required = (self.access_token, self.access_token_secret)
if not all(required):
raise TwitterClientError('''%s must be initialized with access_token and access_token_secret
to fetch authorized access token.''' % self.__class__.__name__)
self.session._client.client.verifier = to_unicode(oauth_verifier, 'utf-8')
try:
token = self.session.fetch_access_token(self.access_token_url)
except requests.RequestException as e:
raise TwitterClientError(str(e))
except ValueError:
raise TwitterClientError('Reponse does not contain a token.')
if auto_set_token:
self.auto_set_token(token)
return JSONObject(token)