2016-10-14 16:49:59 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
|
|
|
|
2019-02-28 09:58:53 +00:00
|
|
|
from django.contrib.auth import get_user_model
|
2023-07-24 03:52:25 +00:00
|
|
|
from django.core.cache import cache
|
2023-10-10 09:52:52 +00:00
|
|
|
from django.utils import timezone
|
2023-07-24 03:52:25 +00:00
|
|
|
from django.utils.translation import gettext as _
|
2018-11-23 02:25:35 +00:00
|
|
|
from rest_framework import authentication, exceptions
|
2016-10-14 16:49:59 +00:00
|
|
|
|
2023-07-24 03:52:25 +00:00
|
|
|
from common.auth import signature
|
2023-11-17 09:07:24 +00:00
|
|
|
from common.decorators import merge_delay_run
|
2023-10-31 06:15:07 +00:00
|
|
|
from common.utils import get_object_or_none, get_request_ip_or_data, contains_ip
|
2024-01-17 11:31:01 +00:00
|
|
|
from users.models import User
|
2019-02-28 09:58:53 +00:00
|
|
|
from ..models import AccessKey, PrivateToken
|
2016-10-14 16:49:59 +00:00
|
|
|
|
2016-12-21 17:07:05 +00:00
|
|
|
|
2023-10-10 09:52:52 +00:00
|
|
|
def date_more_than(d, seconds):
|
|
|
|
return d is None or (timezone.now() - d).seconds > seconds
|
2017-01-17 08:34:47 +00:00
|
|
|
|
2016-10-14 16:49:59 +00:00
|
|
|
|
2023-11-17 09:07:24 +00:00
|
|
|
@merge_delay_run(ttl=60)
|
|
|
|
def update_token_last_used(tokens=()):
|
2024-01-17 11:31:01 +00:00
|
|
|
access_keys_ids = [token.id for token in tokens if isinstance(token, AccessKey)]
|
|
|
|
private_token_keys = [token.key for token in tokens if isinstance(token, PrivateToken)]
|
|
|
|
if len(access_keys_ids) > 0:
|
|
|
|
AccessKey.objects.filter(id__in=access_keys_ids).update(date_last_used=timezone.now())
|
|
|
|
if len(private_token_keys) > 0:
|
|
|
|
PrivateToken.objects.filter(key__in=private_token_keys).update(date_last_used=timezone.now())
|
2023-11-16 10:00:57 +00:00
|
|
|
|
|
|
|
|
2023-11-17 09:07:24 +00:00
|
|
|
@merge_delay_run(ttl=60)
|
|
|
|
def update_user_last_used(users=()):
|
2024-01-17 11:31:01 +00:00
|
|
|
User.objects.filter(id__in=users).update(date_api_key_last_used=timezone.now())
|
2016-10-14 16:49:59 +00:00
|
|
|
|
2023-11-16 10:00:57 +00:00
|
|
|
|
|
|
|
def after_authenticate_update_date(user, token=None):
|
2024-01-23 08:45:59 +00:00
|
|
|
update_user_last_used.delay(users=(user.id,))
|
2023-11-16 10:00:57 +00:00
|
|
|
if token:
|
2024-01-23 08:45:59 +00:00
|
|
|
update_token_last_used.delay(tokens=(token,))
|
2020-04-22 07:13:04 +00:00
|
|
|
|
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-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:
|
2023-10-10 09:52:52 +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:
|
2023-10-10 09:52:52 +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)
|
2023-10-10 09:52:52 +00:00
|
|
|
user, header = self.authenticate_credentials(token)
|
|
|
|
after_authenticate_update_date(user)
|
|
|
|
return user, header
|
2016-10-31 10:58:23 +00:00
|
|
|
|
2023-10-10 09:52:52 +00:00
|
|
|
@staticmethod
|
|
|
|
def authenticate_credentials(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
|
|
|
|
2023-10-10 09:52:52 +00:00
|
|
|
class PrivateTokenAuthentication(authentication.TokenAuthentication):
|
2016-12-25 15:10:53 +00:00
|
|
|
model = PrivateToken
|
2016-12-28 16:29:59 +00:00
|
|
|
|
2023-10-10 09:52:52 +00:00
|
|
|
def authenticate(self, request):
|
|
|
|
user_token = super().authenticate(request)
|
|
|
|
if not user_token:
|
|
|
|
return
|
|
|
|
user, token = user_token
|
|
|
|
after_authenticate_update_date(user, token)
|
|
|
|
return user, token
|
|
|
|
|
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.
|
2023-10-10 09:52:52 +00:00
|
|
|
Otherwise, returns `None`.
|
2019-06-19 08:45:14 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
# 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)
|
2023-10-10 09:52:52 +00:00
|
|
|
after_authenticate_update_date(user, key)
|
2019-08-21 12:27:21 +00:00
|
|
|
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
|
2023-10-31 06:15:07 +00:00
|
|
|
|
|
|
|
def is_ip_allow(self, key_id, request):
|
|
|
|
try:
|
|
|
|
ak = AccessKey.objects.get(id=key_id)
|
|
|
|
ip_group = ak.ip_group
|
|
|
|
ip = get_request_ip_or_data(request)
|
|
|
|
if not contains_ip(ip, ip_group):
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
except (AccessKey.DoesNotExist, exceptions.ValidationError):
|
|
|
|
return False
|