login.py 4.3 KB

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