summaryrefslogtreecommitdiffstats
path: root/packages/meshbay-cli/src/meshbay_cli/commands/logout.py
blob: 7ee3aa2618078945afe6db896df67fd15c390437 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""`logout`: end the session on the hub, retire this machine's key, erase the store."""

import json

from ..client.account import Account, no_passphrase
from ..client.hub import Hub
from ..errors import CliError
from ..output import err, sentence
from .context import Context

HELP = "end the session, retire this machine's device key and erase what is stored"


def add_parser(sub, parent) -> None:
    sub.add_parser("logout", parents=[parent], help=HELP, description=sentence(HELP) + ".")


async def sign_out_stored(ctx: Context) -> None:
    """Whatever account the store holds, on whatever hub. Never asks anything."""
    stored = ctx.store.peek()
    hub = ctx.hub if stored.get("hub") == ctx.hub.url else Hub(stored.get("hub", ""))
    try:
        account = Account.open(hub, None, no_passphrase, ctx.store)
        warnings = await account.sign_out()
    except CliError as e:
        warnings = [f"The saved session could not be opened ({e.message}); it is erased "
                    "here, and ends on the hub when it expires."]
        with ctx.store.locked():
            ctx.store.erase()
    finally:
        if hub is not ctx.hub:
            await hub.aclose()
    for w in warnings:
        err(f"meshbay-cli: warning: {w}")


async def run(ctx: Context) -> int:
    if not ctx.store.peek():
        print(json.dumps({"signed_out": False}) if ctx.args.json else "Not signed in.")
        return 0
    await sign_out_stored(ctx)
    print(json.dumps({"signed_out": True}) if ctx.args.json else "Signed out.")
    return 0