Commit e9f6547d authored by ibuler's avatar ibuler

修改 auth 和sdk

parent 83c0ed36
...@@ -24,9 +24,9 @@ def make_signature(access_key_secret, date=None): ...@@ -24,9 +24,9 @@ def make_signature(access_key_secret, date=None):
class AccessKeyAuth(object): class AccessKeyAuth(object):
def __init__(self, access_key_id, access_key_secret): def __init__(self, access_key):
self.id = access_key_id self.id = access_key.id
self.secret = access_key_secret self.secret = access_key.secret
def sign_request(self, req): def sign_request(self, req):
req.headers['Date'] = utils.http_date() req.headers['Date'] = utils.http_date()
...@@ -34,48 +34,48 @@ class AccessKeyAuth(object): ...@@ -34,48 +34,48 @@ class AccessKeyAuth(object):
req.headers['Authorization'] = "Sign {0}:{1}".format(self.id, signature) req.headers['Authorization'] = "Sign {0}:{1}".format(self.id, signature)
return req return req
#
class AccessTokenAuth(object): # class AccessTokenAuth(object):
def __init__(self, token): # def __init__(self, token):
self.token = token # self.token = token
#
def sign_request(self, req): # def sign_request(self, req):
req.headers['Authorization'] = 'Bearer {0}'.format(self.token) # req.headers['Authorization'] = 'Bearer {0}'.format(self.token)
return req # return req
#
#
class SessionAuth(object): # class SessionAuth(object):
def __init__(self, session_id, csrf_token): # def __init__(self, session_id, csrf_token):
self.session_id = session_id # self.session_id = session_id
self.csrf_token = csrf_token # self.csrf_token = csrf_token
#
def sign_request(self, req): # def sign_request(self, req):
cookie = [v for v in req.headers.get('Cookie', '').split(';') # cookie = [v for v in req.headers.get('Cookie', '').split(';')
if v.strip()] # if v.strip()]
cookie.extend(['sessionid='+self.session_id, # cookie.extend(['sessionid='+self.session_id,
'csrftoken='+self.csrf_token]) # 'csrftoken='+self.csrf_token])
req.headers['Cookie'] = ';'.join(cookie) # req.headers['Cookie'] = ';'.join(cookie)
req.headers['X-CSRFTOKEN'] = self.csrf_token # req.headers['X-CSRFTOKEN'] = self.csrf_token
return req # return req
class Auth(object): # class Auth(object):
def __init__(self, token=None, access_key_id=None, # def __init__(self, token=None, access_key_id=None,
access_key_secret=None, # access_key_secret=None,
session_id=None, csrf_token=None): # session_id=None, csrf_token=None):
#
if token is not None: # if token is not None:
self.instance = AccessTokenAuth(token) # self.instance = AccessTokenAuth(token)
elif access_key_id and access_key_secret: # elif access_key_id and access_key_secret:
self.instance = AccessKeyAuth(access_key_id, access_key_secret) # self.instance = AccessKeyAuth(access_key_id, access_key_secret)
elif session_id and csrf_token: # elif session_id and csrf_token:
self.instance = SessionAuth(session_id, csrf_token) # self.instance = SessionAuth(session_id, csrf_token)
else: # else:
raise SyntaxError('Need token or access_key_id, access_key_secret ' # raise SyntaxError('Need token or access_key_id, access_key_secret '
'or session_id, csrf_token') # 'or session_id, csrf_token')
#
def sign_request(self, req): # def sign_request(self, req):
return self.instance.sign_request(req) # return self.instance.sign_request(req)
class AccessKey(object): class AccessKey(object):
...@@ -84,9 +84,9 @@ class AccessKey(object): ...@@ -84,9 +84,9 @@ class AccessKey(object):
self.secret = secret self.secret = secret
@staticmethod @staticmethod
def clean(value, delimiter=':', silent=False): def clean(value, sep=':', silent=False):
try: try:
id, secret = value.split(delimiter) id, secret = value.split(sep)
except (AttributeError, ValueError) as e: except (AttributeError, ValueError) as e:
if not silent: if not silent:
raise LoadAccessKeyError(e) raise LoadAccessKeyError(e)
...@@ -94,6 +94,11 @@ class AccessKey(object): ...@@ -94,6 +94,11 @@ class AccessKey(object):
else: else:
return id, secret return id, secret
@classmethod
def load_from_val(cls, val, **kwargs):
id, secret = cls.clean(val, **kwargs)
return cls(id, secret)
@classmethod @classmethod
def load_from_env(cls, env, **kwargs): def load_from_env(cls, env, **kwargs):
value = os.environ.get(env) value = os.environ.get(env)
...@@ -135,88 +140,35 @@ class AccessKey(object): ...@@ -135,88 +140,35 @@ class AccessKey(object):
__repr__ = __str__ __repr__ = __str__
class ServiceAccessKey(AccessKey): class AppAccessKey(AccessKey):
"""使用Access key来认证""" """使用Access key来认证"""
# 默认从配置文件中读取的设置 def __init__(self, app, id=None, secret=None):
# 配置文件中ACCESS_KEY值的名称
conf_attr_var = 'ACCESS_KEY'
# 配置文件中配置环境变量的名称
conf_env_var = 'ACCESS_KEY_ENV'
# 配置文件中定义Access key store的位置
conf_store_var = 'ACCESS_KEY_STORE'
# 如果用户配置中没有设置, 方法中也没填入, 使用下面默认
default_key_env = 'ACCESS_KEY_ENV'
default_key_store = os.path.join(os.environ.get('HOME', ''), '.access_key')
def __init__(self, id=None, secret=None, config=None):
super().__init__(id=id, secret=secret) super().__init__(id=id, secret=secret)
self.config = config or {} self.app = app
self._key_store = None self._key_store = app.config['ACCESS_KEY_STORE']
self._key_env = None self._key_env = app.config['ACCESS_KEY_ENV']
self._key_val = app.config['ACCESS_KEY']
# 获取key store位置
@property
def key_store(self):
if self._key_store:
return self._key_store
elif self.conf_store_var in self.config:
return self.config[self.conf_store_var]
else:
return self.default_key_store
@key_store.setter
def key_store(self, value):
self._key_store = value
# 获取access key的环境变量名
@property
def key_env(self):
if self._key_env:
return self._key_env
elif self.conf_env_var in self.config:
return self.config[self.conf_env_var]
else:
return self.default_key_env
@key_env.setter def load_from_conf_env(self, sep=':', silent=False):
def key_env(self, value): return super().load_from_env(self._key_env, sep=sep, silent=silent)
self._key_env = value
def load_from_conf_env(self, env=None, delimiter=':'): def load_from_conf(self, sep=':', silent=False):
if env is None: return super().load_from_val(self._key_val, sep=sep, silent=silent)
env = self.key_env
return super(ServiceAccessKey, self).\
load_from_env(env, delimiter=delimiter)
def load_from_conf_setting(self, attr=None, delimiter=':', silent=False): def load_from_key_store(self, sep=':', silent=False):
value = '' return super().load_from_f(self._key_store, sep=sep, silent=silent)
if attr is None:
attr = self.conf_attr_var def load(self, **kwargs):
if attr in self.config:
value = self.config.get(attr)
return self.clean(value, delimiter, silent)
def load_from_key_store(self, f=None, delimiter=':', silent=False):
if f is None:
f = self.key_store
return super(ServiceAccessKey, self).load_from_f(f, delimiter, silent)
def load_from_conf_all(self, **kwargs):
"""Should return access_key_id, access_key_secret""" """Should return access_key_id, access_key_secret"""
for method in [self.load_from_conf_setting, for method in [self.load_from_env,
self.load_from_key_store, self.load_from_conf,
self.load_from_conf_env]: self.load_from_key_store]:
try: try:
return method(**kwargs) return method(**kwargs)
except LoadAccessKeyError: except LoadAccessKeyError:
continue continue
return None
if not (bool(self.id) and bool(self.secret)): def save_to_key_store(self):
logging.error('Load access key failed') return super().save_to_f(self._key_store)
\ No newline at end of file
def save_to_key_store(self, key_store=None, silent=True):
if key_store is None:
key_store = self.key_store
return super(ServiceAccessKey, self).save_to_f(key_store, silent)
\ No newline at end of file
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment