helper.py 8.0 KB

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