You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

wraps.py 6.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. from datetime import UTC, datetime
  2. from functools import wraps
  3. from flask import request
  4. from flask_restful import Resource
  5. from werkzeug.exceptions import BadRequest, NotFound, Unauthorized
  6. from controllers.web.error import WebAppAuthAccessDeniedError, WebAppAuthRequiredError
  7. from extensions.ext_database import db
  8. from libs.passport import PassportService
  9. from models.model import App, EndUser, Site
  10. from services.enterprise.enterprise_service import EnterpriseService, WebAppSettings
  11. from services.feature_service import FeatureService
  12. from services.webapp_auth_service import WebAppAuthService
  13. def validate_jwt_token(view=None):
  14. def decorator(view):
  15. @wraps(view)
  16. def decorated(*args, **kwargs):
  17. app_model, end_user = decode_jwt_token()
  18. return view(app_model, end_user, *args, **kwargs)
  19. return decorated
  20. if view:
  21. return decorator(view)
  22. return decorator
  23. def decode_jwt_token():
  24. system_features = FeatureService.get_system_features()
  25. app_code = str(request.headers.get("X-App-Code"))
  26. try:
  27. auth_header = request.headers.get("Authorization")
  28. if auth_header is None:
  29. raise Unauthorized("Authorization header is missing.")
  30. if " " not in auth_header:
  31. raise Unauthorized("Invalid Authorization header format. Expected 'Bearer <api-key>' format.")
  32. auth_scheme, tk = auth_header.split(None, 1)
  33. auth_scheme = auth_scheme.lower()
  34. if auth_scheme != "bearer":
  35. raise Unauthorized("Invalid Authorization header format. Expected 'Bearer <api-key>' format.")
  36. decoded = PassportService().verify(tk)
  37. app_code = decoded.get("app_code")
  38. app_id = decoded.get("app_id")
  39. app_model = db.session.query(App).filter(App.id == app_id).first()
  40. site = db.session.query(Site).filter(Site.code == app_code).first()
  41. if not app_model:
  42. raise NotFound()
  43. if not app_code or not site:
  44. raise BadRequest("Site URL is no longer valid.")
  45. if app_model.enable_site is False:
  46. raise BadRequest("Site is disabled.")
  47. end_user_id = decoded.get("end_user_id")
  48. end_user = db.session.query(EndUser).filter(EndUser.id == end_user_id).first()
  49. if not end_user:
  50. raise NotFound()
  51. # for enterprise webapp auth
  52. app_web_auth_enabled = False
  53. webapp_settings = None
  54. if system_features.webapp_auth.enabled:
  55. webapp_settings = EnterpriseService.WebAppAuth.get_app_access_mode_by_code(app_code=app_code)
  56. if not webapp_settings:
  57. raise NotFound("Web app settings not found.")
  58. app_web_auth_enabled = webapp_settings.access_mode != "public"
  59. _validate_webapp_token(decoded, app_web_auth_enabled, system_features.webapp_auth.enabled)
  60. _validate_user_accessibility(
  61. decoded, app_code, app_web_auth_enabled, system_features.webapp_auth.enabled, webapp_settings
  62. )
  63. return app_model, end_user
  64. except Unauthorized as e:
  65. if system_features.webapp_auth.enabled:
  66. if not app_code:
  67. raise Unauthorized("Please re-login to access the web app.")
  68. app_web_auth_enabled = (
  69. EnterpriseService.WebAppAuth.get_app_access_mode_by_code(app_code=str(app_code)).access_mode != "public"
  70. )
  71. if app_web_auth_enabled:
  72. raise WebAppAuthRequiredError()
  73. raise Unauthorized(e.description)
  74. def _validate_webapp_token(decoded, app_web_auth_enabled: bool, system_webapp_auth_enabled: bool):
  75. # Check if authentication is enforced for web app, and if the token source is not webapp,
  76. # raise an error and redirect to login
  77. if system_webapp_auth_enabled and app_web_auth_enabled:
  78. source = decoded.get("token_source")
  79. if not source or source != "webapp":
  80. raise WebAppAuthRequiredError()
  81. # Check if authentication is not enforced for web, and if the token source is webapp,
  82. # raise an error and redirect to normal passport login
  83. if not system_webapp_auth_enabled or not app_web_auth_enabled:
  84. source = decoded.get("token_source")
  85. if source and source == "webapp":
  86. raise Unauthorized("webapp token expired.")
  87. def _validate_user_accessibility(
  88. decoded,
  89. app_code,
  90. app_web_auth_enabled: bool,
  91. system_webapp_auth_enabled: bool,
  92. webapp_settings: WebAppSettings | None,
  93. ):
  94. if system_webapp_auth_enabled and app_web_auth_enabled:
  95. # Check if the user is allowed to access the web app
  96. user_id = decoded.get("user_id")
  97. if not user_id:
  98. raise WebAppAuthRequiredError()
  99. if not webapp_settings:
  100. raise WebAppAuthRequiredError("Web app settings not found.")
  101. if WebAppAuthService.is_app_require_permission_check(access_mode=webapp_settings.access_mode):
  102. if not EnterpriseService.WebAppAuth.is_user_allowed_to_access_webapp(user_id, app_code=app_code):
  103. raise WebAppAuthAccessDeniedError()
  104. auth_type = decoded.get("auth_type")
  105. granted_at = decoded.get("granted_at")
  106. if not auth_type:
  107. raise WebAppAuthAccessDeniedError("Missing auth_type in the token.")
  108. if not granted_at:
  109. raise WebAppAuthAccessDeniedError("Missing granted_at in the token.")
  110. # check if sso has been updated
  111. if auth_type == "external":
  112. last_update_time = EnterpriseService.get_app_sso_settings_last_update_time()
  113. if granted_at and datetime.fromtimestamp(granted_at, tz=UTC) < last_update_time:
  114. raise WebAppAuthAccessDeniedError("SSO settings have been updated. Please re-login.")
  115. elif auth_type == "internal":
  116. last_update_time = EnterpriseService.get_workspace_sso_settings_last_update_time()
  117. if granted_at and datetime.fromtimestamp(granted_at, tz=UTC) < last_update_time:
  118. raise WebAppAuthAccessDeniedError("SSO settings have been updated. Please re-login.")
  119. class WebApiResource(Resource):
  120. method_decorators = [validate_jwt_token]