forked from rdegges/python-basicauth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasicauth.py
52 lines (40 loc) · 1.56 KB
/
basicauth.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""An incredibly simple HTTP basic auth implementation."""
from base64 import b64decode, b64encode
from six.moves.urllib.parse import quote, unquote
class DecodeError(Exception):
pass
def encode(username, password):
"""Returns an HTTP basic authentication encrypted string given a valid
username and password.
"""
username_password = '%s:%s' % (quote(username), quote(password))
return 'Basic ' + b64encode(username_password.encode()).decode()
def decode(encoded_str):
"""Decode an encrypted HTTP basic authentication string. Returns a tuple of
the form (username, password), and raises a DecodeError exception if
nothing could be decoded.
"""
split = encoded_str.strip().split(' ')
# If split is only one element, try to decode the username and password
# directly.
if len(split) == 1:
try:
username, password = b64decode(split[0]).decode().split(':', 1)
except:
raise DecodeError
# If there are only two elements, check the first and ensure it says
# 'basic' so that we know we're about to decode the right thing. If not,
# bail out.
elif len(split) == 2:
if split[0].strip().lower() == 'basic':
try:
username, password = b64decode(split[1]).decode().split(':', 1)
except:
raise DecodeError
else:
raise DecodeError
# If there are more than 2 elements, something crazy must be happening.
# Bail.
else:
raise DecodeError
return unquote(username), unquote(password)