Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

wraps.py 6.3KB

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