This repository has been archived by the owner on Jul 1, 2024. It is now read-only.
forked from simplebot-org/simplebot-www-heroku
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrestore_keys.py
46 lines (39 loc) · 1.46 KB
/
restore_keys.py
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
44
45
46
import os
import subprocess
from tempfile import TemporaryDirectory
import psycopg2
def set_key(keydata: str) -> None:
with TemporaryDirectory() as tempdir:
path = os.path.join(tempdir, "private-key.asc")
with open(path, "w") as keyfile:
keyfile.write(keydata)
subprocess.run(["simplebot", "-a", os.environ["ADDR"], "import", tempdir])
def get_key() -> str:
with TemporaryDirectory() as tempdir:
subprocess.run(["simplebot", "-a", os.environ["ADDR"], "export", "-k", tempdir])
for name in os.listdir(tempdir):
if "private" in name:
with open(os.path.join(tempdir, name)) as keyfile:
return keyfile.read()
raise ValueError("invalid key data")
if __name__ == "__main__":
conn = psycopg2.connect(os.environ["DATABASE_URL"])
try:
with conn:
with conn.cursor() as cur:
cur.execute(
"CREATE TABLE config (key varchar(250) PRIMARY KEY, value varchar);"
)
cur.execute(
"INSERT INTO config (key, value) VALUES (%s, %s)",
("private_key", get_key()),
)
except Exception:
with conn:
with conn.cursor() as cur:
cur.execute(
"SELECT value FROM config WHERE key = %s;", ("private_key",)
)
set_key(cur.fetchone()[0])
finally:
conn.close()