2016-10-14 16:49:59 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
|
|
|
|
2017-01-20 05:59:53 +00:00
|
|
|
import uuid
|
2016-12-25 05:15:28 +00:00
|
|
|
import time
|
2016-10-31 10:58:23 +00:00
|
|
|
|
|
|
|
from django.core.cache import cache
|
|
|
|
from django.utils.translation import ugettext as _
|
2020-11-19 07:50:31 +00:00
|
|
|
from six import text_type
|
2019-02-28 09:58:53 +00:00
|
|
|
from django.contrib.auth import get_user_model
|
2022-02-25 11:23:59 +00:00
|
|
|
|
2016-12-21 17:07:05 +00:00
|
|
|
from rest_framework import HTTP_HEADER_ENCODING
|
2018-11-23 02:25:35 +00:00
|
|
|
from rest_framework import authentication, exceptions
|
2019-08-21 12:27:21 +00:00
|
|
|
from common.auth import signature
|
2016-10-14 16:49:59 +00:00
|
|
|
|
2016-12-25 05:15:28 +00:00
|
|
|
from common.utils import get_object_or_none, make_signature, http_to_unixtime
|
2019-02-28 09:58:53 +00:00
|
|
|
from ..models import AccessKey, PrivateToken
|
2022-02-25 11:23:59 +00:00
|
|
|
from .base import JMSBaseAuthBackend, JMSModelBackend
|
2016-10-14 16:49:59 +00:00
|
|
|
|
|
|
|
|
2021-07-06 11:03:58 +00:00
|
|
|
UserModel = get_user_model()
|
|
|
|
|
|
|
|
|
2016-12-21 17:07:05 +00:00
|
|
|
def get_request_date_header(request):
|
|
|
|
date = request.META.get('HTTP_DATE', b'')
|
|
|
|
if isinstance(date, text_type):
|
|
|
|
# Work around django test client oddness
|
|
|
|
date = date.encode(HTTP_HEADER_ENCODING)
|
|
|
|
return date
|
|
|
|
|
|
|
|
|
|
|
|
class AccessKeyAuthentication(authentication.BaseAuthentication):
|
2017-01-17 08:34:47 +00:00
|
|
|
"""App使用Access key进行签名认证, 目前签名算法比较简单,
|
|
|
|
app注册或者手动建立后,会生成 access_key_id 和 access_key_secret,
|
|
|
|
然后使用 如下算法生成签名:
|
|
|
|
Signature = md5(access_key_secret + '\n' + Date)
|
|
|
|
example: Signature = md5('d32d2b8b-9a10-4b8d-85bb-1a66976f6fdc' + '\n' +
|
|
|
|
'Thu, 12 Jan 2017 08:19:41 GMT')
|
|
|
|
请求时设置请求header
|
|
|
|
header['Authorization'] = 'Sign access_key_id:Signature' 如:
|
|
|
|
header['Authorization'] =
|
|
|
|
'Sign d32d2b8b-9a10-4b8d-85bb-1a66976f6fdc:OKOlmdxgYPZ9+SddnUUDbQ=='
|
|
|
|
|
|
|
|
验证时根据相同算法进行验证, 取到access_key_id对应的access_key_id, 从request
|
|
|
|
headers取到Date, 然后进行md5, 判断得到的结果是否相同, 如果是认证通过, 否则 认证
|
|
|
|
失败
|
|
|
|
"""
|
2016-10-14 16:49:59 +00:00
|
|
|
keyword = 'Sign'
|
|
|
|
|
|
|
|
def authenticate(self, request):
|
|
|
|
auth = authentication.get_authorization_header(request).split()
|
|
|
|
if not auth or auth[0].lower() != self.keyword.lower().encode():
|
|
|
|
return None
|
|
|
|
|
|
|
|
if len(auth) == 1:
|
2016-12-21 17:07:05 +00:00
|
|
|
msg = _('Invalid signature header. No credentials provided.')
|
2016-10-14 16:49:59 +00:00
|
|
|
raise exceptions.AuthenticationFailed(msg)
|
|
|
|
elif len(auth) > 2:
|
2017-01-17 08:34:47 +00:00
|
|
|
msg = _('Invalid signature header. Signature '
|
|
|
|
'string should not contain spaces.')
|
2016-10-14 16:49:59 +00:00
|
|
|
raise exceptions.AuthenticationFailed(msg)
|
|
|
|
|
|
|
|
try:
|
2016-12-21 17:07:05 +00:00
|
|
|
sign = auth[1].decode().split(':')
|
|
|
|
if len(sign) != 2:
|
2017-01-17 08:34:47 +00:00
|
|
|
msg = _('Invalid signature header. '
|
|
|
|
'Format like AccessKeyId:Signature')
|
2016-12-21 17:07:05 +00:00
|
|
|
raise exceptions.AuthenticationFailed(msg)
|
2016-10-14 16:49:59 +00:00
|
|
|
except UnicodeError:
|
2017-01-17 08:34:47 +00:00
|
|
|
msg = _('Invalid signature header. '
|
|
|
|
'Signature string should not contain invalid characters.')
|
2016-10-14 16:49:59 +00:00
|
|
|
raise exceptions.AuthenticationFailed(msg)
|
2016-12-21 17:07:05 +00:00
|
|
|
|
|
|
|
access_key_id = sign[0]
|
2017-01-20 05:59:53 +00:00
|
|
|
try:
|
|
|
|
uuid.UUID(access_key_id)
|
|
|
|
except ValueError:
|
|
|
|
raise exceptions.AuthenticationFailed('Access key id invalid')
|
2016-12-25 05:15:28 +00:00
|
|
|
request_signature = sign[1]
|
2016-10-14 16:49:59 +00:00
|
|
|
|
2017-01-17 08:34:47 +00:00
|
|
|
return self.authenticate_credentials(
|
2017-10-31 03:34:20 +00:00
|
|
|
request, access_key_id, request_signature
|
|
|
|
)
|
2016-12-21 17:07:05 +00:00
|
|
|
|
2016-12-29 11:17:00 +00:00
|
|
|
@staticmethod
|
|
|
|
def authenticate_credentials(request, access_key_id, request_signature):
|
2016-12-21 17:07:05 +00:00
|
|
|
access_key = get_object_or_none(AccessKey, id=access_key_id)
|
2016-12-25 05:15:28 +00:00
|
|
|
request_date = get_request_date_header(request)
|
2016-12-21 17:07:05 +00:00
|
|
|
if access_key is None or not access_key.user:
|
|
|
|
raise exceptions.AuthenticationFailed(_('Invalid signature.'))
|
2016-12-25 05:15:28 +00:00
|
|
|
access_key_secret = access_key.secret
|
|
|
|
|
|
|
|
try:
|
|
|
|
request_unix_time = http_to_unixtime(request_date)
|
|
|
|
except ValueError:
|
2017-01-17 08:34:47 +00:00
|
|
|
raise exceptions.AuthenticationFailed(
|
|
|
|
_('HTTP header: Date not provide '
|
|
|
|
'or not %a, %d %b %Y %H:%M:%S GMT'))
|
2016-12-25 05:15:28 +00:00
|
|
|
|
2017-01-17 08:34:47 +00:00
|
|
|
if int(time.time()) - request_unix_time > 15 * 60:
|
|
|
|
raise exceptions.AuthenticationFailed(
|
|
|
|
_('Expired, more than 15 minutes'))
|
2016-12-25 05:15:28 +00:00
|
|
|
|
|
|
|
signature = make_signature(access_key_secret, request_date)
|
|
|
|
if not signature == request_signature:
|
2017-01-17 08:34:47 +00:00
|
|
|
raise exceptions.AuthenticationFailed(_('Invalid signature.'))
|
2016-12-21 17:07:05 +00:00
|
|
|
|
|
|
|
if not access_key.user.is_active:
|
|
|
|
raise exceptions.AuthenticationFailed(_('User disabled.'))
|
|
|
|
return access_key.user, None
|
2016-10-15 08:04:54 +00:00
|
|
|
|
2020-04-22 07:13:04 +00:00
|
|
|
def authenticate_header(self, request):
|
|
|
|
return 'Sign access_key_id:Signature'
|
|
|
|
|
2016-10-15 08:04:54 +00:00
|
|
|
|
2016-10-31 10:58:23 +00:00
|
|
|
class AccessTokenAuthentication(authentication.BaseAuthentication):
|
2016-12-16 11:32:05 +00:00
|
|
|
keyword = 'Bearer'
|
2019-12-05 07:09:25 +00:00
|
|
|
# expiration = settings.TOKEN_EXPIRATION or 3600
|
2019-08-21 12:27:21 +00:00
|
|
|
model = get_user_model()
|
2016-10-31 10:58:23 +00:00
|
|
|
|
|
|
|
def authenticate(self, request):
|
|
|
|
auth = authentication.get_authorization_header(request).split()
|
|
|
|
if not auth or auth[0].lower() != self.keyword.lower().encode():
|
|
|
|
return None
|
|
|
|
|
|
|
|
if len(auth) == 1:
|
|
|
|
msg = _('Invalid token header. No credentials provided.')
|
|
|
|
raise exceptions.AuthenticationFailed(msg)
|
|
|
|
elif len(auth) > 2:
|
2017-01-17 08:34:47 +00:00
|
|
|
msg = _('Invalid token header. Sign string '
|
|
|
|
'should not contain spaces.')
|
2016-10-31 10:58:23 +00:00
|
|
|
raise exceptions.AuthenticationFailed(msg)
|
|
|
|
|
|
|
|
try:
|
|
|
|
token = auth[1].decode()
|
|
|
|
except UnicodeError:
|
2017-01-17 08:34:47 +00:00
|
|
|
msg = _('Invalid token header. Sign string '
|
|
|
|
'should not contain invalid characters.')
|
2016-10-31 10:58:23 +00:00
|
|
|
raise exceptions.AuthenticationFailed(msg)
|
2016-12-25 15:10:53 +00:00
|
|
|
return self.authenticate_credentials(token)
|
2016-10-31 10:58:23 +00:00
|
|
|
|
2019-02-28 09:58:53 +00:00
|
|
|
def authenticate_credentials(self, token):
|
2019-08-21 12:27:21 +00:00
|
|
|
model = get_user_model()
|
2016-10-31 10:58:23 +00:00
|
|
|
user_id = cache.get(token)
|
2019-08-21 12:27:21 +00:00
|
|
|
user = get_object_or_none(model, id=user_id)
|
2016-10-31 10:58:23 +00:00
|
|
|
|
|
|
|
if not user:
|
2016-12-25 15:10:53 +00:00
|
|
|
msg = _('Invalid token or cache refreshed.')
|
|
|
|
raise exceptions.AuthenticationFailed(msg)
|
2016-10-31 10:58:23 +00:00
|
|
|
return user, None
|
2016-12-25 15:10:53 +00:00
|
|
|
|
2020-04-22 07:13:04 +00:00
|
|
|
def authenticate_header(self, request):
|
|
|
|
return self.keyword
|
|
|
|
|
2016-12-25 15:10:53 +00:00
|
|
|
|
2022-02-25 11:23:59 +00:00
|
|
|
class PrivateTokenAuthentication(JMSBaseAuthBackend, authentication.TokenAuthentication):
|
2016-12-25 15:10:53 +00:00
|
|
|
model = PrivateToken
|
2016-12-28 16:29:59 +00:00
|
|
|
|
|
|
|
|
|
|
|
class SessionAuthentication(authentication.SessionAuthentication):
|
2019-06-19 08:45:14 +00:00
|
|
|
def authenticate(self, request):
|
|
|
|
"""
|
|
|
|
Returns a `User` if the request session currently has a logged in user.
|
|
|
|
Otherwise returns `None`.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Get the session-based user from the underlying HttpRequest object
|
|
|
|
user = getattr(request._request, 'user', None)
|
|
|
|
|
|
|
|
# Unauthenticated, CSRF validation not required
|
|
|
|
if not user or not user.is_active:
|
|
|
|
return None
|
|
|
|
|
|
|
|
try:
|
|
|
|
self.enforce_csrf(request)
|
|
|
|
except exceptions.AuthenticationFailed:
|
|
|
|
return None
|
|
|
|
|
|
|
|
# CSRF passed with authenticated user
|
|
|
|
return user, None
|
2019-08-21 12:27:21 +00:00
|
|
|
|
|
|
|
|
|
|
|
class SignatureAuthentication(signature.SignatureAuthentication):
|
|
|
|
# The HTTP header used to pass the consumer key ID.
|
|
|
|
|
|
|
|
# A method to fetch (User instance, user_secret_string) from the
|
|
|
|
# consumer key ID, or None in case it is not found. Algorithm
|
|
|
|
# will be what the client has sent, in the case that both RSA
|
|
|
|
# and HMAC are supported at your site (and also for expansion).
|
|
|
|
model = get_user_model()
|
|
|
|
|
|
|
|
def fetch_user_data(self, key_id, algorithm="hmac-sha256"):
|
|
|
|
# ...
|
|
|
|
# example implementation:
|
|
|
|
try:
|
|
|
|
key = AccessKey.objects.get(id=key_id)
|
|
|
|
if not key.is_active:
|
|
|
|
return None, None
|
|
|
|
user, secret = key.user, str(key.secret)
|
|
|
|
return user, secret
|
2022-06-15 02:31:20 +00:00
|
|
|
except (AccessKey.DoesNotExist, exceptions.ValidationError):
|
2019-08-21 12:27:21 +00:00
|
|
|
return None, None
|
2020-07-31 10:18:52 +00:00
|
|
|
|