helper.py 8.8 KB

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