helper.py 8.2 KB

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