wraps.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import json
  2. import os
  3. import time
  4. from functools import wraps
  5. from flask import abort, request
  6. from flask_login import current_user # type: ignore
  7. from configs import dify_config
  8. from controllers.console.workspace.error import AccountNotInitializedError
  9. from extensions.ext_database import db
  10. from extensions.ext_redis import redis_client
  11. from models.dataset import RateLimitLog
  12. from models.model import DifySetup
  13. from services.feature_service import FeatureService, LicenseStatus
  14. from services.operation_service import OperationService
  15. from .error import NotInitValidateError, NotSetupError, UnauthorizedAndForceLogout
  16. def account_initialization_required(view):
  17. @wraps(view)
  18. def decorated(*args, **kwargs):
  19. # check account initialization
  20. account = current_user
  21. if account.status == "uninitialized":
  22. raise AccountNotInitializedError()
  23. return view(*args, **kwargs)
  24. return decorated
  25. def only_edition_cloud(view):
  26. @wraps(view)
  27. def decorated(*args, **kwargs):
  28. if dify_config.EDITION != "CLOUD":
  29. abort(404)
  30. return view(*args, **kwargs)
  31. return decorated
  32. def only_edition_self_hosted(view):
  33. @wraps(view)
  34. def decorated(*args, **kwargs):
  35. if dify_config.EDITION != "SELF_HOSTED":
  36. abort(404)
  37. return view(*args, **kwargs)
  38. return decorated
  39. def cloud_edition_billing_resource_check(resource: str):
  40. def interceptor(view):
  41. @wraps(view)
  42. def decorated(*args, **kwargs):
  43. features = FeatureService.get_features(current_user.current_tenant_id)
  44. if features.billing.enabled:
  45. members = features.members
  46. apps = features.apps
  47. vector_space = features.vector_space
  48. documents_upload_quota = features.documents_upload_quota
  49. annotation_quota_limit = features.annotation_quota_limit
  50. if resource == "members" and 0 < members.limit <= members.size:
  51. abort(403, "The number of members has reached the limit of your subscription.")
  52. elif resource == "apps" and 0 < apps.limit <= apps.size:
  53. abort(403, "The number of apps has reached the limit of your subscription.")
  54. elif resource == "vector_space" and 0 < vector_space.limit <= vector_space.size:
  55. abort(
  56. 403, "The capacity of the knowledge storage space has reached the limit of your subscription."
  57. )
  58. elif resource == "documents" and 0 < documents_upload_quota.limit <= documents_upload_quota.size:
  59. # The api of file upload is used in the multiple places,
  60. # so we need to check the source of the request from datasets
  61. source = request.args.get("source")
  62. if source == "datasets":
  63. abort(403, "The number of documents has reached the limit of your subscription.")
  64. else:
  65. return view(*args, **kwargs)
  66. elif resource == "workspace_custom" and not features.can_replace_logo:
  67. abort(403, "The workspace custom feature has reached the limit of your subscription.")
  68. elif resource == "annotation" and 0 < annotation_quota_limit.limit < annotation_quota_limit.size:
  69. abort(403, "The annotation quota has reached the limit of your subscription.")
  70. else:
  71. return view(*args, **kwargs)
  72. return view(*args, **kwargs)
  73. return decorated
  74. return interceptor
  75. def cloud_edition_billing_knowledge_limit_check(resource: str):
  76. def interceptor(view):
  77. @wraps(view)
  78. def decorated(*args, **kwargs):
  79. features = FeatureService.get_features(current_user.current_tenant_id)
  80. if features.billing.enabled:
  81. if resource == "add_segment":
  82. if features.billing.subscription.plan == "sandbox":
  83. abort(
  84. 403,
  85. "To unlock this feature and elevate your Dify experience, please upgrade to a paid plan.",
  86. )
  87. else:
  88. return view(*args, **kwargs)
  89. return view(*args, **kwargs)
  90. return decorated
  91. return interceptor
  92. def cloud_edition_billing_rate_limit_check(resource: str):
  93. def interceptor(view):
  94. @wraps(view)
  95. def decorated(*args, **kwargs):
  96. if resource == "knowledge":
  97. knowledge_rate_limit = FeatureService.get_knowledge_rate_limit(current_user.current_tenant_id)
  98. if knowledge_rate_limit.enabled:
  99. current_time = int(time.time() * 1000)
  100. key = f"rate_limit_{current_user.current_tenant_id}"
  101. redis_client.zadd(key, {current_time: current_time})
  102. redis_client.zremrangebyscore(key, 0, current_time - 60000)
  103. request_count = redis_client.zcard(key)
  104. if request_count > knowledge_rate_limit.limit:
  105. # add ratelimit record
  106. rate_limit_log = RateLimitLog(
  107. tenant_id=current_user.current_tenant_id,
  108. subscription_plan=knowledge_rate_limit.subscription_plan,
  109. operation="knowledge",
  110. )
  111. db.session.add(rate_limit_log)
  112. db.session.commit()
  113. abort(
  114. 403, "Sorry, you have reached the knowledge base request rate limit of your subscription."
  115. )
  116. return view(*args, **kwargs)
  117. return decorated
  118. return interceptor
  119. def cloud_utm_record(view):
  120. @wraps(view)
  121. def decorated(*args, **kwargs):
  122. try:
  123. features = FeatureService.get_features(current_user.current_tenant_id)
  124. if features.billing.enabled:
  125. utm_info = request.cookies.get("utm_info")
  126. if utm_info:
  127. utm_info_dict: dict = json.loads(utm_info)
  128. OperationService.record_utm(current_user.current_tenant_id, utm_info_dict)
  129. except Exception as e:
  130. pass
  131. return view(*args, **kwargs)
  132. return decorated
  133. def setup_required(view):
  134. @wraps(view)
  135. def decorated(*args, **kwargs):
  136. # check setup
  137. if (
  138. dify_config.EDITION == "SELF_HOSTED"
  139. and os.environ.get("INIT_PASSWORD")
  140. and not db.session.query(DifySetup).first()
  141. ):
  142. raise NotInitValidateError()
  143. elif dify_config.EDITION == "SELF_HOSTED" and not db.session.query(DifySetup).first():
  144. raise NotSetupError()
  145. return view(*args, **kwargs)
  146. return decorated
  147. def enterprise_license_required(view):
  148. @wraps(view)
  149. def decorated(*args, **kwargs):
  150. settings = FeatureService.get_system_features()
  151. if settings.license.status in [LicenseStatus.INACTIVE, LicenseStatus.EXPIRED, LicenseStatus.LOST]:
  152. raise UnauthorizedAndForceLogout("Your license is invalid. Please contact your administrator.")
  153. return view(*args, **kwargs)
  154. return decorated