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.

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