diff --git a/spug_api/apps/account/models.py b/spug_api/apps/account/models.py index b8ff524..e9ce731 100644 --- a/spug_api/apps/account/models.py +++ b/spug_api/apps/account/models.py @@ -12,6 +12,7 @@ class User(models.Model, ModelMixin): access_token = models.CharField(max_length=32) token_expired = models.IntegerField(null=True) last_login = models.CharField(max_length=20) + last_ip = models.CharField(max_length=50) role = models.ForeignKey('Role', on_delete=models.PROTECT, null=True) created_at = models.CharField(max_length=20, default=human_datetime) diff --git a/spug_api/apps/account/views.py b/spug_api/apps/account/views.py index 0185971..e509444 100644 --- a/spug_api/apps/account/views.py +++ b/spug_api/apps/account/views.py @@ -90,12 +90,18 @@ def login(request): return json_response(error="账户已被禁用") if user.verify_password(form.password): cache.delete(form.username) + x_real_ip = request.headers.get('x-real-ip', '') token_isvalid = user.access_token and len(user.access_token) == 32 and user.token_expired >= time.time() user.access_token = user.access_token if token_isvalid else uuid.uuid4().hex user.token_expired = time.time() + 8 * 60 * 60 user.last_login = human_datetime() + user.last_ip = x_real_ip user.save() - return json_response({'access_token': user.access_token, 'nickname': user.nickname}) + return json_response({ + 'access_token': user.access_token, + 'nickname': user.nickname, + 'has_real_ip': True if x_real_ip else False + }) value = cache.get_or_set(form.username, 0, 86400) if value >= 3: diff --git a/spug_api/libs/middleware.py b/spug_api/libs/middleware.py index 56a8d77..814e4a8 100644 --- a/spug_api/libs/middleware.py +++ b/spug_api/libs/middleware.py @@ -26,10 +26,11 @@ class AuthenticationMiddleware(MiddlewareMixin): return None if any(x.match(request.path) for x in settings.AUTHENTICATION_EXCLUDES if hasattr(x, 'match')): return None - access_token = request.META.get('HTTP_X_TOKEN') or request.GET.get('x-token') + access_token = request.headers.get('x-token') or request.GET.get('x-token') if access_token and len(access_token) == 32: + x_real_ip = request.headers.get('x-real-ip', '') user = User.objects.filter(access_token=access_token).first() - if user and user.token_expired >= time.time() and user.is_active: + if user and x_real_ip == user.last_ip and user.token_expired >= time.time() and user.is_active: request.user = user user.token_expired = time.time() + 8 * 60 * 60 user.save() diff --git a/spug_api/spug/settings.py b/spug_api/spug/settings.py index 2720777..038ec47 100644 --- a/spug_api/spug/settings.py +++ b/spug_api/spug/settings.py @@ -25,7 +25,7 @@ SECRET_KEY = 'vk0do47)egwzz!uk49%(y3s(fpx4+ha@ugt-hcv&%&d@hwr&p7' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True -ALLOWED_HOSTS = [] +ALLOWED_HOSTS = ['127.0.0.1'] # Application definition