__init__.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """
  2. Authentication and authorization policies and helpers.
  3. """
  4. from flask import Flask
  5. from flask_security import Security, SQLAlchemySessionUserDatastore
  6. from flask_login import user_logged_in, current_user
  7. from werkzeug.exceptions import Forbidden, Unauthorized
  8. from flexmeasures.data import db
  9. def register_at(app: Flask):
  10. from flexmeasures.auth.error_handling import (
  11. unauthenticated_handler,
  12. unauthenticated_handler_e,
  13. ) # noqa: F401
  14. from flexmeasures.auth.error_handling import (
  15. unauthorized_handler,
  16. unauthorized_handler_e,
  17. ) # noqa: F401
  18. from flexmeasures.data.models.user import (
  19. User,
  20. Role,
  21. remember_login,
  22. remember_last_seen,
  23. ) # noqa: F401
  24. # Setup Flask-Security-Too for user authentication & authorization
  25. user_datastore = SQLAlchemySessionUserDatastore(db.session, User, Role)
  26. app.security = Security(app, user_datastore)
  27. # Register custom auth problem handlers.
  28. # Note how we are switching authorization and authentication - read more about this in error_handling.py!
  29. # Flask-Security-Too seems to handle it the intended way:
  30. # https://flask-security-too.readthedocs.io/en/stable/api.html#flask_security.Security.unauthn_handler
  31. # is defaulting to 401.
  32. app.security.unauthn_handler(unauthenticated_handler)
  33. app.register_error_handler(Unauthorized, unauthenticated_handler_e)
  34. app.security.unauthz_handler(unauthorized_handler)
  35. app.register_error_handler(Forbidden, unauthorized_handler_e)
  36. # add our custom handler for a user login event
  37. user_logged_in.connect(remember_login)
  38. # also store when the last contact was
  39. @app.before_request
  40. def record_last_seen():
  41. remember_last_seen(current_user)