您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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