Files

54 lines
2.0 KiB
Python

async def _token(client, email, password="secret123"):
resp = await client.post(
"/api/auth/login", data={"username": email, "password": password}
)
assert resp.status_code == 200, resp.text
return resp.json()["access_token"]
async def test_reader_can_list_but_not_create(client, seeded, make_user):
# User with only the "user" role (grants users:read).
await make_user("reader@example.com", role_ids=[seeded["roles"]["user"].id])
token = await _token(client, "reader@example.com")
headers = {"Authorization": f"Bearer {token}"}
assert (await client.get("/api/users", headers=headers)).status_code == 200
resp = await client.post(
"/api/users",
json={"email": "new@example.com", "password": "secret123"},
headers=headers,
)
assert resp.status_code == 403
async def test_superuser_bypasses_permissions(client, seeded, make_user):
await make_user("root@example.com", is_superuser=True)
headers = {"Authorization": f"Bearer {await _token(client, 'root@example.com')}"}
resp = await client.post(
"/api/users",
json={"email": "created@example.com", "password": "secret123"},
headers=headers,
)
assert resp.status_code == 201, resp.text
# Superuser can also manage roles.
assert (await client.get("/api/roles", headers=headers)).status_code == 200
async def test_no_role_user_is_forbidden(client, seeded, make_user):
await make_user("plain@example.com") # no roles, not superuser
headers = {"Authorization": f"Bearer {await _token(client, 'plain@example.com')}"}
assert (await client.get("/api/users", headers=headers)).status_code == 403
async def test_registered_user_gets_default_role(client, seeded):
await client.post(
"/api/auth/register",
json={"email": "fresh@example.com", "password": "secret123"},
)
headers = {"Authorization": f"Bearer {await _token(client, 'fresh@example.com')}"}
me = (await client.get("/api/users/me", headers=headers)).json()
assert [r["name"] for r in me["roles"]] == ["user"]