115 lignes
5.3 KiB
Python
115 lignes
5.3 KiB
Python
"""Gestion des codes d'accès et des retours de la bêta (en ligne de commande, local).
|
|
|
|
python beta/codes.py generer --label "Prénom N." [--jours 30] [--nombre 1] [--sessions 3] [--csv]
|
|
python beta/codes.py liste
|
|
python beta/codes.py revoquer <id>
|
|
python beta/codes.py prolonger <id> --jours 14
|
|
python beta/codes.py journal [--n 30]
|
|
python beta/codes.py retours [--n 30]
|
|
python beta/codes.py testeurs
|
|
|
|
Le code en clair n'est affiché qu'une seule fois, à la génération.
|
|
"""
|
|
import argparse
|
|
import csv
|
|
import os
|
|
import sys
|
|
import time
|
|
import unicodedata
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
import db # noqa: E402
|
|
|
|
|
|
def propre(v):
|
|
"""Remplace tout caractère de contrôle (catégorie Unicode C*) : un testeur ne doit
|
|
pas pouvoir injecter de séquence d'échappement dans le terminal."""
|
|
return "".join(" " if unicodedata.category(ch)[0] == "C" else ch for ch in str(v if v is not None else ""))
|
|
|
|
|
|
def fmt(ts):
|
|
return datetime.fromtimestamp(ts).strftime("%d/%m/%Y %H:%M") if ts else "-"
|
|
|
|
|
|
def etat(r):
|
|
if r["revoked_at"]:
|
|
return "révoqué"
|
|
if r["expires_at"] and r["expires_at"] <= time.time():
|
|
return "expiré"
|
|
return "actif"
|
|
|
|
|
|
def main(argv=None):
|
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
sp = ap.add_subparsers(dest="cmd", required=True)
|
|
g = sp.add_parser("generer")
|
|
g.add_argument("--label", required=True)
|
|
g.add_argument("--jours", type=int, default=30, help="durée de validité (0 = sans expiration)")
|
|
g.add_argument("--nombre", type=int, default=1)
|
|
g.add_argument("--sessions", type=int, default=3)
|
|
g.add_argument("--csv", action="store_true", help="écrit aussi beta/data/codes-emis.csv (hors git)")
|
|
sp.add_parser("liste")
|
|
r = sp.add_parser("revoquer"); r.add_argument("id", type=int)
|
|
p = sp.add_parser("prolonger"); p.add_argument("id", type=int); p.add_argument("--jours", type=int, required=True)
|
|
j = sp.add_parser("journal"); j.add_argument("--n", type=int, default=30)
|
|
f = sp.add_parser("retours"); f.add_argument("--n", type=int, default=30)
|
|
sp.add_parser("testeurs")
|
|
a = ap.parse_args(argv)
|
|
c = db.connect()
|
|
|
|
if a.cmd == "generer":
|
|
lignes = []
|
|
for i in range(a.nombre):
|
|
label = a.label if a.nombre == 1 else f"{a.label} {i + 1}"
|
|
cid, code = db.creer_code(c, label, a.jours, a.sessions)
|
|
lignes.append((cid, label, code))
|
|
print(f"#{cid} {propre(label)} {code}")
|
|
if a.csv:
|
|
f_ = db.DATA / "codes-emis.csv"
|
|
neuf = not f_.exists()
|
|
fd = os.open(f_, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
|
|
with os.fdopen(fd, "a", newline="", encoding="utf-8") as fh:
|
|
w = csv.writer(fh)
|
|
if neuf:
|
|
w.writerow(["id", "label", "code"])
|
|
w.writerows(lignes)
|
|
print(f"(écrit dans {f_} : hors git, à supprimer après envoi)")
|
|
elif a.cmd == "liste":
|
|
for r_ in c.execute("SELECT * FROM codes ORDER BY id"):
|
|
print(f"#{r_['id']:<3} {etat(r_):<8} {propre(r_['label']):<24} créé {fmt(r_['created_at'])} expire {fmt(r_['expires_at'])} "
|
|
f"usages {r_['uses']} dernier {fmt(r_['last_used_at'])}")
|
|
elif a.cmd == "revoquer":
|
|
c.execute("UPDATE codes SET revoked_at=? WHERE id=? AND revoked_at IS NULL", (time.time(), a.id))
|
|
c.execute("DELETE FROM sessions WHERE code_id=?", (a.id,))
|
|
c.commit()
|
|
db.journal(c, "code_revoque", a.id)
|
|
print(f"Code #{a.id} révoqué ; ses sessions sont coupées.")
|
|
elif a.cmd == "prolonger":
|
|
row = c.execute("SELECT * FROM codes WHERE id=?", (a.id,)).fetchone()
|
|
if not row or row["revoked_at"]:
|
|
sys.exit("Code introuvable ou révoqué.")
|
|
base = max(row["expires_at"] or time.time(), time.time())
|
|
c.execute("UPDATE codes SET expires_at=? WHERE id=?", (base + a.jours * 86400, a.id))
|
|
c.commit()
|
|
db.journal(c, "code_prolonge", a.id, None, f"+{a.jours} j")
|
|
print("Prolongé.")
|
|
elif a.cmd == "journal":
|
|
for r_ in c.execute("SELECT * FROM audit ORDER BY id DESC LIMIT ?", (a.n,)):
|
|
print(f"{fmt(r_['ts'])} {propre(r_['event']):<16} code={r_['code_id'] or '-'} ip={propre(r_['ip_hash']) or '-'} {propre(r_['detail'])}")
|
|
elif a.cmd == "retours":
|
|
for r_ in c.execute("SELECT f.*, c.label FROM feedback f LEFT JOIN codes c ON c.id=f.code_id ORDER BY f.id DESC LIMIT ?", (a.n,)):
|
|
print(f"#{r_['id']} {fmt(r_['ts'])} [{propre(r_['kind'])}] {propre(r_['label'])} sur {propre(r_['page'])} ({propre(r_['viewport'])})"
|
|
f"{' capture: ' + propre(r_['shot']) if r_['shot'] else ''}\n {propre(r_['text'])}")
|
|
elif a.cmd == "testeurs":
|
|
for r_ in c.execute("SELECT * FROM testers ORDER BY id"):
|
|
st = "ACTIF" if r_["actif"] else "SUSPENDU"
|
|
ip_str = f"IP={propre(r_['ip'])} (purge {fmt(r_['expire_ip_at'])})" if r_["ip"] else "IP: -"
|
|
print(f"#{r_['id']} [{st}] {propre(r_['prenom'])} {propre(r_['nom'])} <{propre(r_['email'])}> {propre(r_['tel'])} {ip_str} "
|
|
f"{'MINEUR (parent: ' + propre(r_['parent_nom']) + ')' if r_['mineur'] else 'majeur'} reseaux={r_['suivi_reseaux']}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|