decorators.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. from functools import wraps
  2. from .models import User
  3. from utils.http import make_json_response
  4. def _login_required(error='未登录'):
  5. # 判断是否登录的decorator
  6. def is_login(request):
  7. if request.method != 'POST':
  8. return False
  9. username = request.POST.get('username', '')
  10. token = request.POST.get('token', '')
  11. print(f'username={username} token={token}')
  12. try:
  13. user = User.objects.get(username=username)
  14. except:
  15. print('用户不存在')
  16. return False
  17. if not user.check_token(token) or not user.tokens.filter(token=token):
  18. print('token无效')
  19. return False
  20. print('已登录')
  21. if hasattr(request, 'user'):
  22. request.user = user
  23. return True
  24. def decorator(view_func):
  25. @wraps(view_func)
  26. def _wrapped_view(request, *args, **kwargs):
  27. if is_login(request):
  28. return view_func(request, *args, **kwargs)
  29. return make_json_response(code=401, error=error)
  30. return _wrapped_view
  31. return decorator
  32. login_required = _login_required()