login.py 4.2 KB

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