Skip to content

Commit

Permalink
Modify the Auth Module
Browse files Browse the repository at this point in the history
  • Loading branch information
dt3310321 committed Sep 29, 2017
1 parent d4f8af1 commit 1d32ff7
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 13 deletions.
33 changes: 23 additions & 10 deletions qcloud_cos/cos_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,28 @@
import urllib
import hashlib
import logging
from urllib import quote
from urllib import quote_plus
from urlparse import urlparse
from requests.auth import AuthBase
logger = logging.getLogger(__name__)


def filter_headers(data):
"""只设置host content-type 还有x开头的头部"""
headers = {}
for i in data.keys():
if i == 'Content-Type' or i == 'Host' or i[0] == 'x' or i[0] == 'X':
headers[i] = data[i]
return headers


def cos_quote(value):
"""对头部进行encode"""
data = quote_plus(value, '-_.~') # 保留字为-_.~,并且要对/进行Encode
data = data.replace('+', '%20') # 对于空格,需要Encode成%20,而不是+
return data


class CosS3Auth(AuthBase):

def __init__(self, access_id, secret_key, expire=10000):
Expand All @@ -19,20 +35,19 @@ def __init__(self, access_id, secret_key, expire=10000):
self._expire = expire

def __call__(self, r):
method = r.method.lower()
method = r.method.lower() # 获取小写method
uri = urllib.unquote(r.url)
uri = uri.split('?')[0]
http_header = r.headers
r.headers = {}
rt = urlparse(uri)
rt = urlparse(uri) # 解析host以及params
logger.debug("url parse: " + str(rt))
if rt.query != "" and ("&" in rt.query or '=' in rt.query):
uri_params = dict(map(lambda s: s.lower().split('='), rt.query.split('&')))
elif rt.query != "":
uri_params = {rt.query: ""}
else:
uri_params = {}
headers = dict([(k.lower(), quote(v).lower()) for k, v in r.headers.items()])
headers = filter_headers(r.headers)
headers = dict([(k.lower(), cos_quote(v)) for k, v in headers.items()]) # headers中的key转换为小写,value进行encode
format_str = "{method}\n{host}\n{params}\n{headers}\n".format(
method=method.lower(),
host=rt.path,
Expand All @@ -42,7 +57,7 @@ def __call__(self, r):
logger.debug("format str: " + format_str)

start_sign_time = int(time.time())
sign_time = "{bg_time};{ed_time}".format(bg_time=start_sign_time-60, ed_time=start_sign_time + self._expire)
sign_time = "{bg_time};{ed_time}".format(bg_time=start_sign_time-60, ed_time=start_sign_time+self._expire)
sha1 = hashlib.sha1()
sha1.update(format_str)

Expand All @@ -54,18 +69,16 @@ def __call__(self, r):
logger.debug('sign: ' + str(sign))
sign_tpl = "q-sign-algorithm=sha1&q-ak={ak}&q-sign-time={sign_time}&q-key-time={key_time}&q-header-list={headers}&q-url-param-list={params}&q-signature={sign}"

http_header['Authorization'] = sign_tpl.format(
r.headers['Authorization'] = sign_tpl.format(
ak=self._access_id,
sign_time=sign_time,
key_time=sign_time,
params=';'.join(sorted(map(lambda k: k.lower(), uri_params.keys()))),
headers=';'.join(sorted(headers.keys())),
sign=sign
)
r.headers = http_header
logger.debug("sign_key" + str(sign_key))
logger.debug(r.headers['Authorization'])

logger.debug("request headers: " + str(r.headers))
return r

Expand Down
2 changes: 1 addition & 1 deletion qcloud_cos/cos_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
level=logging.INFO,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='cos_s3.log',
filename='cos_v5.log',
filemode='w')
logger = logging.getLogger(__name__)
reload(sys)
Expand Down
3 changes: 1 addition & 2 deletions qcloud_cos/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,7 @@ def Test():
response = client.list_buckets()

copy_source = {'Appid': '1252408340', 'Bucket': 'test02', 'Key': '/test.txt', 'Region': 'ap-guangzhou'}
print "Test Copy Object From Other Bucket "

print "Test Copy Object From Otopy Object
response = client.copy_object(
Bucket='test04',
Key='test.txt',
Expand Down

0 comments on commit 1d32ff7

Please sign in to comment.