Workhub / server /admin.py
ag235772's picture
files Replacement
e298636
Raw History Blame Contribute Delete
1.53 kB
"""Admin helper: python server/admin.py list | reset-2fa <email> | remove-device <email> | audit [n]"""
import sys, time
import db
db.init()
cmd, *a = sys.argv[1:] or ["help"]
if cmd == "list":
for u in db.qa("SELECT id,email,totp_confirmed,last_login FROM users ORDER BY email"):
n = db.q1("SELECT COUNT(*) c FROM devices WHERE user_id=? AND revoked=0", u["id"])["c"]
print(f'{u["email"]:40} 2FA={"yes" if u["totp_confirmed"] else "no "} devices={n} last_login={time.strftime("%Y-%m-%d %H:%M", time.localtime(u["last_login"] or 0))}')
elif cmd == "reset-2fa" and a: # lost authenticator: user will re-enrol (QR) at next sign-in, all devices forgotten
u = db.q1("SELECT id FROM users WHERE email=?", a[0].lower())
if not u: sys.exit("no such user")
db.ex("UPDATE users SET totp_secret=NULL,totp_confirmed=0,fail_count=0,locked_until=0,last_step=0 WHERE id=?", u["id"])
db.ex("UPDATE devices SET revoked=1 WHERE user_id=?", u["id"]); db.audit(a[0], "admin_reset_2fa"); print("done")
elif cmd == "remove-device" and a:
u = db.q1("SELECT id FROM users WHERE email=?", a[0].lower())
if not u: sys.exit("no such user")
db.ex("UPDATE devices SET revoked=1 WHERE user_id=?", u["id"]); print("all devices revoked")
elif cmd == "audit":
for r in db.qa("SELECT * FROM audit ORDER BY ts DESC LIMIT ?", int(a[0]) if a else 30):
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(r["ts"])), r["email"], r["event"], r["ip"], r["detail"] or "")
else:
print(__doc__)