forked from cartsnitch/cartsnitch
Merge pull request #213 from cartsnitch/dev
Promote to UAT: vite, mock-auth, Redis rate-limit, Redis cache, email verification
This commit is contained in:
@@ -47,5 +47,30 @@ class CacheClient:
|
|||||||
return
|
return
|
||||||
await self._client.delete(key)
|
await self._client.delete(key)
|
||||||
|
|
||||||
|
async def invalidate_price_cache(self, product_id: str) -> None:
|
||||||
|
"""Invalidate all price-related cache entries for a product."""
|
||||||
|
if not self._client:
|
||||||
|
return
|
||||||
|
pattern = f"price:*:{product_id}"
|
||||||
|
await self._delete_pattern(pattern)
|
||||||
|
|
||||||
|
async def invalidate_product_cache(self, product_id: str) -> None:
|
||||||
|
"""Invalidate the product detail cache entry."""
|
||||||
|
if not self._client:
|
||||||
|
return
|
||||||
|
await self._client.delete(f"product:{product_id}")
|
||||||
|
|
||||||
|
async def _delete_pattern(self, pattern: str) -> None:
|
||||||
|
"""Delete all keys matching a pattern using SCAN."""
|
||||||
|
if not self._client:
|
||||||
|
return
|
||||||
|
cursor = 0
|
||||||
|
while True:
|
||||||
|
cursor, keys = await self._client.scan(cursor=cursor, match=pattern, count=100)
|
||||||
|
if keys:
|
||||||
|
await self._client.delete(*keys)
|
||||||
|
if cursor == 0:
|
||||||
|
break
|
||||||
|
|
||||||
|
|
||||||
cache_client = CacheClient()
|
cache_client = CacheClient()
|
||||||
|
|||||||
@@ -32,6 +32,9 @@ class Settings(BaseSettings):
|
|||||||
|
|
||||||
rate_limit_requests: int = 60
|
rate_limit_requests: int = 60
|
||||||
rate_limit_window_seconds: int = 60
|
rate_limit_window_seconds: int = 60
|
||||||
|
rate_limit_auth_requests: int = 5
|
||||||
|
rate_limit_auth_window_seconds: int = 60
|
||||||
|
rate_limit_redis_enabled: bool = True
|
||||||
rate_limit_enabled: bool = True
|
rate_limit_enabled: bool = True
|
||||||
|
|
||||||
_PLACEHOLDER_VALUES = {"change-me-in-production"}
|
_PLACEHOLDER_VALUES = {"change-me-in-production"}
|
||||||
@@ -72,7 +75,9 @@ class Settings(BaseSettings):
|
|||||||
def normalize_database_url(self):
|
def normalize_database_url(self):
|
||||||
"""Normalize postgresql:// → postgresql+asyncpg:// for the asyncpg driver."""
|
"""Normalize postgresql:// → postgresql+asyncpg:// for the asyncpg driver."""
|
||||||
if self.database_url.startswith("postgresql://"):
|
if self.database_url.startswith("postgresql://"):
|
||||||
self.database_url = self.database_url.replace("postgresql://", "postgresql+asyncpg://", 1)
|
self.database_url = self.database_url.replace(
|
||||||
|
"postgresql://", "postgresql+asyncpg://", 1
|
||||||
|
)
|
||||||
return self
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -5,18 +5,31 @@ Per-IP limiting on public endpoints, per-token limiting on authenticated endpoin
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import hashlib
|
import hashlib
|
||||||
|
import logging
|
||||||
import time
|
import time
|
||||||
|
import uuid
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from threading import Lock
|
from threading import Lock
|
||||||
|
from typing import Protocol
|
||||||
|
|
||||||
from fastapi import FastAPI, Request, status
|
from fastapi import FastAPI, Request, status
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
|
from redis.asyncio import Redis, RedisError
|
||||||
from starlette.middleware.base import BaseHTTPMiddleware
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
|
|
||||||
from cartsnitch_api.config import settings
|
from cartsnitch_api.config import settings
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
class _SlidingWindowCounter:
|
|
||||||
|
class RateLimitBackend(Protocol):
|
||||||
|
"""Protocol for rate limit backends."""
|
||||||
|
|
||||||
|
async def is_allowed(self, key: str) -> tuple[bool, int, int]:
|
||||||
|
"""Check if request is allowed. Returns (allowed, remaining, retry_after)."""
|
||||||
|
|
||||||
|
|
||||||
|
class InMemorySlidingWindow:
|
||||||
"""Thread-safe in-memory sliding window rate limiter."""
|
"""Thread-safe in-memory sliding window rate limiter."""
|
||||||
|
|
||||||
def __init__(self, max_requests: int, window_seconds: int) -> None:
|
def __init__(self, max_requests: int, window_seconds: int) -> None:
|
||||||
@@ -25,13 +38,12 @@ class _SlidingWindowCounter:
|
|||||||
self._hits: dict[str, list[float]] = defaultdict(list)
|
self._hits: dict[str, list[float]] = defaultdict(list)
|
||||||
self._lock = Lock()
|
self._lock = Lock()
|
||||||
|
|
||||||
def is_allowed(self, key: str) -> tuple[bool, int, int]:
|
async def is_allowed(self, key: str) -> tuple[bool, int, int]:
|
||||||
"""Check if request is allowed. Returns (allowed, remaining, retry_after)."""
|
"""Check if request is allowed. Returns (allowed, remaining, retry_after)."""
|
||||||
now = time.monotonic()
|
now = time.monotonic()
|
||||||
cutoff = now - self.window_seconds
|
cutoff = now - self.window_seconds
|
||||||
|
|
||||||
with self._lock:
|
with self._lock:
|
||||||
# Prune expired entries
|
|
||||||
self._hits[key] = [t for t in self._hits[key] if t > cutoff]
|
self._hits[key] = [t for t in self._hits[key] if t > cutoff]
|
||||||
|
|
||||||
current_count = len(self._hits[key])
|
current_count = len(self._hits[key])
|
||||||
@@ -44,15 +56,84 @@ class _SlidingWindowCounter:
|
|||||||
return True, remaining, 0
|
return True, remaining, 0
|
||||||
|
|
||||||
|
|
||||||
# Module-level counters — one for public (per-IP), one for auth (per-token)
|
class RedisSlidingWindow:
|
||||||
_public_limiter = _SlidingWindowCounter(
|
"""Redis-backed sliding window rate limiter using sorted sets."""
|
||||||
max_requests=settings.rate_limit_requests,
|
|
||||||
window_seconds=settings.rate_limit_window_seconds,
|
def __init__(self, redis: Redis, max_requests: int, window_seconds: int) -> None:
|
||||||
)
|
self.redis = redis
|
||||||
_auth_limiter = _SlidingWindowCounter(
|
self.max_requests = max_requests
|
||||||
max_requests=settings.rate_limit_requests * 5, # 300/min for authenticated users
|
self.window_seconds = window_seconds
|
||||||
window_seconds=settings.rate_limit_window_seconds,
|
|
||||||
)
|
async def is_allowed(self, key: str) -> tuple[bool, int, int]:
|
||||||
|
"""Check if request is allowed. Returns (allowed, remaining, retry_after)."""
|
||||||
|
try:
|
||||||
|
now = time.monotonic()
|
||||||
|
cutoff = now - self.window_seconds
|
||||||
|
now_ms = int(now * 1000)
|
||||||
|
cutoff_ms = int(cutoff * 1000)
|
||||||
|
|
||||||
|
pipe = self.redis.pipeline()
|
||||||
|
pipe.zremrangebyscore(key, 0, cutoff_ms)
|
||||||
|
pipe.zcard(key)
|
||||||
|
results = await pipe.execute()
|
||||||
|
|
||||||
|
current_count = results[1]
|
||||||
|
|
||||||
|
if current_count >= self.max_requests:
|
||||||
|
oldest = await self.redis.zrange(key, 0, 0, withscores=True)
|
||||||
|
if oldest:
|
||||||
|
retry_after = int((oldest[0][1] - cutoff) / 1000) + 1
|
||||||
|
else:
|
||||||
|
retry_after = self.window_seconds
|
||||||
|
return False, 0, retry_after
|
||||||
|
|
||||||
|
member = f"{now_ms}:{uuid.uuid4().hex[:8]}"
|
||||||
|
pipe = self.redis.pipeline()
|
||||||
|
pipe.zadd(key, {member: now_ms})
|
||||||
|
pipe.expire(key, self.window_seconds)
|
||||||
|
await pipe.execute()
|
||||||
|
|
||||||
|
remaining = self.max_requests - current_count - 1
|
||||||
|
return True, remaining, 0
|
||||||
|
|
||||||
|
except RedisError as e:
|
||||||
|
logger.warning("Redis rate limit error, falling back to in-memory: %s", e)
|
||||||
|
in_memory = InMemorySlidingWindow(self.max_requests, self.window_seconds)
|
||||||
|
return await in_memory.is_allowed(key)
|
||||||
|
|
||||||
|
|
||||||
|
_redis_client: Redis | None = None
|
||||||
|
_use_redis = False
|
||||||
|
|
||||||
|
if settings.rate_limit_redis_enabled:
|
||||||
|
try:
|
||||||
|
_redis_client = Redis.from_url(settings.redis_url)
|
||||||
|
_use_redis = True
|
||||||
|
logger.info("Rate limiting will use Redis at %s", settings.redis_url)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed to connect to Redis for rate limiting, using in-memory: %s", e)
|
||||||
|
_use_redis = False
|
||||||
|
|
||||||
|
if _use_redis and _redis_client:
|
||||||
|
_public_limiter = RedisSlidingWindow(
|
||||||
|
_redis_client, settings.rate_limit_requests, settings.rate_limit_window_seconds
|
||||||
|
)
|
||||||
|
_auth_limiter = RedisSlidingWindow(
|
||||||
|
_redis_client, settings.rate_limit_requests * 5, settings.rate_limit_window_seconds
|
||||||
|
)
|
||||||
|
_auth_strict_limiter = RedisSlidingWindow(
|
||||||
|
_redis_client, settings.rate_limit_auth_requests, settings.rate_limit_auth_window_seconds
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
_public_limiter = InMemorySlidingWindow(
|
||||||
|
settings.rate_limit_requests, settings.rate_limit_window_seconds
|
||||||
|
)
|
||||||
|
_auth_limiter = InMemorySlidingWindow(
|
||||||
|
settings.rate_limit_requests * 5, settings.rate_limit_window_seconds
|
||||||
|
)
|
||||||
|
_auth_strict_limiter = InMemorySlidingWindow(
|
||||||
|
settings.rate_limit_auth_requests, settings.rate_limit_auth_window_seconds
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _get_client_ip(request: Request) -> str:
|
def _get_client_ip(request: Request) -> str:
|
||||||
@@ -63,30 +144,30 @@ def _get_client_ip(request: Request) -> str:
|
|||||||
return request.client.host if request.client else "unknown"
|
return request.client.host if request.client else "unknown"
|
||||||
|
|
||||||
|
|
||||||
def _get_rate_limit_key(request: Request) -> tuple[str, _SlidingWindowCounter]:
|
def _get_rate_limit_key(request: Request) -> tuple[str, RateLimitBackend]:
|
||||||
"""Determine rate limit key and which limiter to use."""
|
"""Determine rate limit key and which limiter to use."""
|
||||||
if request.url.path.startswith("/public"):
|
if request.url.path.startswith("/public"):
|
||||||
return f"ip:{_get_client_ip(request)}", _public_limiter
|
return f"ip:{_get_client_ip(request)}", _public_limiter
|
||||||
|
|
||||||
# For authenticated endpoints, use Bearer token as key if present
|
if request.url.path.startswith("/auth/") and request.method == "POST":
|
||||||
|
return f"ip:{_get_client_ip(request)}", _auth_strict_limiter
|
||||||
|
|
||||||
auth_header = request.headers.get("authorization", "")
|
auth_header = request.headers.get("authorization", "")
|
||||||
if auth_header.startswith("Bearer "):
|
if auth_header.startswith("Bearer "):
|
||||||
token = auth_header[7:]
|
token = auth_header[7:]
|
||||||
token_hash = hashlib.sha256(token.encode()).hexdigest()
|
token_hash = hashlib.sha256(token.encode()).hexdigest()
|
||||||
return f"token:{token_hash}", _auth_limiter
|
return f"token:{token_hash}", _auth_limiter
|
||||||
|
|
||||||
# Fallback to IP for unauthenticated non-public endpoints
|
|
||||||
return f"ip:{_get_client_ip(request)}", _public_limiter
|
return f"ip:{_get_client_ip(request)}", _public_limiter
|
||||||
|
|
||||||
|
|
||||||
class RateLimitMiddleware(BaseHTTPMiddleware):
|
class RateLimitMiddleware(BaseHTTPMiddleware):
|
||||||
async def dispatch(self, request: Request, call_next):
|
async def dispatch(self, request: Request, call_next):
|
||||||
# Skip rate limiting when disabled (e.g. in tests) or for health checks
|
|
||||||
if not settings.rate_limit_enabled or request.url.path == "/health":
|
if not settings.rate_limit_enabled or request.url.path == "/health":
|
||||||
return await call_next(request)
|
return await call_next(request)
|
||||||
|
|
||||||
key, limiter = _get_rate_limit_key(request)
|
key, limiter = _get_rate_limit_key(request)
|
||||||
allowed, remaining, retry_after = limiter.is_allowed(key)
|
allowed, remaining, retry_after = await limiter.is_allowed(key)
|
||||||
|
|
||||||
if not allowed:
|
if not allowed:
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
|
|||||||
@@ -1,49 +1,184 @@
|
|||||||
"""Tests for rate limiting middleware."""
|
"""Tests for rate limiting middleware."""
|
||||||
|
|
||||||
from unittest.mock import MagicMock
|
import time
|
||||||
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from cartsnitch_api.middleware.rate_limit import _SlidingWindowCounter, _get_rate_limit_key
|
from cartsnitch_api.config import settings
|
||||||
|
from cartsnitch_api.middleware.rate_limit import (
|
||||||
|
InMemorySlidingWindow,
|
||||||
|
RedisSlidingWindow,
|
||||||
|
_get_client_ip,
|
||||||
|
_get_rate_limit_key,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class TestSlidingWindowCounter:
|
class TestInMemorySlidingWindow:
|
||||||
def test_allows_within_limit(self):
|
def test_allows_within_limit(self):
|
||||||
counter = _SlidingWindowCounter(max_requests=5, window_seconds=60)
|
limiter = InMemorySlidingWindow(max_requests=5, window_seconds=60)
|
||||||
for i in range(5):
|
for i in range(5):
|
||||||
allowed, remaining, retry = counter.is_allowed("test-key")
|
allowed, remaining, retry = limiter.is_allowed("test-key")
|
||||||
assert allowed is True
|
assert allowed is True
|
||||||
assert remaining == 4 - i
|
assert remaining == 4 - i
|
||||||
|
|
||||||
def test_blocks_over_limit(self):
|
def test_blocks_over_limit(self):
|
||||||
counter = _SlidingWindowCounter(max_requests=3, window_seconds=60)
|
limiter = InMemorySlidingWindow(max_requests=3, window_seconds=60)
|
||||||
for _ in range(3):
|
for _ in range(3):
|
||||||
counter.is_allowed("test-key")
|
limiter.is_allowed("test-key")
|
||||||
|
|
||||||
allowed, remaining, retry = counter.is_allowed("test-key")
|
allowed, remaining, retry = limiter.is_allowed("test-key")
|
||||||
assert allowed is False
|
assert allowed is False
|
||||||
assert remaining == 0
|
assert remaining == 0
|
||||||
assert retry > 0
|
assert retry > 0
|
||||||
|
|
||||||
def test_separate_keys(self):
|
def test_separate_keys(self):
|
||||||
counter = _SlidingWindowCounter(max_requests=2, window_seconds=60)
|
limiter = InMemorySlidingWindow(max_requests=2, window_seconds=60)
|
||||||
# Fill key-a
|
limiter.is_allowed("key-a")
|
||||||
counter.is_allowed("key-a")
|
limiter.is_allowed("key-a")
|
||||||
counter.is_allowed("key-a")
|
allowed_a, _, _ = limiter.is_allowed("key-a")
|
||||||
allowed_a, _, _ = counter.is_allowed("key-a")
|
|
||||||
assert allowed_a is False
|
assert allowed_a is False
|
||||||
|
|
||||||
# key-b should still be allowed
|
allowed_b, remaining, _ = limiter.is_allowed("key-b")
|
||||||
allowed_b, remaining, _ = counter.is_allowed("key-b")
|
|
||||||
assert allowed_b is True
|
assert allowed_b is True
|
||||||
assert remaining == 1
|
assert remaining == 1
|
||||||
|
|
||||||
|
def test_resets_after_window_expires(self):
|
||||||
|
limiter = InMemorySlidingWindow(max_requests=2, window_seconds=1)
|
||||||
|
for _ in range(2):
|
||||||
|
limiter.is_allowed("test-key")
|
||||||
|
allowed, remaining, _ = limiter.is_allowed("test-key")
|
||||||
|
assert allowed is False
|
||||||
|
|
||||||
|
time.sleep(1.1)
|
||||||
|
allowed, remaining, _ = limiter.is_allowed("test-key")
|
||||||
|
assert allowed is True
|
||||||
|
assert remaining == 1
|
||||||
|
|
||||||
|
|
||||||
|
class TestGetClientIp:
|
||||||
|
def test_x_forwarded_for_single(self):
|
||||||
|
req = MagicMock()
|
||||||
|
req.headers = {"x-forwarded-for": "192.168.1.1"}
|
||||||
|
req.client = None
|
||||||
|
assert _get_client_ip(req) == "192.168.1.1"
|
||||||
|
|
||||||
|
def test_x_forwarded_for_multiple(self):
|
||||||
|
req = MagicMock()
|
||||||
|
req.headers = {"x-forwarded-for": "192.168.1.1, 10.0.0.1, 172.16.0.1"}
|
||||||
|
req.client = None
|
||||||
|
assert _get_client_ip(req) == "192.168.1.1"
|
||||||
|
|
||||||
|
def test_x_forwarded_for_with_port(self):
|
||||||
|
req = MagicMock()
|
||||||
|
req.headers = {"x-forwarded-for": "192.168.1.1:8080"}
|
||||||
|
req.client = None
|
||||||
|
assert _get_client_ip(req) == "192.168.1.1"
|
||||||
|
|
||||||
|
def test_no_forwarded_header(self):
|
||||||
|
req = MagicMock()
|
||||||
|
req.headers = {}
|
||||||
|
req.client.host = "127.0.0.1"
|
||||||
|
assert _get_client_ip(req) == "127.0.0.1"
|
||||||
|
|
||||||
|
def test_no_client(self):
|
||||||
|
req = MagicMock()
|
||||||
|
req.headers = {}
|
||||||
|
req.client = None
|
||||||
|
assert _get_client_ip(req) == "unknown"
|
||||||
|
|
||||||
|
|
||||||
|
class TestGetRateLimitKey:
|
||||||
|
def _make_request(
|
||||||
|
self,
|
||||||
|
path: str = "/purchases",
|
||||||
|
method: str = "GET",
|
||||||
|
auth_header: str = "",
|
||||||
|
headers: dict | None = None,
|
||||||
|
) -> MagicMock:
|
||||||
|
req = MagicMock()
|
||||||
|
req.url.path = path
|
||||||
|
req.method = method
|
||||||
|
req.headers = dict(headers) if headers else {}
|
||||||
|
if auth_header:
|
||||||
|
req.headers["authorization"] = auth_header
|
||||||
|
return req
|
||||||
|
|
||||||
|
def test_public_path_uses_public_limiter(self):
|
||||||
|
req = self._make_request("/public/inflation")
|
||||||
|
key, limiter = _get_rate_limit_key(req)
|
||||||
|
assert key.startswith("ip:")
|
||||||
|
assert limiter.max_requests == settings.rate_limit_requests
|
||||||
|
|
||||||
|
def test_auth_post_path_uses_strict_limiter(self):
|
||||||
|
req = self._make_request("/auth/login", method="POST")
|
||||||
|
key, limiter = _get_rate_limit_key(req)
|
||||||
|
assert key.startswith("ip:")
|
||||||
|
assert limiter.max_requests == settings.rate_limit_auth_requests
|
||||||
|
assert limiter.window_seconds == settings.rate_limit_auth_window_seconds
|
||||||
|
|
||||||
|
def test_auth_get_path_uses_auth_limiter(self):
|
||||||
|
req = self._make_request("/auth/me", method="GET")
|
||||||
|
key, limiter = _get_rate_limit_key(req)
|
||||||
|
assert key.startswith("ip:")
|
||||||
|
assert limiter.max_requests == settings.rate_limit_requests * 5
|
||||||
|
|
||||||
|
def test_authenticated_token_uses_auth_limiter(self):
|
||||||
|
req = self._make_request("/purchases", auth_header="Bearer token123")
|
||||||
|
key, limiter = _get_rate_limit_key(req)
|
||||||
|
assert key.startswith("token:")
|
||||||
|
assert limiter.max_requests == settings.rate_limit_requests * 5
|
||||||
|
|
||||||
|
def test_distinct_tokens_produce_distinct_keys(self):
|
||||||
|
req1 = self._make_request("/purchases", auth_header="Bearer token_alpha_12345")
|
||||||
|
req2 = self._make_request("/purchases", auth_header="Bearer token_beta_67890")
|
||||||
|
key1, _ = _get_rate_limit_key(req1)
|
||||||
|
key2, _ = _get_rate_limit_key(req2)
|
||||||
|
assert key1 != key2
|
||||||
|
|
||||||
|
def test_same_token_produces_same_key(self):
|
||||||
|
req1 = self._make_request("/purchases", auth_header="Bearer same_token_value_abc")
|
||||||
|
req2 = self._make_request("/purchases", auth_header="Bearer same_token_value_abc")
|
||||||
|
key1, _ = _get_rate_limit_key(req1)
|
||||||
|
key2, _ = _get_rate_limit_key(req2)
|
||||||
|
assert key1 == key2
|
||||||
|
|
||||||
|
def test_key_does_not_contain_raw_token_suffix(self):
|
||||||
|
raw_token = "my_secret_jwt_token_xyz"
|
||||||
|
req = self._make_request("/purchases", auth_header=f"Bearer {raw_token}")
|
||||||
|
key, _ = _get_rate_limit_key(req)
|
||||||
|
assert raw_token[-16:] not in key
|
||||||
|
assert raw_token not in key
|
||||||
|
|
||||||
|
|
||||||
|
class TestRedisSlidingWindowFallback:
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_fallback_on_redis_connection_error(self):
|
||||||
|
mock_redis = AsyncMock()
|
||||||
|
mock_redis.pipeline.return_value = AsyncMock()
|
||||||
|
pipe_mock = AsyncMock()
|
||||||
|
pipe_mock.execute.side_effect = Exception("Connection refused")
|
||||||
|
mock_redis.pipeline.return_value = pipe_mock
|
||||||
|
|
||||||
|
limiter = RedisSlidingWindow(mock_redis, max_requests=5, window_seconds=60)
|
||||||
|
allowed, remaining, retry = await limiter.is_allowed("test-key")
|
||||||
|
assert allowed is True
|
||||||
|
assert remaining == 4
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_fallback_on_redis_error_during_pipeline(self):
|
||||||
|
mock_redis = AsyncMock()
|
||||||
|
pipe_mock = AsyncMock()
|
||||||
|
pipe_mock.execute.side_effect = Exception("Redis error")
|
||||||
|
mock_redis.pipeline.return_value = pipe_mock
|
||||||
|
|
||||||
|
limiter = RedisSlidingWindow(mock_redis, max_requests=3, window_seconds=60)
|
||||||
|
allowed, remaining, retry = await limiter.is_allowed("test-key")
|
||||||
|
assert allowed is True
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_rate_limit_returns_429(client):
|
async def test_rate_limit_returns_429(client):
|
||||||
"""Public endpoint should return 429 after limit exceeded."""
|
|
||||||
# The default limit is 60/min — we won't hit it in normal tests,
|
|
||||||
# but we verify the middleware adds rate limit headers.
|
|
||||||
resp = await client.get("/public/inflation")
|
resp = await client.get("/public/inflation")
|
||||||
assert "x-ratelimit-limit" in resp.headers
|
assert "x-ratelimit-limit" in resp.headers
|
||||||
assert "x-ratelimit-remaining" in resp.headers
|
assert "x-ratelimit-remaining" in resp.headers
|
||||||
@@ -51,36 +186,6 @@ async def test_rate_limit_returns_429(client):
|
|||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_health_skips_rate_limit(client):
|
async def test_health_skips_rate_limit(client):
|
||||||
"""Health endpoint should not have rate limit headers."""
|
|
||||||
resp = await client.get("/health")
|
resp = await client.get("/health")
|
||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
assert "x-ratelimit-limit" not in resp.headers
|
assert "x-ratelimit-limit" not in resp.headers
|
||||||
|
|
||||||
|
|
||||||
class TestGetRateLimitKey:
|
|
||||||
def _make_request(self, auth_header: str = "") -> MagicMock:
|
|
||||||
req = MagicMock()
|
|
||||||
req.url.path = "/purchases"
|
|
||||||
req.headers = {"authorization": auth_header} if auth_header else {}
|
|
||||||
return req
|
|
||||||
|
|
||||||
def test_distinct_tokens_produce_distinct_keys(self):
|
|
||||||
req1 = self._make_request("Bearer token_alpha_12345")
|
|
||||||
req2 = self._make_request("Bearer token_beta_67890")
|
|
||||||
key1, _ = _get_rate_limit_key(req1)
|
|
||||||
key2, _ = _get_rate_limit_key(req2)
|
|
||||||
assert key1 != key2
|
|
||||||
|
|
||||||
def test_same_token_produces_same_key(self):
|
|
||||||
req1 = self._make_request("Bearer same_token_value_abc")
|
|
||||||
req2 = self._make_request("Bearer same_token_value_abc")
|
|
||||||
key1, _ = _get_rate_limit_key(req1)
|
|
||||||
key2, _ = _get_rate_limit_key(req2)
|
|
||||||
assert key1 == key2
|
|
||||||
|
|
||||||
def test_key_does_not_contain_raw_token_suffix(self):
|
|
||||||
raw_token = "my_secret_jwt_token_xyz"
|
|
||||||
req = self._make_request(f"Bearer {raw_token}")
|
|
||||||
key, _ = _get_rate_limit_key(req)
|
|
||||||
assert raw_token[-16:] not in key
|
|
||||||
assert raw_token not in key
|
|
||||||
|
|||||||
@@ -9,3 +9,7 @@ DATABASE_URL=postgresql://cartsnitch:cartsnitch@localhost:5432/cartsnitch
|
|||||||
|
|
||||||
# Port the auth service listens on
|
# Port the auth service listens on
|
||||||
PORT=3001
|
PORT=3001
|
||||||
|
|
||||||
|
# Resend email provider for transactional email
|
||||||
|
RESEND_API_KEY=re_your_api_key_here
|
||||||
|
FROM_EMAIL=CartSnitch <noreply@cartsnitch.com>
|
||||||
|
|||||||
Generated
+74
-1
@@ -10,7 +10,8 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"bcrypt": "^6.0.0",
|
"bcrypt": "^6.0.0",
|
||||||
"better-auth": "^1.2.0",
|
"better-auth": "^1.2.0",
|
||||||
"pg": "^8.13.0"
|
"pg": "^8.13.0",
|
||||||
|
"resend": "^6.11.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/bcrypt": "^6.0.0",
|
"@types/bcrypt": "^6.0.0",
|
||||||
@@ -633,6 +634,12 @@
|
|||||||
"node": ">=14"
|
"node": ">=14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@stablelib/base64": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@standard-schema/spec": {
|
"node_modules/@standard-schema/spec": {
|
||||||
"version": "1.1.0",
|
"version": "1.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
|
||||||
@@ -858,6 +865,12 @@
|
|||||||
"@esbuild/win32-x64": "0.27.4"
|
"@esbuild/win32-x64": "0.27.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/fast-sha256": {
|
||||||
|
"version": "1.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",
|
||||||
|
"integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==",
|
||||||
|
"license": "Unlicense"
|
||||||
|
},
|
||||||
"node_modules/fsevents": {
|
"node_modules/fsevents": {
|
||||||
"version": "2.3.3",
|
"version": "2.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
||||||
@@ -1028,6 +1041,12 @@
|
|||||||
"split2": "^4.1.0"
|
"split2": "^4.1.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/postal-mime": {
|
||||||
|
"version": "2.7.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/postal-mime/-/postal-mime-2.7.4.tgz",
|
||||||
|
"integrity": "sha512-0WdnFQYUrPGGTFu1uOqD2s7omwua8xaeYGdO6rb88oD5yJ/4pPHDA4sdWqfD8wQVfCny563n/HQS7zTFft+f/g==",
|
||||||
|
"license": "MIT-0"
|
||||||
|
},
|
||||||
"node_modules/postgres-array": {
|
"node_modules/postgres-array": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
|
||||||
@@ -1067,6 +1086,27 @@
|
|||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/resend": {
|
||||||
|
"version": "6.11.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/resend/-/resend-6.11.0.tgz",
|
||||||
|
"integrity": "sha512-S9gxOccfwc+E6Cr3q28Gu8NkiIjYlYPlj9rqk4zkIuzlEoh8sWu/IvJSg7U7t+o3g0Ov2IOCzcneUaCi/M/WdQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"postal-mime": "2.7.4",
|
||||||
|
"svix": "1.90.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@react-email/render": "*"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@react-email/render": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/resolve-pkg-maps": {
|
"node_modules/resolve-pkg-maps": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",
|
||||||
@@ -1098,6 +1138,26 @@
|
|||||||
"node": ">= 10.x"
|
"node": ">= 10.x"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/standardwebhooks": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.0.0.tgz",
|
||||||
|
"integrity": "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@stablelib/base64": "^1.0.0",
|
||||||
|
"fast-sha256": "^1.3.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/svix": {
|
||||||
|
"version": "1.90.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/svix/-/svix-1.90.0.tgz",
|
||||||
|
"integrity": "sha512-ljkZuyy2+IBEoESkIpn8sLM+sxJHQcPxlZFxU+nVDhltNfUMisMBzWX/UR8SjEnzoI28ZjCzMbmYAPwSTucoMw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"standardwebhooks": "1.0.0",
|
||||||
|
"uuid": "^10.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/tsx": {
|
"node_modules/tsx": {
|
||||||
"version": "4.21.0",
|
"version": "4.21.0",
|
||||||
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz",
|
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz",
|
||||||
@@ -1139,6 +1199,19 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/uuid": {
|
||||||
|
"version": "10.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz",
|
||||||
|
"integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==",
|
||||||
|
"funding": [
|
||||||
|
"https://github.com/sponsors/broofa",
|
||||||
|
"https://github.com/sponsors/ctavan"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"bin": {
|
||||||
|
"uuid": "dist/bin/uuid"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/xtend": {
|
"node_modules/xtend": {
|
||||||
"version": "4.0.2",
|
"version": "4.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
||||||
|
|||||||
+3
-2
@@ -10,14 +10,15 @@
|
|||||||
"generate": "npx @better-auth/cli generate"
|
"generate": "npx @better-auth/cli generate"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"bcrypt": "^6.0.0",
|
||||||
"better-auth": "^1.2.0",
|
"better-auth": "^1.2.0",
|
||||||
"pg": "^8.13.0",
|
"pg": "^8.13.0",
|
||||||
"bcrypt": "^6.0.0"
|
"resend": "^6.11.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/bcrypt": "^6.0.0",
|
||||||
"@types/node": "^22.0.0",
|
"@types/node": "^22.0.0",
|
||||||
"@types/pg": "^8.11.0",
|
"@types/pg": "^8.11.0",
|
||||||
"@types/bcrypt": "^6.0.0",
|
|
||||||
"tsx": "^4.19.0",
|
"tsx": "^4.19.0",
|
||||||
"typescript": "^5.7.0"
|
"typescript": "^5.7.0"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { betterAuth } from "better-auth";
|
import { betterAuth } from "better-auth";
|
||||||
import bcrypt from "bcrypt";
|
import bcrypt from "bcrypt";
|
||||||
import pg from "pg";
|
import pg from "pg";
|
||||||
|
import { Resend } from "resend";
|
||||||
|
|
||||||
const { Pool } = pg;
|
const { Pool } = pg;
|
||||||
|
|
||||||
@@ -21,6 +22,9 @@ export const pool = new Pool({
|
|||||||
connectionString: databaseUrl ?? "postgresql://cartsnitch:cartsnitch@localhost:5432/cartsnitch",
|
connectionString: databaseUrl ?? "postgresql://cartsnitch:cartsnitch@localhost:5432/cartsnitch",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const resend = new Resend(process.env.RESEND_API_KEY);
|
||||||
|
const fromEmail = process.env.FROM_EMAIL || "CartSnitch <noreply@cartsnitch.com>";
|
||||||
|
|
||||||
export const auth = betterAuth({
|
export const auth = betterAuth({
|
||||||
database: pool,
|
database: pool,
|
||||||
basePath: "/auth",
|
basePath: "/auth",
|
||||||
@@ -41,6 +45,19 @@ export const auth = betterAuth({
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
|
emailVerification: {
|
||||||
|
sendOnSignUp: true,
|
||||||
|
autoSignInAfterVerification: true,
|
||||||
|
sendVerificationEmail: async ({ user, url }) => {
|
||||||
|
await resend.emails.send({
|
||||||
|
from: fromEmail,
|
||||||
|
to: user.email,
|
||||||
|
subject: "Verify your CartSnitch email",
|
||||||
|
html: `<p>Hi ${user.name || ""},</p><p>Click the link below to verify your email address:</p><p><a href="${url}">Verify Email</a></p><p>This link expires in 1 hour.</p><p>— CartSnitch</p>`,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
session: {
|
session: {
|
||||||
modelName: "sessions",
|
modelName: "sessions",
|
||||||
fields: {
|
fields: {
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ test.describe('J1: Registration and Login', () => {
|
|||||||
await page.fill('[placeholder="Password (min. 8 characters)"]', 'TestPass123!');
|
await page.fill('[placeholder="Password (min. 8 characters)"]', 'TestPass123!');
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
|
|
||||||
// With VITE_MOCK_AUTH=true the app navigates to "/" on success
|
|
||||||
await expect(page).toHaveURL('http://localhost:5173/');
|
await expect(page).toHaveURL('http://localhost:5173/');
|
||||||
await expect(page.getByRole('heading', { name: /cart/i })).toBeVisible();
|
await expect(page.getByRole('heading', { name: /cart/i })).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ export default defineConfig({
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
webServer: {
|
webServer: {
|
||||||
command: 'VITE_MOCK_AUTH=true npm run dev',
|
command: 'npm run dev',
|
||||||
url: 'http://localhost:5173',
|
url: 'http://localhost:5173',
|
||||||
reuseExistingServer: !process.env.CI,
|
reuseExistingServer: !process.env.CI,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import { AccountLinking } from './pages/AccountLinking.tsx'
|
|||||||
import { Login } from './pages/Login.tsx'
|
import { Login } from './pages/Login.tsx'
|
||||||
import { Register } from './pages/Register.tsx'
|
import { Register } from './pages/Register.tsx'
|
||||||
import { ForgotPassword } from './pages/ForgotPassword.tsx'
|
import { ForgotPassword } from './pages/ForgotPassword.tsx'
|
||||||
|
import { VerifyEmail } from './pages/VerifyEmail.tsx'
|
||||||
|
|
||||||
const queryClient = new QueryClient({
|
const queryClient = new QueryClient({
|
||||||
defaultOptions: {
|
defaultOptions: {
|
||||||
@@ -47,6 +48,7 @@ export default function App() {
|
|||||||
<Route path="login" element={<Login />} />
|
<Route path="login" element={<Login />} />
|
||||||
<Route path="register" element={<Register />} />
|
<Route path="register" element={<Register />} />
|
||||||
<Route path="forgot-password" element={<ForgotPassword />} />
|
<Route path="forgot-password" element={<ForgotPassword />} />
|
||||||
|
<Route path="verify-email" element={<VerifyEmail />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
|
|||||||
@@ -1,25 +1,8 @@
|
|||||||
import { useEffect } from 'react'
|
|
||||||
import { Navigate, Outlet } from 'react-router-dom'
|
import { Navigate, Outlet } from 'react-router-dom'
|
||||||
import { authClient } from '../lib/auth-client.ts'
|
import { authClient } from '../lib/auth-client.ts'
|
||||||
import { useAuthStore } from '../stores/auth.ts'
|
|
||||||
|
|
||||||
export function ProtectedRoute() {
|
export function ProtectedRoute() {
|
||||||
const isMockAuth = import.meta.env.VITE_MOCK_AUTH === 'true'
|
|
||||||
const { data: session, isPending } = authClient.useSession()
|
const { data: session, isPending } = authClient.useSession()
|
||||||
const isAuthenticated = useAuthStore((s) => s.isAuthenticated)
|
|
||||||
const setAuthenticated = useAuthStore((s) => s.setAuthenticated)
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!isMockAuth) {
|
|
||||||
setAuthenticated(!!session)
|
|
||||||
}
|
|
||||||
}, [session, setAuthenticated, isMockAuth])
|
|
||||||
|
|
||||||
// In mock auth mode, rely on Zustand store (set by Login/Register pages)
|
|
||||||
if (isMockAuth) {
|
|
||||||
if (!isAuthenticated) return <Navigate to="/login" replace />
|
|
||||||
return <Outlet />
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isPending) {
|
if (isPending) {
|
||||||
return (
|
return (
|
||||||
|
|||||||
+1
-8
@@ -1,7 +1,6 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { Link, useNavigate } from 'react-router-dom'
|
import { Link, useNavigate } from 'react-router-dom'
|
||||||
import { authClient } from '../lib/auth-client.ts'
|
import { authClient } from '../lib/auth-client.ts'
|
||||||
import { useAuthStore } from '../stores/auth.ts'
|
|
||||||
|
|
||||||
export function Login() {
|
export function Login() {
|
||||||
const [email, setEmail] = useState('')
|
const [email, setEmail] = useState('')
|
||||||
@@ -9,7 +8,6 @@ export function Login() {
|
|||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
const [loading, setLoading] = useState(false)
|
const [loading, setLoading] = useState(false)
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const setAuthenticated = useAuthStore((s) => s.setAuthenticated)
|
|
||||||
|
|
||||||
async function handleSubmit(e: React.FormEvent) {
|
async function handleSubmit(e: React.FormEvent) {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
@@ -40,12 +38,7 @@ export function Login() {
|
|||||||
setError('Sign in failed. Please try again.')
|
setError('Sign in failed. Please try again.')
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
if (import.meta.env.VITE_MOCK_AUTH === 'true') {
|
setError('Invalid email or password. Please try again.')
|
||||||
setAuthenticated(true)
|
|
||||||
navigate('/')
|
|
||||||
} else {
|
|
||||||
setError('Invalid email or password. Please try again.')
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
|
|||||||
+48
-17
@@ -1,7 +1,6 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { Link, useNavigate } from 'react-router-dom'
|
import { Link, useNavigate } from 'react-router-dom'
|
||||||
import { authClient } from '../lib/auth-client.ts'
|
import { authClient } from '../lib/auth-client.ts'
|
||||||
import { useAuthStore } from '../stores/auth.ts'
|
|
||||||
|
|
||||||
export function Register() {
|
export function Register() {
|
||||||
const [name, setName] = useState('')
|
const [name, setName] = useState('')
|
||||||
@@ -9,8 +8,10 @@ export function Register() {
|
|||||||
const [password, setPassword] = useState('')
|
const [password, setPassword] = useState('')
|
||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
const [loading, setLoading] = useState(false)
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [registrationComplete, setRegistrationComplete] = useState(false)
|
||||||
|
const [resendLoading, setResendLoading] = useState(false)
|
||||||
|
const [resendMessage, setResendMessage] = useState('')
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const setAuthenticated = useAuthStore((s) => s.setAuthenticated)
|
|
||||||
|
|
||||||
async function handleSubmit(e: React.FormEvent) {
|
async function handleSubmit(e: React.FormEvent) {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
@@ -38,27 +39,57 @@ export function Register() {
|
|||||||
throw new Error(authError.message ?? 'Registration failed')
|
throw new Error(authError.message ?? 'Registration failed')
|
||||||
}
|
}
|
||||||
|
|
||||||
// After successful signUp, force a session fetch to confirm the cookie is set
|
setRegistrationComplete(true)
|
||||||
// before navigating to the protected route
|
|
||||||
const sessionResult = await authClient.getSession()
|
|
||||||
if (sessionResult.data) {
|
|
||||||
navigate('/')
|
|
||||||
} else {
|
|
||||||
// Session not established — show success message and link to login
|
|
||||||
setError('Account created! Please sign in.')
|
|
||||||
}
|
|
||||||
} catch {
|
} catch {
|
||||||
if (import.meta.env.VITE_MOCK_AUTH === 'true') {
|
setError('Registration failed. Please try again.')
|
||||||
setAuthenticated(true)
|
|
||||||
navigate('/')
|
|
||||||
} else {
|
|
||||||
setError('Registration failed. Please try again.')
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function handleResendVerification() {
|
||||||
|
setResendLoading(true)
|
||||||
|
setResendMessage('')
|
||||||
|
try {
|
||||||
|
const { error } = await authClient.sendVerificationEmail({ email })
|
||||||
|
if (error) {
|
||||||
|
setResendMessage('Failed to resend. Please try again.')
|
||||||
|
} else {
|
||||||
|
setResendMessage('Verification email sent!')
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setResendLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (registrationComplete) {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen flex-col items-center justify-center px-4">
|
||||||
|
<h1 className="mb-2 text-3xl font-bold text-gray-900">Check your email</h1>
|
||||||
|
<p className="mb-8 text-sm text-gray-500">
|
||||||
|
We sent a verification link to {email}. Click it to activate your account.
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleResendVerification}
|
||||||
|
disabled={resendLoading}
|
||||||
|
className="min-h-12 rounded-xl bg-brand-blue px-6 py-3 text-base font-medium text-white active:bg-brand-blue/90 disabled:opacity-60"
|
||||||
|
>
|
||||||
|
{resendLoading ? 'Sending...' : 'Resend email'}
|
||||||
|
</button>
|
||||||
|
{resendMessage && (
|
||||||
|
<p className="mt-4 text-sm text-gray-500">{resendMessage}</p>
|
||||||
|
)}
|
||||||
|
<p className="mt-6 text-sm text-gray-500">
|
||||||
|
Already have an account?{' '}
|
||||||
|
<Link to="/login" className="text-brand-blue">
|
||||||
|
Sign in
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-screen flex-col items-center justify-center px-4">
|
<div className="flex min-h-screen flex-col items-center justify-center px-4">
|
||||||
<h1 className="mb-2 text-3xl font-bold text-gray-900">Create Account</h1>
|
<h1 className="mb-2 text-3xl font-bold text-gray-900">Create Account</h1>
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { useNavigate, useSearchParams } from "react-router-dom";
|
||||||
|
import { authClient } from "../lib/auth-client.ts";
|
||||||
|
|
||||||
|
export function VerifyEmail() {
|
||||||
|
const [searchParams] = useSearchParams();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const [status, setStatus] = useState<"verifying" | "success" | "error">("verifying");
|
||||||
|
const [resendEmail, setResendEmail] = useState("");
|
||||||
|
const [showResend, setShowResend] = useState(false);
|
||||||
|
const [resending, setResending] = useState(false);
|
||||||
|
const [resendMessage, setResendMessage] = useState("");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const token = searchParams.get("token");
|
||||||
|
const callbackURL = searchParams.get("callbackURL") || "/";
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
setStatus("error");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
authClient.verifyEmail({ query: { token } })
|
||||||
|
.then(() => {
|
||||||
|
setStatus("success");
|
||||||
|
setTimeout(() => {
|
||||||
|
navigate(callbackURL);
|
||||||
|
}, 2000);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
setStatus("error");
|
||||||
|
});
|
||||||
|
}, [searchParams, navigate]);
|
||||||
|
|
||||||
|
async function handleResend() {
|
||||||
|
if (!resendEmail) {
|
||||||
|
setResendMessage("Please enter your email address.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setResending(true);
|
||||||
|
setResendMessage("");
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { error } = await authClient.sendVerificationEmail({ email: resendEmail });
|
||||||
|
if (error) {
|
||||||
|
setResendMessage("Failed to resend. Please try again.");
|
||||||
|
} else {
|
||||||
|
setResendMessage("Verification email sent!");
|
||||||
|
setShowResend(false);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setResending(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen flex-col items-center justify-center px-4">
|
||||||
|
{status === "verifying" && (
|
||||||
|
<>
|
||||||
|
<div className="mb-4 h-8 w-8 animate-spin rounded-full border-4 border-gray-200 border-t-brand-blue" />
|
||||||
|
<h1 className="mb-2 text-2xl font-bold text-gray-900">Verifying your email...</h1>
|
||||||
|
<p className="text-sm text-gray-500">Please wait while we verify your email address.</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{status === "success" && (
|
||||||
|
<>
|
||||||
|
<h1 className="mb-2 text-2xl font-bold text-gray-900">Email verified!</h1>
|
||||||
|
<p className="text-sm text-gray-500">Redirecting you shortly...</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{status === "error" && (
|
||||||
|
<>
|
||||||
|
<h1 className="mb-2 text-2xl font-bold text-gray-900">Verification failed</h1>
|
||||||
|
<p className="mb-6 text-sm text-gray-500">The verification link may have expired or is invalid.</p>
|
||||||
|
|
||||||
|
{!showResend ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowResend(true)}
|
||||||
|
className="min-h-12 rounded-xl bg-brand-blue px-6 py-3 text-base font-medium text-white active:bg-brand-blue/90"
|
||||||
|
>
|
||||||
|
Resend verification email
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<div className="w-full max-w-sm space-y-4">
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
placeholder="Your email address"
|
||||||
|
value={resendEmail}
|
||||||
|
onChange={(e) => setResendEmail(e.target.value)}
|
||||||
|
className="min-h-12 w-full rounded-xl border border-gray-200 px-4 text-base focus:border-brand-blue focus:outline-none focus:ring-1 focus:ring-brand-blue"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleResend}
|
||||||
|
disabled={resending}
|
||||||
|
className="min-h-12 w-full rounded-xl bg-brand-blue px-4 py-3 text-base font-medium text-white active:bg-brand-blue/90 disabled:opacity-60"
|
||||||
|
>
|
||||||
|
{resending ? "Sending..." : "Send verification email"}
|
||||||
|
</button>
|
||||||
|
{resendMessage && (
|
||||||
|
<p className="text-sm text-gray-500">{resendMessage}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user