Rétablissement dossier travail

This commit is contained in:
2025-08-18 09:45:24 +02:00
parent 726a35c1a6
commit 8550400255
2 changed files with 42 additions and 33 deletions

View File

@@ -1,39 +1,60 @@
#!/usr/bin/env python3
import os, sys, argparse, datetime
from pathlib import Path
import mysql.connector, bcrypt
from dotenv import load_dotenv
def load_env_near_exe():
base = Path(sys.executable).parent if getattr(sys, "frozen", False) else Path(__file__).resolve().parent
env_path = base / ".env"
if env_path.exists():
for line in env_path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
os.environ.setdefault(k.strip(), v.strip())
def read_stdin() -> str:
data = sys.stdin.read()
return data.rstrip("\r\n")
return sys.stdin.read().rstrip("\r\n")
def main():
load_dotenv()
load_env_near_exe()
ap = argparse.ArgumentParser(description="Auth bcrypt locale pour Excel")
ap = argparse.ArgumentParser(description="Auth bcrypt pour Excel")
ap.add_argument("--user", required=True, help="NomUtilisateur (clé primaire)")
ap.add_argument("--password-stdin", action="store_true",
help="Lire le mot de passe via STDIN (recommandé)")
ap.add_argument("--password-stdin", action="store_true", help="Lire le mot de passe via STDIN")
ap.add_argument("--debug", action="store_true", help="Afficher les détails de connexion")
args = ap.parse_args()
if not args.password_stdin:
print("ERR|Utiliser --password-stdin et fournir le mot de passe via STDIN", flush=True)
return 2
print("ERR|Utiliser --password-stdin et fournir le mot de passe via STDIN", flush=True); return 2
password = read_stdin()
if not password:
print("ERR|Mot de passe vide", flush=True)
return 2
print("ERR|Mot de passe vide", flush=True); return 2
# Récupération des infos de connexion depuis .env
host = os.getenv("DB_HOST")
host = os.getenv("DB_HOST", "localhost")
db = os.getenv("DB_NAME")
user = os.getenv("DB_USER")
pwd = os.getenv("DB_PASSWORD")
port = int(os.getenv("DB_PORT", "3306"))
ssl_ca = os.getenv("DB_SSL_CA")
ssl_cert = os.getenv("DB_SSL_CERT")
ssl_key = os.getenv("DB_SSL_KEY")
ssl_opts = {}
if ssl_ca:
ssl_opts["ssl_ca"] = ssl_ca
if ssl_cert: ssl_opts["ssl_cert"] = ssl_cert
if ssl_key: ssl_opts["ssl_key"] = ssl_key
if args.debug:
print(f"DEBUG host={host} port={port} db={db} user={user} ssl={'on' if ssl_opts else 'off'}", flush=True)
try:
conn = mysql.connector.connect(
host=host, database=db, user=user, password=pwd, connection_timeout=5
host=host, port=port, database=db, user=user, password=pwd,
connection_timeout=6, **ssl_opts
)
cur = conn.cursor(dictionary=True)
cur.execute("""
@@ -43,44 +64,32 @@ def main():
LIMIT 1
""", (args.user,))
row = cur.fetchone()
cur.close(); conn.close()
except Exception as e:
print("ERR|Connexion base impossible", flush=True)
print(f"ERR|Connexion base impossible{': ' + str(e) if args.debug else ''}", flush=True)
return 3
finally:
try:
cur.close()
conn.close()
except Exception:
pass
if not row or not row.get("MotDePasseHash"):
print("ERR|Utilisateur ou mot de passe invalide", flush=True)
return 1
print("ERR|Utilisateur ou mot de passe invalide", flush=True); return 1
try:
ok = bcrypt.checkpw(password.encode("utf-8"),
row["MotDePasseHash"].encode("ascii"))
ok = bcrypt.checkpw(password.encode("utf-8"), row["MotDePasseHash"].encode("ascii"))
except Exception:
ok = False
if not ok:
print("ERR|Utilisateur ou mot de passe invalide", flush=True)
return 1
print("ERR|Utilisateur ou mot de passe invalide", flush=True); return 1
# Contrôle expiration (si renseignée)
exp = row.get("DateExpiration")
if exp is not None:
today = datetime.date.today()
exp_date = exp if isinstance(exp, datetime.date) else getattr(exp, "date", lambda: today)()
exp_date = exp if hasattr(exp, "year") else getattr(exp, "date", lambda: today)()
if exp_date < today:
print(f"ERR|Compte expiré le {exp_date.isoformat()}", flush=True)
return 2
print(f"ERR|Compte expiré le {exp_date.isoformat()}", flush=True); return 2
site = row.get("Site") or ""
nom = row.get("Nom_complet") or ""
print(f"OK|Site={site}|NomComplet={nom}", flush=True)
return 0
if __name__ == "__main__":
sys.exit(main())