109 lines
2.9 KiB
Python
109 lines
2.9 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
Script de création du premier utilisateur administrateur
|
|
|
|
Usage:
|
|
python create_admin.py
|
|
"""
|
|
|
|
import asyncio
|
|
import sys
|
|
from pathlib import Path
|
|
import uuid
|
|
from datetime import datetime
|
|
|
|
sys.path.insert(0, str(Path(__file__).parent))
|
|
|
|
from database import async_session_factory, User
|
|
from security.auth import hash_password, validate_password_strength
|
|
import logging
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
async def create_admin():
|
|
"""Crée un utilisateur admin"""
|
|
|
|
print("\n" + "=" * 60)
|
|
print("🔐 Création d'un compte administrateur")
|
|
print("=" * 60 + "\n")
|
|
|
|
# Saisie des informations
|
|
email = input("Email de l'admin: ").strip().lower()
|
|
if not email or "@" not in email:
|
|
print("❌ Email invalide")
|
|
return False
|
|
|
|
prenom = input("Prénom: ").strip()
|
|
nom = input("Nom: ").strip()
|
|
|
|
if not prenom or not nom:
|
|
print("❌ Prénom et nom requis")
|
|
return False
|
|
|
|
# Mot de passe avec validation
|
|
while True:
|
|
password = input(
|
|
"Mot de passe (min 8 car., 1 maj, 1 min, 1 chiffre, 1 spécial): "
|
|
)
|
|
is_valid, error_msg = validate_password_strength(password)
|
|
|
|
if is_valid:
|
|
confirm = input("Confirmez le mot de passe: ")
|
|
if password == confirm:
|
|
break
|
|
else:
|
|
print("❌ Les mots de passe ne correspondent pas\n")
|
|
else:
|
|
print(f"❌ {error_msg}\n")
|
|
|
|
# Vérifier si l'email existe déjà
|
|
async with async_session_factory() as session:
|
|
from sqlalchemy import select
|
|
|
|
result = await session.execute(select(User).where(User.email == email))
|
|
existing = result.scalar_one_or_none()
|
|
|
|
if existing:
|
|
print(f"\n❌ Un utilisateur avec l'email {email} existe déjà")
|
|
return False
|
|
|
|
# Créer l'admin
|
|
admin = User(
|
|
id=str(uuid.uuid4()),
|
|
email=email,
|
|
hashed_password=hash_password(password),
|
|
nom=nom,
|
|
prenom=prenom,
|
|
role="admin",
|
|
is_verified=True, # Admin vérifié par défaut
|
|
is_active=True,
|
|
created_at=datetime.now(),
|
|
)
|
|
|
|
session.add(admin)
|
|
await session.commit()
|
|
|
|
print("\n✅ Administrateur créé avec succès!")
|
|
print(f"📧 Email: {email}")
|
|
print(f"👤 Nom: {prenom} {nom}")
|
|
print(f"🔑 Rôle: admin")
|
|
print(f"🆔 ID: {admin.id}")
|
|
print("\n💡 Vous pouvez maintenant vous connecter à l'API\n")
|
|
|
|
return True
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
result = asyncio.run(create_admin())
|
|
sys.exit(0 if result else 1)
|
|
except KeyboardInterrupt:
|
|
print("\n\n❌ Création annulée")
|
|
sys.exit(1)
|
|
except Exception as e:
|
|
print(f"\n❌ Erreur: {e}")
|
|
logger.exception("Détails:")
|
|
sys.exit(1)
|