helper.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import json
  2. import logging
  3. import random
  4. import re
  5. import string
  6. import subprocess
  7. import time
  8. import uuid
  9. from collections.abc import Generator, Mapping
  10. from datetime import datetime
  11. from hashlib import sha256
  12. from typing import Any, Optional, Union
  13. from zoneinfo import available_timezones
  14. from flask import Response, stream_with_context
  15. from flask_restful import fields
  16. from configs import dify_config
  17. from core.app.features.rate_limiting.rate_limit import RateLimitGenerator
  18. from core.file import helpers as file_helpers
  19. from extensions.ext_redis import redis_client
  20. from models.account import Account
  21. def run(script):
  22. return subprocess.getstatusoutput("source /root/.bashrc && " + script)
  23. class AppIconUrlField(fields.Raw):
  24. def output(self, key, obj):
  25. if obj is None:
  26. return None
  27. from models.model import App, IconType, Site
  28. if isinstance(obj, dict) and "app" in obj:
  29. obj = obj["app"]
  30. if isinstance(obj, App | Site) and obj.icon_type == IconType.IMAGE.value:
  31. return file_helpers.get_signed_file_url(obj.icon)
  32. return None
  33. class TimestampField(fields.Raw):
  34. def format(self, value) -> int:
  35. return int(value.timestamp())
  36. def email(email):
  37. # Define a regex pattern for email addresses
  38. pattern = r"^[\w\.!#$%&'*+\-/=?^_`{|}~]+@([\w-]+\.)+[\w-]{2,}$"
  39. # Check if the email matches the pattern
  40. if re.match(pattern, email) is not None:
  41. return email
  42. error = "{email} is not a valid email.".format(email=email)
  43. raise ValueError(error)
  44. def uuid_value(value):
  45. if value == "":
  46. return str(value)
  47. try:
  48. uuid_obj = uuid.UUID(value)
  49. return str(uuid_obj)
  50. except ValueError:
  51. error = "{value} is not a valid uuid.".format(value=value)
  52. raise ValueError(error)
  53. def alphanumeric(value: str):
  54. # check if the value is alphanumeric and underlined
  55. if re.match(r"^[a-zA-Z0-9_]+$", value):
  56. return value
  57. raise ValueError(f"{value} is not a valid alphanumeric value")
  58. def timestamp_value(timestamp):
  59. try:
  60. int_timestamp = int(timestamp)
  61. if int_timestamp < 0:
  62. raise ValueError
  63. return int_timestamp
  64. except ValueError:
  65. error = "{timestamp} is not a valid timestamp.".format(timestamp=timestamp)
  66. raise ValueError(error)
  67. class StrLen:
  68. """Restrict input to an integer in a range (inclusive)"""
  69. def __init__(self, max_length, argument="argument"):
  70. self.max_length = max_length
  71. self.argument = argument
  72. def __call__(self, value):
  73. length = len(value)
  74. if length > self.max_length:
  75. error = "Invalid {arg}: {val}. {arg} cannot exceed length {length}".format(
  76. arg=self.argument, val=value, length=self.max_length
  77. )
  78. raise ValueError(error)
  79. return value
  80. class FloatRange:
  81. """Restrict input to an float in a range (inclusive)"""
  82. def __init__(self, low, high, argument="argument"):
  83. self.low = low
  84. self.high = high
  85. self.argument = argument
  86. def __call__(self, value):
  87. value = _get_float(value)
  88. if value < self.low or value > self.high:
  89. error = "Invalid {arg}: {val}. {arg} must be within the range {lo} - {hi}".format(
  90. arg=self.argument, val=value, lo=self.low, hi=self.high
  91. )
  92. raise ValueError(error)
  93. return value
  94. class DatetimeString:
  95. def __init__(self, format, argument="argument"):
  96. self.format = format
  97. self.argument = argument
  98. def __call__(self, value):
  99. try:
  100. datetime.strptime(value, self.format)
  101. except ValueError:
  102. error = "Invalid {arg}: {val}. {arg} must be conform to the format {format}".format(
  103. arg=self.argument, val=value, format=self.format
  104. )
  105. raise ValueError(error)
  106. return value
  107. def _get_float(value):
  108. try:
  109. return float(value)
  110. except (TypeError, ValueError):
  111. raise ValueError("{} is not a valid float".format(value))
  112. def timezone(timezone_string):
  113. if timezone_string and timezone_string in available_timezones():
  114. return timezone_string
  115. error = "{timezone_string} is not a valid timezone.".format(timezone_string=timezone_string)
  116. raise ValueError(error)
  117. def generate_string(n):
  118. letters_digits = string.ascii_letters + string.digits
  119. result = ""
  120. for i in range(n):
  121. result += random.choice(letters_digits)
  122. return result
  123. def extract_remote_ip(request) -> str:
  124. if request.headers.get("CF-Connecting-IP"):
  125. return request.headers.get("Cf-Connecting-Ip")
  126. elif request.headers.getlist("X-Forwarded-For"):
  127. return request.headers.getlist("X-Forwarded-For")[0]
  128. else:
  129. return request.remote_addr
  130. def generate_text_hash(text: str) -> str:
  131. hash_text = str(text) + "None"
  132. return sha256(hash_text.encode()).hexdigest()
  133. def compact_generate_response(
  134. response: Union[Mapping[str, Any], RateLimitGenerator, Generator[str, None, None]],
  135. ) -> Response:
  136. if isinstance(response, dict):
  137. return Response(response=json.dumps(response), status=200, mimetype="application/json")
  138. else:
  139. def generate() -> Generator:
  140. yield from response
  141. return Response(stream_with_context(generate()), status=200, mimetype="text/event-stream")
  142. class TokenManager:
  143. @classmethod
  144. def generate_token(
  145. cls,
  146. token_type: str,
  147. account: Optional[Account] = None,
  148. email: Optional[str] = None,
  149. additional_data: Optional[dict] = None,
  150. ) -> str:
  151. if account is None and email is None:
  152. raise ValueError("Account or email must be provided")
  153. account_id = account.id if account else None
  154. account_email = account.email if account else email
  155. if account_id:
  156. old_token = cls._get_current_token_for_account(account_id, token_type)
  157. if old_token:
  158. if isinstance(old_token, bytes):
  159. old_token = old_token.decode("utf-8")
  160. cls.revoke_token(old_token, token_type)
  161. token = str(uuid.uuid4())
  162. token_data = {"account_id": account_id, "email": account_email, "token_type": token_type}
  163. if additional_data:
  164. token_data.update(additional_data)
  165. expiry_minutes = dify_config.model_dump().get(f"{token_type.upper()}_TOKEN_EXPIRY_MINUTES")
  166. token_key = cls._get_token_key(token, token_type)
  167. expiry_time = int(expiry_minutes * 60)
  168. redis_client.setex(token_key, expiry_time, json.dumps(token_data))
  169. if account_id:
  170. cls._set_current_token_for_account(account.id, token, token_type, expiry_minutes)
  171. return token
  172. @classmethod
  173. def _get_token_key(cls, token: str, token_type: str) -> str:
  174. return f"{token_type}:token:{token}"
  175. @classmethod
  176. def revoke_token(cls, token: str, token_type: str):
  177. token_key = cls._get_token_key(token, token_type)
  178. redis_client.delete(token_key)
  179. @classmethod
  180. def get_token_data(cls, token: str, token_type: str) -> Optional[dict[str, Any]]:
  181. key = cls._get_token_key(token, token_type)
  182. token_data_json = redis_client.get(key)
  183. if token_data_json is None:
  184. logging.warning(f"{token_type} token {token} not found with key {key}")
  185. return None
  186. token_data = json.loads(token_data_json)
  187. return token_data
  188. @classmethod
  189. def _get_current_token_for_account(cls, account_id: str, token_type: str) -> Optional[str]:
  190. key = cls._get_account_token_key(account_id, token_type)
  191. current_token = redis_client.get(key)
  192. return current_token
  193. @classmethod
  194. def _set_current_token_for_account(
  195. cls, account_id: str, token: str, token_type: str, expiry_hours: Union[int, float]
  196. ):
  197. key = cls._get_account_token_key(account_id, token_type)
  198. expiry_time = int(expiry_hours * 60 * 60)
  199. redis_client.setex(key, expiry_time, token)
  200. @classmethod
  201. def _get_account_token_key(cls, account_id: str, token_type: str) -> str:
  202. return f"{token_type}:account:{account_id}"
  203. class RateLimiter:
  204. def __init__(self, prefix: str, max_attempts: int, time_window: int):
  205. self.prefix = prefix
  206. self.max_attempts = max_attempts
  207. self.time_window = time_window
  208. def _get_key(self, email: str) -> str:
  209. return f"{self.prefix}:{email}"
  210. def is_rate_limited(self, email: str) -> bool:
  211. key = self._get_key(email)
  212. current_time = int(time.time())
  213. window_start_time = current_time - self.time_window
  214. redis_client.zremrangebyscore(key, "-inf", window_start_time)
  215. attempts = redis_client.zcard(key)
  216. if attempts and int(attempts) >= self.max_attempts:
  217. return True
  218. return False
  219. def increment_rate_limit(self, email: str):
  220. key = self._get_key(email)
  221. current_time = int(time.time())
  222. redis_client.zadd(key, {current_time: current_time})
  223. redis_client.expire(key, self.time_window * 2)