Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generalize attempts to use resources #4532

Merged
merged 5 commits into from
Jan 28, 2025
Merged

Conversation

tspenov
Copy link
Contributor

@tspenov tspenov commented Jan 21, 2025

Rate Limiting System Refactor

Changes

  • Introduced a new generic AccessAttempt module to handle rate limiting across different features
  • Created AccessAttemptBehaviour to define a common interface for rate-limited actions
  • Migrated email login attempts to use the new system
  • Added rate limiting for coupon code validation
  • Added comprehensive tests for the new rate limiting system

Technical Details

  • Created new access_attempts table to track attempts across different features
  • Each attempt type (email login, coupon validation) has its own configuration for:
    • Time interval
    • Maximum attempts per user
    • Maximum attempts per IP address
  • Implemented proper error handling and user-friendly error messages

This refactor makes it easier to add rate limiting to new features while maintaining consistent behavior and configuration across the application.

Example implementation of the behaviour

defmodule Sanbase.Accounts.CouponAttempt do
  @behaviour Sanbase.Accounts.AccessAttemptBehaviour
  alias Sanbase.Accounts.AccessAttempt

  @impl true
  def type, do: "coupon"

  @impl true
  def config do
    %{
      interval_in_minutes: 10,
      allowed_user_attempts: 5,
      allowed_ip_attempts: 20
    }
  end

  @impl true
  def check_attempt_limit(user, remote_ip) do
    AccessAttempt.check_attempt_limit(type(), user, remote_ip)
  end

  @impl true
  def create(user, remote_ip) do
    AccessAttempt.create(type(), user, remote_ip)
  end
end

Ticket

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • I have tried to find clearer solution before commenting hard-to-understand parts of code
  • I have added tests that prove my fix is effective or that my feature works

@tspenov tspenov merged commit 02afec1 into master Jan 28, 2025
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants