test_auth_token.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from flask_login import current_user, login_user, logout_user
  2. from flask_security.core import AnonymousUser
  3. from flask_security.proxies import _security
  4. from flask_security import decorators as fs_decorators
  5. from flask_principal import Identity, identity_changed
  6. from flask import url_for, current_app, request
  7. from flexmeasures.api.tests.utils import UserContext
  8. def patched_check_token() -> bool:
  9. """
  10. The _check_token function in Flask-Security is successfully getting the user,
  11. but it fails to stick with flask_login.
  12. This happens only when testing, so our test setup might not be 100% compatible
  13. with Flask >2.2 ecosystem.
  14. See for details:
  15. https://github.com/FlexMeasures/flexmeasures/pull/838#discussion_r1321692937
  16. https://github.com/Flask-Middleware/flask-security/issues/834
  17. """
  18. user = _security.login_manager.request_callback(request)
  19. if user and user.is_authenticated:
  20. app = current_app._get_current_object()
  21. identity_changed.send(app, identity=Identity(user.fs_uniquifier))
  22. login_user(user) # THIS LINE ADDED BY US
  23. return True
  24. return False
  25. def test_auth_token(monkeypatch, app, client, setup_api_test_data):
  26. """Use an auth token to query an endpoint.
  27. (we test other endpoints using the api/conftest/requesting_user fixture,
  28. so they're already logged in via session)
  29. """
  30. with UserContext("test_admin_user@seita.nl") as admin:
  31. auth_token = admin.get_auth_token()
  32. assert isinstance(current_user, AnonymousUser)
  33. monkeypatch.setattr(fs_decorators, "_check_token", patched_check_token)
  34. print("Getting assets ...")
  35. response = client.get(
  36. url_for("AssetAPI:index"), headers={"Authorization": auth_token}
  37. )
  38. print(response)
  39. assert response.status_code == 200
  40. logout_user() # undo the login made by our patch during token auth
  41. assert response.json == [] # admin has no assets themselves