helper.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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 extensions.ext_redis import redis_client
  17. from models.account import Account
  18. def run(script):
  19. return subprocess.getstatusoutput('source /root/.bashrc && ' + script)
  20. class TimestampField(fields.Raw):
  21. def format(self, value) -> int:
  22. return int(value.timestamp())
  23. def email(email):
  24. # Define a regex pattern for email addresses
  25. pattern = r"^[\w\.!#$%&'*+\-/=?^_`{|}~]+@([\w-]+\.)+[\w-]{2,}$"
  26. # Check if the email matches the pattern
  27. if re.match(pattern, email) is not None:
  28. return email
  29. error = ('{email} is not a valid email.'
  30. .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.'
  40. .format(value=value))
  41. raise ValueError(error)
  42. def alphanumeric(value: str):
  43. # check if the value is alphanumeric and underlined
  44. if re.match(r'^[a-zA-Z0-9_]+$', value):
  45. return value
  46. raise ValueError(f'{value} is not a valid alphanumeric value')
  47. def timestamp_value(timestamp):
  48. try:
  49. int_timestamp = int(timestamp)
  50. if int_timestamp < 0:
  51. raise ValueError
  52. return int_timestamp
  53. except ValueError:
  54. error = ('{timestamp} is not a valid timestamp.'
  55. .format(timestamp=timestamp))
  56. raise ValueError(error)
  57. class str_len:
  58. """ Restrict input to an integer in a range (inclusive) """
  59. def __init__(self, max_length, argument='argument'):
  60. self.max_length = max_length
  61. self.argument = argument
  62. def __call__(self, value):
  63. length = len(value)
  64. if length > self.max_length:
  65. error = ('Invalid {arg}: {val}. {arg} cannot exceed length {length}'
  66. .format(arg=self.argument, val=value, length=self.max_length))
  67. raise ValueError(error)
  68. return value
  69. class float_range:
  70. """ Restrict input to an float in a range (inclusive) """
  71. def __init__(self, low, high, argument='argument'):
  72. self.low = low
  73. self.high = high
  74. self.argument = argument
  75. def __call__(self, value):
  76. value = _get_float(value)
  77. if value < self.low or value > self.high:
  78. error = ('Invalid {arg}: {val}. {arg} must be within the range {lo} - {hi}'
  79. .format(arg=self.argument, val=value, lo=self.low, hi=self.high))
  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}'
  91. .format(arg=self.argument, val=value, format=self.format))
  92. raise ValueError(error)
  93. return value
  94. def _get_float(value):
  95. try:
  96. return float(value)
  97. except (TypeError, ValueError):
  98. raise ValueError('{} is not a valid float'.format(value))
  99. def timezone(timezone_string):
  100. if timezone_string and timezone_string in available_timezones():
  101. return timezone_string
  102. error = ('{timezone_string} is not a valid timezone.'
  103. .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, Generator]) -> 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,
  128. mimetype='text/event-stream')
  129. class TokenManager:
  130. @classmethod
  131. def generate_token(cls, account: Account, token_type: str, additional_data: dict = None) -> str:
  132. old_token = cls._get_current_token_for_account(account.id, token_type)
  133. if old_token:
  134. if isinstance(old_token, bytes):
  135. old_token = old_token.decode('utf-8')
  136. cls.revoke_token(old_token, token_type)
  137. token = str(uuid.uuid4())
  138. token_data = {
  139. 'account_id': account.id,
  140. 'email': account.email,
  141. 'token_type': token_type
  142. }
  143. if additional_data:
  144. token_data.update(additional_data)
  145. expiry_hours = current_app.config[f'{token_type.upper()}_TOKEN_EXPIRY_HOURS']
  146. token_key = cls._get_token_key(token, token_type)
  147. redis_client.setex(
  148. token_key,
  149. expiry_hours * 60 * 60,
  150. json.dumps(token_data)
  151. )
  152. cls._set_current_token_for_account(account.id, token, token_type, expiry_hours)
  153. return token
  154. @classmethod
  155. def _get_token_key(cls, token: str, token_type: str) -> str:
  156. return f'{token_type}:token:{token}'
  157. @classmethod
  158. def revoke_token(cls, token: str, token_type: str):
  159. token_key = cls._get_token_key(token, token_type)
  160. redis_client.delete(token_key)
  161. @classmethod
  162. def get_token_data(cls, token: str, token_type: str) -> Optional[dict[str, Any]]:
  163. key = cls._get_token_key(token, token_type)
  164. token_data_json = redis_client.get(key)
  165. if token_data_json is None:
  166. logging.warning(f"{token_type} token {token} not found with key {key}")
  167. return None
  168. token_data = json.loads(token_data_json)
  169. return token_data
  170. @classmethod
  171. def _get_current_token_for_account(cls, account_id: str, token_type: str) -> Optional[str]:
  172. key = cls._get_account_token_key(account_id, token_type)
  173. current_token = redis_client.get(key)
  174. return current_token
  175. @classmethod
  176. def _set_current_token_for_account(cls, account_id: str, token: str, token_type: str, expiry_hours: int):
  177. key = cls._get_account_token_key(account_id, token_type)
  178. redis_client.setex(key, expiry_hours * 60 * 60, token)
  179. @classmethod
  180. def _get_account_token_key(cls, account_id: str, token_type: str) -> str:
  181. return f'{token_type}:account:{account_id}'
  182. class RateLimiter:
  183. def __init__(self, prefix: str, max_attempts: int, time_window: int):
  184. self.prefix = prefix
  185. self.max_attempts = max_attempts
  186. self.time_window = time_window
  187. def _get_key(self, email: str) -> str:
  188. return f"{self.prefix}:{email}"
  189. def is_rate_limited(self, email: str) -> bool:
  190. key = self._get_key(email)
  191. current_time = int(time.time())
  192. window_start_time = current_time - self.time_window
  193. redis_client.zremrangebyscore(key, '-inf', window_start_time)
  194. attempts = redis_client.zcard(key)
  195. if attempts and int(attempts) >= self.max_attempts:
  196. return True
  197. return False
  198. def increment_rate_limit(self, email: str):
  199. key = self._get_key(email)
  200. current_time = int(time.time())
  201. redis_client.zadd(key, {current_time: current_time})
  202. redis_client.expire(key, self.time_window * 2)