Skip to content

Commit

Permalink
feat: add rate limiter
Browse files Browse the repository at this point in the history
  • Loading branch information
GareArc committed Dec 21, 2024
1 parent 5636d7a commit 557fc1f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
6 changes: 6 additions & 0 deletions api/controllers/console/auth/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,9 @@ class EmailCodeLoginRateLimitExceededError(BaseHTTPException):
error_code = "email_code_login_rate_limit_exceeded"
description = "Too many login emails have been sent. Please try again in 5 minutes."
code = 429


class EmailCodeAccountDeletionRateLimitExceededError(BaseHTTPException):
error_code = "email_code_account_deletion_rate_limit_exceeded"
description = "Too many account deletion emails have been sent. Please try again in 5 minutes."
code = 429
15 changes: 13 additions & 2 deletions api/services/account_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ class AccountService:
email_code_login_rate_limiter = RateLimiter(
prefix="email_code_login_rate_limit", max_attempts=1, time_window=60 * 1
)
email_code_account_deletion_rate_limiter = RateLimiter(
prefix="email_code_account_deletion_rate_limit", max_attempts=1, time_window=60 * 1
)
LOGIN_MAX_ERROR_LIMITS = 5

@staticmethod
Expand Down Expand Up @@ -245,11 +248,19 @@ def generate_account_deletion_verification_code(account: Account) -> tuple[str,
)
return code, token

@staticmethod
def send_account_deletion_verification_email(account: Account, code: str):
@classmethod
def send_account_deletion_verification_email(cls, account: Account, code: str):
if cls.email_code_account_deletion_rate_limiter.is_rate_limited(email):
from controllers.console.auth.error import \
EmailCodeAccountDeletionRateLimitExceededError

raise EmailCodeAccountDeletionRateLimitExceededError()

language, email = account.interface_language, account.email
send_account_deletion_verification_code.delay(language=language, to=email, code=code)

cls.email_code_account_deletion_rate_limiter.increment_rate_limit(email)

@staticmethod
def verify_account_deletion_code(token: str, code: str) -> bool:
token_data = TokenManager.get_token_data(token, "account_deletion")
Expand Down

0 comments on commit 557fc1f

Please sign in to comment.