#!/usr/bin/env python3 import base64 import json import urllib.error import urllib.request import uuid BASE_URL = "http://localhost:8080" PASSWORD = "correct-password-123" def call( method: str, path: str, body: dict | None = None, headers: dict[str, str] | None = None, ) -> tuple[int, dict | None, dict]: request_headers = dict(headers or {}) data = None if body is not None: data = json.dumps(body).encode("utf-8") request_headers["Content-Type"] = "application/json" request = urllib.request.Request( BASE_URL + path, data=data, headers=request_headers, method=method, ) try: with urllib.request.urlopen(request, timeout=10) as response: raw = response.read() response_body = json.loads(raw) if raw else None return response.status, response_body, dict(response.headers) except urllib.error.HTTPError as error: raw = error.read() response_body = json.loads(raw) if raw else None return error.code, response_body, dict(error.headers) def basic_header(username: str, password: str) -> str: credentials = f"{username}:{password}".encode("utf-8") encoded = base64.b64encode(credentials).decode("ascii") return f"Basic {encoded}" def main() -> None: username = "auth_" + uuid.uuid4().hex[:16] # 1. Создаём отдельного пользователя для этого теста. status, body, _ = call( "POST", "/api/v1/users", { "username": username, "display_name": "Auth Test User", "password": PASSWORD, }, ) if status != 201: raise AssertionError( f"registration: expected 201, got {status}: {body}" ) # 2. Неверный пароль не должен создавать сессию. status, body, headers = call( "POST", "/api/v1/auth/sessions", headers={ "Authorization": basic_header( username, "definitely-wrong-password", ) }, ) if status != 401: raise AssertionError( f"wrong password: expected 401, got {status}: {body}" ) if body is None or body.get("error", {}).get("code") != "unauthorized": raise AssertionError( f"wrong password: unexpected response body: {body}" ) # 3. С правильным паролем получаем Bearer-сессию. status, body, _ = call( "POST", "/api/v1/auth/sessions", headers={ "Authorization": basic_header(username, PASSWORD) }, ) if status != 201: raise AssertionError( f"login: expected 201, got {status}: {body}" ) if body is None: raise AssertionError("login: empty response body") token = body.get("token") if not token: raise AssertionError("login: token is missing") if body.get("token_type") != "Bearer": raise AssertionError( f"login: expected token_type Bearer, got {body.get('token_type')}" ) bearer = {"Authorization": f"Bearer {token}"} # 4. До logout токен обязан работать. status, body, _ = call( "GET", "/api/v1/users/me", headers=bearer, ) if status != 200: raise AssertionError( f"token before logout: expected 200, got {status}: {body}" ) # 5. Отзываем текущую сессию. status, body, _ = call( "DELETE", "/api/v1/auth/sessions/current", headers=bearer, ) if status != 204: raise AssertionError( f"logout: expected 204, got {status}: {body}" ) # 6. Тот же токен после logout больше не принимается. status, body, _ = call( "GET", "/api/v1/users/me", headers=bearer, ) if status != 401: raise AssertionError( f"token after logout: expected 401, got {status}: {body}" ) # 7. Повторный logout с уже отозванным токеном тоже не авторизован. status, body, _ = call( "DELETE", "/api/v1/auth/sessions/current", headers=bearer, ) if status != 401: raise AssertionError( f"repeated logout: expected 401, got {status}: {body}" ) print( "PASS: wrong password returned 401; " "valid session worked; logout revoked the token." ) if __name__ == "__main__": main()