first key exchange thing
This commit is contained in:
75
python_frontend/frontend.py
Normal file
75
python_frontend/frontend.py
Normal file
@@ -0,0 +1,75 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import List
|
||||
import requests
|
||||
from nacl.signing import SigningKey, VerifyKey
|
||||
import base64
|
||||
|
||||
import json
|
||||
|
||||
|
||||
BASE_URL = "http://localhost:1323/api"
|
||||
|
||||
|
||||
class User:
|
||||
def __init__(self, session: Session, name: str) -> None:
|
||||
self.session = session
|
||||
self.name = name
|
||||
|
||||
self.signing_key = SigningKey.generate()
|
||||
|
||||
r = requests.post(BASE_URL + f"/{self.session.name}/user", json={
|
||||
"Name": name,
|
||||
"PublicKey": base64.b64encode(self.signing_key.verify_key.__bytes__()).decode("ascii")
|
||||
})
|
||||
|
||||
data = r.json()
|
||||
print(json.dumps(data, indent=4))
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"User({self.name})"
|
||||
|
||||
|
||||
def test_auth(self):
|
||||
r = self.signed_request("/test-auth", {
|
||||
"foo": "bar"
|
||||
})
|
||||
print(r.content)
|
||||
|
||||
def signed_request(self, endpoint: str, body: dict) -> requests.Response:
|
||||
payload = json.dumps(body).encode("utf-8")
|
||||
|
||||
signature = self.signing_key.sign(payload)
|
||||
|
||||
return requests.post(
|
||||
url=BASE_URL+f"/{self.session.name}"+endpoint,
|
||||
data=payload,
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"signature": base64.b64encode(signature.signature).decode("ascii")
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class Session:
|
||||
def __init__(self) -> None:
|
||||
data = requests.post(BASE_URL + "/session").json()
|
||||
self.name = data["Name"]
|
||||
self.users: List[User] = []
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Session({self.name})"
|
||||
|
||||
def add_user(self, name: str) -> User:
|
||||
u = User(session=self, name=name)
|
||||
self.users.append(u)
|
||||
return u
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
s = Session()
|
||||
print(s)
|
||||
u = s.add_user(name="Hazel")
|
||||
print(u)
|
||||
|
||||
u.test_auth()
|
||||
Reference in New Issue
Block a user