Skip to content

Instantly share code, notes, and snippets.

View njwest's full-sized avatar
🎹
Groovin

Nick West 韋羲 njwest

🎹
Groovin
View GitHub Profile
@spec allow_login_attempt?(String.t(), non_neg_integer()) :: boolean()
def allow_login_attempt?(email, limit \\ @login_request_limit) do
def allow_login_attempt?(email, limit \\ @login_request_limit)
when is_binary(email) and is_integer(limit) and limit >= 0 do
# ...code omitted
require Logger
# ...code omitted
def allow_login_attempt?(email, limit \\ @login_request_limit) do
case ExRated.check_rate("login_attempt:#{email}", @time_window, limit) do
{:ok, _count} -> true
{:error, _limit} ->
Logger.warning("Login attempt limit exceeded for email: #{email}")
doctest RateLimiter
test "allow_login_attempt?/2 returns true when login attempts do not exceed a limit of #{@limit}" do
assert RateLimiter.allow_login_attempt?(@test_email, @limit) == true
assert RateLimiter.allow_login_attempt?(@test_email, @limit) == true
end
@test_email "test@example.com"
@limit 2
setup do
# Empty the login attempt bucket for @test_email before each test
ExRated.delete_bucket("login_attempt:#{@test_email}")
:ok
end
# ...code omitted
import ExUnit.CaptureLog
# ...code omitted
test "allow_login_attempt?/2 returns false with a warning log when over the login attempt limit" do
assert RateLimiter.allow_login_attempt?(@test_email, @limit) == true
assert RateLimiter.allow_login_attempt?(@test_email, @limit) == true
log = capture_log(fn ->
assert RateLimiter.allow_login_attempt?(@test_email, @limit) == false
defmodule RateLimiterTest do
use ExUnit.Case
import ExUnit.CaptureLog
@test_email "test@example.com"
@limit 2
# ...code omitted
@njwest
njwest / doctest_example.ex
Created July 20, 2024 17:35
Bad Doctest Exmaple
@doc """
iex> RateLimiter.allow_login_attempt?("doctest@example.com", 1)
true
iex> RateLimiter.allow_login_attempt?("doctest@example.com", 0)
false
"""
# ...code omitted
@login_request_limit 4 # login request limit per time window
@time_window 600_000 # 10 minutes in milliseconds
# ...doc omitted
def allow_login_attempt?(email, limit \\ @login_request_limit) do
case ExRated.check_rate("login_attempt:#{email}", @time_window, limit) do
{:ok, _count} -> true
{:error, _limit} -> false
end
@njwest
njwest / rate_limiter.ex
Last active July 20, 2024 17:20
Rate Limiter with @doc
defmodule RateLimiter do
# ...code omitted
@doc """
Check the login attempt rate limit for a given email address.
iex> RateLimiter.allow_login_attempt?("doctest@example.com", 1)
true
iex> RateLimiter.allow_login_attempt?("doctest@example.com", 0)