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 4.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. from functools import wraps
  2. from flask import request
  3. from flask_restful import Resource
  4. from werkzeug.exceptions import BadRequest, NotFound, Unauthorized
  5. from controllers.web.error import WebAppAuthAccessDeniedError, WebAppAuthRequiredError
  6. from extensions.ext_database import db
  7. from libs.passport import PassportService
  8. from models.model import App, EndUser, Site
  9. from services.enterprise.enterprise_service import EnterpriseService
  10. from services.feature_service import FeatureService
  11. def validate_jwt_token(view=None):
  12. def decorator(view):
  13. @wraps(view)
  14. def decorated(*args, **kwargs):
  15. app_model, end_user = decode_jwt_token()
  16. return view(app_model, end_user, *args, **kwargs)
  17. return decorated
  18. if view:
  19. return decorator(view)
  20. return decorator
  21. def decode_jwt_token():
  22. system_features = FeatureService.get_system_features()
  23. app_code = str(request.headers.get("X-App-Code"))
  24. try:
  25. auth_header = request.headers.get("Authorization")
  26. if auth_header is None:
  27. raise Unauthorized("Authorization header is missing.")
  28. if " " not in auth_header:
  29. raise Unauthorized("Invalid Authorization header format. Expected 'Bearer <api-key>' format.")
  30. auth_scheme, tk = auth_header.split(None, 1)
  31. auth_scheme = auth_scheme.lower()
  32. if auth_scheme != "bearer":
  33. raise Unauthorized("Invalid Authorization header format. Expected 'Bearer <api-key>' format.")
  34. decoded = PassportService().verify(tk)
  35. app_code = decoded.get("app_code")
  36. app_model = db.session.query(App).filter(App.id == decoded["app_id"]).first()
  37. site = db.session.query(Site).filter(Site.code == app_code).first()
  38. if not app_model:
  39. raise NotFound()
  40. if not app_code or not site:
  41. raise BadRequest("Site URL is no longer valid.")
  42. if app_model.enable_site is False:
  43. raise BadRequest("Site is disabled.")
  44. end_user = db.session.query(EndUser).filter(EndUser.id == decoded["end_user_id"]).first()
  45. if not end_user:
  46. raise NotFound()
  47. # for enterprise webapp auth
  48. app_web_auth_enabled = False
  49. if system_features.webapp_auth.enabled:
  50. app_web_auth_enabled = (
  51. EnterpriseService.WebAppAuth.get_app_access_mode_by_code(app_code=app_code).access_mode != "public"
  52. )
  53. _validate_webapp_token(decoded, app_web_auth_enabled, system_features.webapp_auth.enabled)
  54. _validate_user_accessibility(decoded, app_code, app_web_auth_enabled, system_features.webapp_auth.enabled)
  55. return app_model, end_user
  56. except Unauthorized as e:
  57. if system_features.webapp_auth.enabled:
  58. app_web_auth_enabled = (
  59. EnterpriseService.WebAppAuth.get_app_access_mode_by_code(app_code=str(app_code)).access_mode != "public"
  60. )
  61. if app_web_auth_enabled:
  62. raise WebAppAuthRequiredError()
  63. raise Unauthorized(e.description)
  64. def _validate_webapp_token(decoded, app_web_auth_enabled: bool, system_webapp_auth_enabled: bool):
  65. # Check if authentication is enforced for web app, and if the token source is not webapp,
  66. # raise an error and redirect to login
  67. if system_webapp_auth_enabled and app_web_auth_enabled:
  68. source = decoded.get("token_source")
  69. if not source or source != "webapp":
  70. raise WebAppAuthRequiredError()
  71. # Check if authentication is not enforced for web, and if the token source is webapp,
  72. # raise an error and redirect to normal passport login
  73. if not system_webapp_auth_enabled or not app_web_auth_enabled:
  74. source = decoded.get("token_source")
  75. if source and source == "webapp":
  76. raise Unauthorized("webapp token expired.")
  77. def _validate_user_accessibility(decoded, app_code, app_web_auth_enabled: bool, system_webapp_auth_enabled: bool):
  78. if system_webapp_auth_enabled and app_web_auth_enabled:
  79. # Check if the user is allowed to access the web app
  80. user_id = decoded.get("user_id")
  81. if not user_id:
  82. raise WebAppAuthRequiredError()
  83. if not EnterpriseService.WebAppAuth.is_user_allowed_to_access_webapp(user_id, app_code=app_code):
  84. raise WebAppAuthAccessDeniedError()
  85. class WebApiResource(Resource):
  86. method_decorators = [validate_jwt_token]