Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

login.py 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from functools import wraps
  2. from typing import Union, cast
  3. from flask import current_app, g, has_request_context, request
  4. from flask_login.config import EXEMPT_METHODS # type: ignore
  5. from werkzeug.local import LocalProxy
  6. from configs import dify_config
  7. from models.account import Account
  8. from models.model import EndUser
  9. #: A proxy for the current user. If no user is logged in, this will be an
  10. #: anonymous user
  11. current_user = cast(Union[Account, EndUser, None], LocalProxy(lambda: _get_user()))
  12. def login_required(func):
  13. """
  14. If you decorate a view with this, it will ensure that the current user is
  15. logged in and authenticated before calling the actual view. (If they are
  16. not, it calls the :attr:`LoginManager.unauthorized` callback.) For
  17. example::
  18. @app.route('/post')
  19. @login_required
  20. def post():
  21. pass
  22. If there are only certain times you need to require that your user is
  23. logged in, you can do so with::
  24. if not current_user.is_authenticated:
  25. return current_app.login_manager.unauthorized()
  26. ...which is essentially the code that this function adds to your views.
  27. It can be convenient to globally turn off authentication when unit testing.
  28. To enable this, if the application configuration variable `LOGIN_DISABLED`
  29. is set to `True`, this decorator will be ignored.
  30. .. Note ::
  31. Per `W3 guidelines for CORS preflight requests
  32. <http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0>`_,
  33. HTTP ``OPTIONS`` requests are exempt from login checks.
  34. :param func: The view function to decorate.
  35. :type func: function
  36. """
  37. @wraps(func)
  38. def decorated_view(*args, **kwargs):
  39. if request.method in EXEMPT_METHODS or dify_config.LOGIN_DISABLED:
  40. pass
  41. elif current_user is not None and not current_user.is_authenticated:
  42. return current_app.login_manager.unauthorized() # type: ignore
  43. # flask 1.x compatibility
  44. # current_app.ensure_sync is only available in Flask >= 2.0
  45. if callable(getattr(current_app, "ensure_sync", None)):
  46. return current_app.ensure_sync(func)(*args, **kwargs)
  47. return func(*args, **kwargs)
  48. return decorated_view
  49. def _get_user() -> EndUser | Account | None:
  50. if has_request_context():
  51. if "_login_user" not in g:
  52. current_app.login_manager._load_user() # type: ignore
  53. return g._login_user # type: ignore
  54. return None