Skip to content

Commit 363ab1b

Browse files
committed
Stop using bytes internally. Instead, expect and use unicode/string type.
1 parent 1468742 commit 363ab1b

File tree

1 file changed

+26
-39
lines changed

1 file changed

+26
-39
lines changed

mwoauth/functions.py

Lines changed: 26 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
import jwt
4040
import requests
4141
from requests_oauthlib import OAuth1
42-
from six import PY3, b, text_type
42+
from six import PY3, text_type
4343

4444
from six.moves.urllib.parse import parse_qs, urlencode, urlparse
4545

@@ -55,7 +55,7 @@ def force_unicode(val, encoding="unicode-escape"):
5555
if PY3:
5656
return val.decode(encoding, errors="replace")
5757
else:
58-
return unicode(val, encoding, errors="replace")
58+
return unicode(val, encoding, errors="replace") # noqa
5959

6060

6161
def initiate(mw_uri, consumer_token, callback='oob',
@@ -90,7 +90,7 @@ def initiate(mw_uri, consumer_token, callback='oob',
9090
auth=auth,
9191
headers={'User-Agent': user_agent})
9292

93-
request_token = process_request_token(r.content)
93+
request_token = process_request_token(r.text)
9494

9595
params = {'title': "Special:OAuth/authenticate",
9696
'oauth_token': request_token.key,
@@ -100,17 +100,16 @@ def initiate(mw_uri, consumer_token, callback='oob',
100100

101101

102102
def process_request_token(content):
103-
text_content = force_unicode(content, "utf8")
104-
if text_content.startswith(force_unicode("Error: ")):
105-
raise OAuthException(text_content[len("Error: "):])
103+
if content.startswith("Error: "):
104+
raise OAuthException(content[len("Error: "):])
106105

107-
credentials = parse_qs(text_content)
106+
credentials = parse_qs(content)
108107

109108
if credentials is None or credentials == {}:
110109
raise OAuthException(
111110
"Expected x-www-form-urlencoded response from " +
112111
"MediaWiki, but got something else: " +
113-
"{0}".format(repr(text_content)))
112+
"{0}".format(repr(content)))
114113
elif 'oauth_token' not in credentials or \
115114
'oauth_token_secret' not in credentials:
116115
raise OAuthException(
@@ -146,31 +145,28 @@ def complete(mw_uri, consumer_token, request_token, response_qs,
146145
can be stored and used by you.
147146
"""
148147

149-
callback_data = parse_qs(_ensure_bytes(response_qs))
148+
callback_data = parse_qs(force_unicode(response_qs))
150149

151150
if callback_data is None or callback_data == {}:
152151
raise OAuthException(
153152
"Expected URL query string, but got " +
154153
"something else instead: {0}".format(str(response_qs)))
155154

156-
elif b('oauth_token') not in callback_data or \
157-
b('oauth_verifier') not in callback_data:
158-
155+
elif 'oauth_token' not in callback_data or \
156+
'oauth_verifier' not in callback_data:
159157
raise OAuthException(
160158
"Query string lacks token information: "
161159
"{0}".format(repr(callback_data)))
162160

163-
else:
164-
# Check if the query string references the right temp resource owner
165-
# key
166-
request_token_key = callback_data.get(b("oauth_token"))[0]
167-
# Get the verifier token
168-
verifier = callback_data.get(b("oauth_verifier"))[0]
161+
# Process the callback_data
162+
request_token_key = callback_data.get('oauth_token')[0]
163+
verifier = callback_data.get('oauth_verifier')[0]
169164

170-
if not request_token.key == force_unicode(request_token_key):
165+
# Check if the query string references the right temp resource owner key
166+
if not request_token.key == request_token_key:
171167
raise OAuthException(
172-
"Unexpect request token key " +
173-
"{0}, expected {1}.".format(request_token_key, request_token.key))
168+
"Unexpect request token key {0!r}, expected {1!r}.".format(
169+
request_token_key, request_token.key))
174170

175171
# Construct a new auth with the verifier
176172
auth = OAuth1(consumer_token.key,
@@ -186,30 +182,21 @@ def complete(mw_uri, consumer_token, request_token, response_qs,
186182
headers={'User-Agent': user_agent})
187183

188184
# Parse response and construct an authorized resource owner
189-
credentials = parse_qs(r.content)
185+
credentials = parse_qs(r.text)
190186

191187
if credentials is None:
192188
raise OAuthException(
193189
"Expected x-www-form-urlencoded response, " +
194-
"but got some else instead: {0}".format(r.content))
190+
"but got some else instead: {0}".format(r.text))
195191

196192
access_token = AccessToken(
197-
credentials.get(b('oauth_token'))[0],
198-
credentials.get(b('oauth_token_secret'))[0]
193+
credentials.get('oauth_token')[0],
194+
credentials.get('oauth_token_secret')[0]
199195
)
200196

201197
return access_token
202198

203199

204-
def _ensure_bytes(val, encoding="ascii"):
205-
if isinstance(val, bytes):
206-
return val
207-
elif str == bytes:
208-
return val.encode(encoding)
209-
else:
210-
return bytes(val, encoding)
211-
212-
213200
def identify(mw_uri, consumer_token, access_token, leeway=10.0,
214201
user_agent=defaults.USER_AGENT):
215202
"""
@@ -252,17 +239,17 @@ def identify(mw_uri, consumer_token, access_token, leeway=10.0,
252239
algorithms=["HS256"],
253240
leeway=leeway)
254241
except jwt.InvalidTokenError as e:
255-
if r.content.startswith(b'{'):
242+
if r.text.startswith('{'):
256243
try:
257-
resp = json.loads(r.content)
244+
resp = json.loads(r.text)
258245
if 'error' in resp:
259246
raise OAuthException(
260247
"A MediaWiki API error occurred: {0}"
261248
.format(resp['message']))
262249
else:
263250
raise OAuthException(
264251
"Unknown JSON response: {0!r}"
265-
.format(r.content[:100]))
252+
.format(r.text[:100]))
266253
except ValueError as e:
267254
raise OAuthException(
268255
"An error occurred while trying to read json " +
@@ -271,7 +258,7 @@ def identify(mw_uri, consumer_token, access_token, leeway=10.0,
271258
raise OAuthException(
272259
"Could not read response from 'Special:OAuth/identify'. " +
273260
"Maybe your MediaWiki is not configured correctly? " +
274-
"Expected JSON but instead got: {0!r}".format(r.content[:100]))
261+
"Expected JSON but instead got: {0!r}".format(r.text[:100]))
275262

276263
# Verify the issuer is who we expect (server sends $wgCanonicalServer)
277264
issuer = urlparse(identity['iss']).netloc
@@ -289,7 +276,7 @@ def identify(mw_uri, consumer_token, access_token, leeway=10.0,
289276
"Identity issued {0} ".format(issued_at - now) +
290277
"seconds in the future!")
291278

292-
# Verify that the nonce matches our request one,
279+
# Verify that the nonce matches our request nonce,
293280
# to avoid a replay attack
294281
authorization_header = force_unicode(r.request.headers['Authorization'])
295282
request_nonce = re.search(r'oauth_nonce="(.*?)"',

0 commit comments

Comments
 (0)