middleware.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # Copyright: (c) OpenSpug Organization. https://github.com/openspug/spug
  2. # Copyright: (c) <spug.dev@gmail.com>
  3. # Released under the AGPL-3.0 License.
  4. from django.utils.deprecation import MiddlewareMixin
  5. from django.conf import settings
  6. from .utils import json_response, get_request_real_ip
  7. from apps.account.models import User
  8. import traceback
  9. import time
  10. class HandleExceptionMiddleware(MiddlewareMixin):
  11. """
  12. 处理试图函数异常
  13. """
  14. def process_exception(self, request, exception):
  15. traceback.print_exc()
  16. return json_response(error='Exception: %s' % exception)
  17. class AuthenticationMiddleware(MiddlewareMixin):
  18. """
  19. 登录验证
  20. """
  21. def process_request(self, request):
  22. if request.path in settings.AUTHENTICATION_EXCLUDES:
  23. return None
  24. if any(x.match(request.path) for x in settings.AUTHENTICATION_EXCLUDES if hasattr(x, 'match')):
  25. return None
  26. access_token = request.headers.get('x-token') or request.GET.get('x-token')
  27. if access_token and len(access_token) == 32:
  28. x_real_ip = get_request_real_ip(request.headers)
  29. user = User.objects.filter(access_token=access_token).first()
  30. if user and x_real_ip == user.last_ip and user.token_expired >= time.time() and user.is_active:
  31. request.user = user
  32. user.token_expired = time.time() + 8 * 60 * 60
  33. user.save()
  34. return None
  35. response = json_response(error="验证失败,请重新登录")
  36. response.status_code = 401
  37. return response