login.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import os
  2. from functools import wraps
  3. from flask import current_app
  4. from flask import g
  5. from flask import has_request_context
  6. from flask import request, session
  7. from flask_login import user_logged_in
  8. from flask_login.config import EXEMPT_METHODS
  9. from werkzeug.exceptions import Unauthorized
  10. from werkzeug.local import LocalProxy
  11. from extensions.ext_database import db
  12. from models.account import Account, Tenant, TenantAccountJoin
  13. #: A proxy for the current user. If no user is logged in, this will be an
  14. #: anonymous user
  15. current_user = LocalProxy(lambda: _get_user())
  16. def login_required(func):
  17. """
  18. If you decorate a view with this, it will ensure that the current user is
  19. logged in and authenticated before calling the actual view. (If they are
  20. not, it calls the :attr:`LoginManager.unauthorized` callback.) For
  21. example::
  22. @app.route('/post')
  23. @login_required
  24. def post():
  25. pass
  26. If there are only certain times you need to require that your user is
  27. logged in, you can do so with::
  28. if not current_user.is_authenticated:
  29. return current_app.login_manager.unauthorized()
  30. ...which is essentially the code that this function adds to your views.
  31. It can be convenient to globally turn off authentication when unit testing.
  32. To enable this, if the application configuration variable `LOGIN_DISABLED`
  33. is set to `True`, this decorator will be ignored.
  34. .. Note ::
  35. Per `W3 guidelines for CORS preflight requests
  36. <http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0>`_,
  37. HTTP ``OPTIONS`` requests are exempt from login checks.
  38. :param func: The view function to decorate.
  39. :type func: function
  40. """
  41. @wraps(func)
  42. def decorated_view(*args, **kwargs):
  43. auth_header = request.headers.get('Authorization')
  44. admin_api_key_enable = os.getenv('ADMIN_API_KEY_ENABLE', default='False')
  45. if admin_api_key_enable:
  46. if auth_header:
  47. if ' ' not in auth_header:
  48. raise Unauthorized('Invalid Authorization header format. Expected \'Bearer <api-key>\' format.')
  49. auth_scheme, auth_token = auth_header.split(None, 1)
  50. auth_scheme = auth_scheme.lower()
  51. if auth_scheme != 'bearer':
  52. raise Unauthorized('Invalid Authorization header format. Expected \'Bearer <api-key>\' format.')
  53. admin_api_key = os.getenv('ADMIN_API_KEY')
  54. if admin_api_key:
  55. if os.getenv('ADMIN_API_KEY') == auth_token:
  56. workspace_id = request.headers.get('X-WORKSPACE-ID')
  57. if workspace_id:
  58. tenant_account_join = db.session.query(Tenant, TenantAccountJoin) \
  59. .filter(Tenant.id == workspace_id) \
  60. .filter(TenantAccountJoin.tenant_id == Tenant.id) \
  61. .filter(TenantAccountJoin.role == 'owner') \
  62. .one_or_none()
  63. if tenant_account_join:
  64. tenant, ta = tenant_account_join
  65. account = Account.query.filter_by(id=ta.account_id).first()
  66. # Login admin
  67. if account:
  68. account.current_tenant = tenant
  69. current_app.login_manager._update_request_context_with_user(account)
  70. user_logged_in.send(current_app._get_current_object(), user=_get_user())
  71. if request.method in EXEMPT_METHODS or current_app.config.get("LOGIN_DISABLED"):
  72. pass
  73. elif not current_user.is_authenticated:
  74. return current_app.login_manager.unauthorized()
  75. # flask 1.x compatibility
  76. # current_app.ensure_sync is only available in Flask >= 2.0
  77. if callable(getattr(current_app, "ensure_sync", None)):
  78. return current_app.ensure_sync(func)(*args, **kwargs)
  79. return func(*args, **kwargs)
  80. return decorated_view
  81. def _get_user():
  82. if has_request_context():
  83. if "_login_user" not in g:
  84. current_app.login_manager._load_user()
  85. return g._login_user
  86. return None