40 lines
1.1 KiB
Python
40 lines
1.1 KiB
Python
from __future__ import annotations
|
|
|
|
import httpx
|
|
|
|
from yuxi.channels.exceptions import ChannelAuthenticationError, ChannelConnectionError
|
|
from yuxi.utils.logging_config import logger
|
|
|
|
from .client import UrbitClient
|
|
|
|
|
|
async def authenticate_ship(
|
|
client: UrbitClient,
|
|
ship_code: str,
|
|
) -> str:
|
|
try:
|
|
r = await client.post("/~/login", json={"password": ship_code})
|
|
except httpx.RequestError as e:
|
|
raise ChannelConnectionError("Cannot reach Urbit Ship") from e
|
|
|
|
if r.status_code == 403:
|
|
raise ChannelAuthenticationError()
|
|
if r.status_code != 200:
|
|
raise ChannelAuthenticationError()
|
|
|
|
cookie = r.cookies.get(client.auth_cookie_name)
|
|
if not cookie:
|
|
raise ChannelAuthenticationError()
|
|
|
|
client.set_session_cookie(cookie)
|
|
logger.info(f"[Urbit] Authenticated to Ship ~{client.ship_name}")
|
|
return cookie
|
|
|
|
|
|
async def refresh_session_if_needed(
|
|
client: UrbitClient,
|
|
ship_code: str,
|
|
) -> str:
|
|
logger.info("[Urbit] Session expired, re-authenticating...")
|
|
return await authenticate_ship(client, ship_code)
|