forked from mtusi2026/mtusi2026lab2
54 lines
1.6 KiB
Python
54 lines
1.6 KiB
Python
#!/usr/bin/env python3
|
|
import base64
|
|
import json
|
|
import time
|
|
import urllib.request
|
|
import urllib.error
|
|
import uuid
|
|
|
|
BASE = "http://127.0.0.1:8080"
|
|
PASSWORD = "Example-only-not-a-real-secret-123"
|
|
|
|
|
|
def call(method, path, body=None, token=None, basic=None):
|
|
h = {"Accept": "application/json"}
|
|
if token:
|
|
h["Authorization"] = f"Bearer {token}"
|
|
if basic:
|
|
h["Authorization"] = f"Basic {basic}"
|
|
data = None
|
|
if body is not None:
|
|
data = json.dumps(body).encode("utf-8")
|
|
h["Content-Type"] = "application/json"
|
|
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=10) as r:
|
|
return r.status, json.loads(r.read()) if r.status != 204 else None
|
|
except urllib.error.HTTPError as e:
|
|
payload = e.read()
|
|
try:
|
|
return e.code, json.loads(payload) if payload else None
|
|
except ValueError:
|
|
return e.code, None
|
|
|
|
|
|
name = f"exp_{uuid.uuid4().hex[:6]}"
|
|
s, _ = call("POST", "/api/v1/users", {"username": name, "display_name": name, "password": PASSWORD})
|
|
assert s == 201, s
|
|
|
|
cred = base64.b64encode(f"{name}:{PASSWORD}".encode()).decode()
|
|
s, session = call("POST", "/api/v1/auth/sessions", basic=cred)
|
|
assert s == 201, (s, session)
|
|
token = session["token"]
|
|
print(f"session created, expires_at={session['expires_at']}")
|
|
|
|
# Сразу
|
|
s, _ = call("GET", "/api/v1/users/me", token=token)
|
|
print(f"immediately: {s} (expect 200)")
|
|
|
|
# Ждём 4 секунды (TTL=2s)
|
|
time.sleep(4)
|
|
|
|
s, body = call("GET", "/api/v1/users/me", token=token)
|
|
print(f"after 4s: {s} (expect 401)")
|
|
print(f"body: {body}") |