Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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