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

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