Files
fastapi-users/tests/test_router_auth.py
François Voron 373157c284 Finalize user activation feature (#439)
* Add routes for user activation (#403)

* Add routes for user activation

Generate a token after creating the user in register route, passing to `activation_callback`, if `activation_callback` supplied
Create new `/activate` route that will verify the token and activate the user
Add new error codes to `fastapi_users/router/common.py`
Update documentation
Add tests

Co-authored-by: Mark Todd <markpeter.todd@hotmail.co.uk>

* Rework routes for user activation

* Separate verification logic and token generation into `/fastapi_users/router/verify.py`, with per-route callbacks for custom behaviour

* Return register router to original state

* Added `is_verified` property to user models

* Added `requires_verification` argument to `get_users_router`and `get_auth_router`

* Additional dependencies added for verification in `fastapi_users/authentication/__init__.py`

* Update tests for new behaviour

* Update `README.md` to describe a workaround for possible problems during testing, by exceeding ulimit file descriptor limit

Co-authored-by: Mark Todd <markpeter.todd@hotmail.co.uk>

* Restored docs to original state.

* All other modifications reqested added

Kebab-case on request-verify-token
SECRET now used as test string
Other minor changes

Co-authored-by: Mark Todd <markpeter.todd@hotmail.co.uk>

* Embed token in body in verify route

* Reorganize checks in verify route and add unit test

* Ignore coverage on Protocol classes

* Tweak verify_user function to take full user in parameter

* Improve unit tests structure regarding parametrized test client

* Make after_verification_request optional to be more consistent with other routers

* Tweak status codes on verify routes

* Write documentation for verification feature

* Add not released warning on verify docs

Co-authored-by: Edd Salkield <edd@salkield.uk>
Co-authored-by: Mark Todd <markpeter.todd@hotmail.co.uk>
2021-01-12 10:44:42 +01:00

202 lines
6.7 KiB
Python

from typing import Any, AsyncGenerator, Dict, Tuple, cast
import httpx
import pytest
from fastapi import FastAPI, status
from fastapi_users.authentication import Authenticator
from fastapi_users.router import ErrorCode, get_auth_router
from tests.conftest import MockAuthentication, UserDB
@pytest.fixture
def app_factory(mock_user_db, mock_authentication):
def _app_factory(requires_verification: bool) -> FastAPI:
mock_authentication_bis = MockAuthentication(name="mock-bis")
authenticator = Authenticator(
[mock_authentication, mock_authentication_bis], mock_user_db
)
mock_auth_router = get_auth_router(
mock_authentication,
mock_user_db,
authenticator,
requires_verification=requires_verification,
)
mock_bis_auth_router = get_auth_router(
mock_authentication_bis,
mock_user_db,
authenticator,
requires_verification=requires_verification,
)
app = FastAPI()
app.include_router(mock_auth_router, prefix="/mock")
app.include_router(mock_bis_auth_router, prefix="/mock-bis")
return app
return _app_factory
@pytest.fixture(
params=[True, False], ids=["required_verification", "not_required_verification"]
)
@pytest.mark.asyncio
async def test_app_client(
request, get_test_client, app_factory
) -> AsyncGenerator[Tuple[httpx.AsyncClient, bool], None]:
requires_verification = request.param
app = app_factory(requires_verification)
async for client in get_test_client(app):
yield client, requires_verification
@pytest.mark.router
@pytest.mark.parametrize("path", ["/mock/login", "/mock-bis/login"])
@pytest.mark.asyncio
class TestLogin:
async def test_empty_body(
self,
path,
test_app_client: Tuple[httpx.AsyncClient, bool],
):
client, _ = test_app_client
response = await client.post(path, data={})
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
async def test_missing_username(
self,
path,
test_app_client: Tuple[httpx.AsyncClient, bool],
):
client, _ = test_app_client
data = {"password": "guinevere"}
response = await client.post(path, data=data)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
async def test_missing_password(
self,
path,
test_app_client: Tuple[httpx.AsyncClient, bool],
):
client, _ = test_app_client
data = {"username": "king.arthur@camelot.bt"}
response = await client.post(path, data=data)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
async def test_not_existing_user(
self,
path,
test_app_client: Tuple[httpx.AsyncClient, bool],
):
client, _ = test_app_client
data = {"username": "lancelot@camelot.bt", "password": "guinevere"}
response = await client.post(path, data=data)
assert response.status_code == status.HTTP_400_BAD_REQUEST
data = cast(Dict[str, Any], response.json())
assert data["detail"] == ErrorCode.LOGIN_BAD_CREDENTIALS
async def test_wrong_password(
self,
path,
test_app_client: Tuple[httpx.AsyncClient, bool],
):
client, _ = test_app_client
data = {"username": "king.arthur@camelot.bt", "password": "percival"}
response = await client.post(path, data=data)
assert response.status_code == status.HTTP_400_BAD_REQUEST
data = cast(Dict[str, Any], response.json())
assert data["detail"] == ErrorCode.LOGIN_BAD_CREDENTIALS
@pytest.mark.parametrize(
"email", ["king.arthur@camelot.bt", "King.Arthur@camelot.bt"]
)
async def test_valid_credentials_unverified(
self,
path,
email,
test_app_client: Tuple[httpx.AsyncClient, bool],
user: UserDB,
):
client, requires_verification = test_app_client
data = {"username": email, "password": "guinevere"}
response = await client.post(path, data=data)
if requires_verification:
assert response.status_code == status.HTTP_400_BAD_REQUEST
data = cast(Dict[str, Any], response.json())
assert data["detail"] == ErrorCode.LOGIN_USER_NOT_VERIFIED
else:
assert response.status_code == status.HTTP_200_OK
assert response.json() == {"token": str(user.id)}
@pytest.mark.parametrize("email", ["lake.lady@camelot.bt", "Lake.Lady@camelot.bt"])
async def test_valid_credentials_verified(
self,
path,
email,
test_app_client: Tuple[httpx.AsyncClient, bool],
verified_user: UserDB,
):
client, _ = test_app_client
data = {"username": email, "password": "excalibur"}
response = await client.post(path, data=data)
assert response.status_code == status.HTTP_200_OK
assert response.json() == {"token": str(verified_user.id)}
async def test_inactive_user(
self,
path,
test_app_client: Tuple[httpx.AsyncClient, bool],
):
client, _ = test_app_client
data = {"username": "percival@camelot.bt", "password": "angharad"}
response = await client.post(path, data=data)
assert response.status_code == status.HTTP_400_BAD_REQUEST
data = cast(Dict[str, Any], response.json())
assert data["detail"] == ErrorCode.LOGIN_BAD_CREDENTIALS
@pytest.mark.router
@pytest.mark.parametrize("path", ["/mock/logout", "/mock-bis/logout"])
@pytest.mark.asyncio
class TestLogout:
async def test_missing_token(
self,
path,
test_app_client: Tuple[httpx.AsyncClient, bool],
):
client, _ = test_app_client
response = await client.post(path)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
async def test_valid_credentials_unverified(
self,
mocker,
path,
test_app_client: Tuple[httpx.AsyncClient, bool],
user: UserDB,
):
client, requires_verification = test_app_client
response = await client.post(
path, headers={"Authorization": f"Bearer {user.id}"}
)
if requires_verification:
assert response.status_code == status.HTTP_401_UNAUTHORIZED
else:
assert response.status_code == status.HTTP_200_OK
async def test_valid_credentials_verified(
self,
mocker,
path,
test_app_client: Tuple[httpx.AsyncClient, bool],
verified_user: UserDB,
):
client, _ = test_app_client
response = await client.post(
path, headers={"Authorization": f"Bearer {verified_user.id}"}
)
assert response.status_code == status.HTTP_200_OK