Skip to content

Commit

Permalink
all tests work again
Browse files Browse the repository at this point in the history
  • Loading branch information
mariusandra committed Dec 25, 2024
1 parent 4beacfc commit ba2672e
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 13 deletions.
2 changes: 1 addition & 1 deletion backend/app/api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ async def login(request: Request, form_data: OAuth2PasswordRequestForm = Depends
email = form_data.username
password = form_data.password
ip = request.client.host
key = f"login_attempts:{ip}"
key = f"login_attempts:{ip}:{email}"
if config.TEST:
key += f":{config.INSTANCE_ID}"
attempts = (await redis.get(key)) or '0'
Expand Down
19 changes: 7 additions & 12 deletions backend/app/api/tests/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,22 +42,21 @@ async def test_login_unknown_email(async_client):


@pytest.mark.asyncio
async def test_login_too_many_attempts(no_auth_client, redis):
async def test_login_too_many_attempts(no_auth_client, redis, db):
"""
Test that after too many failed login attempts, we get 429 Too Many Requests.
The code sets the limit to 10 attempts.
"""
ip = "testclient" # we can rely on starlette's request.client.host
key = f"login_attempts:{ip}"

# Just in case, reset the Redis key for attempts
await redis.delete(key)
user = User(email="[email protected]")
user.set_password("testpassword")
db.add(user)
db.commit()

login_data = {"username": "test@example.com", "password": "wrongpassword"}
login_data = {"username": "toomany@example.com", "password": "wrongpassword"}
# Make 11 attempts
for i in range(11):
resp = await no_auth_client.post("/api/login", data=login_data)
if i < 10:
if i <= 10:
# first 10 attempts => 401
assert resp.status_code == HTTP_401_UNAUTHORIZED, f"Expected 401 on attempt {i+1}, got {resp.status_code}"
else:
Expand All @@ -77,20 +76,16 @@ async def test_signup_first_user(no_auth_client, db: Session):
Test that signing up when no user exists will succeed.
We'll delete all existing users first to ensure DB is empty.
"""
print("!")
db.query(User).delete()
db.commit()
print("!")

signup_data = {
"email": "[email protected]",
"password": "newpassword",
"password2": "newpassword",
"newsletter": False
}
print("!")
response = await no_auth_client.post("/api/signup", json=signup_data)
print("!")
assert response.status_code == 200, f"Expected 200, got {response.status_code}"
json_data = response.json()
# Should contain success, access_token, token_type
Expand Down

0 comments on commit ba2672e

Please sign in to comment.