alioune 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. alioune/__init__.py +3 -0
  2. alioune/__main__.py +4 -0
  3. alioune/auth.py +59 -0
  4. alioune/cli.py +289 -0
  5. alioune/gabarits/auth/app/creer_admin.py +49 -0
  6. alioune/gabarits/auth/app/dependances.py +57 -0
  7. alioune/gabarits/auth/app/modeles/utilisateur.py +18 -0
  8. alioune/gabarits/auth/app/routeurs/auth.py +39 -0
  9. alioune/gabarits/auth/app/schemas/auth.py +25 -0
  10. alioune/gabarits/auth/app/securite.py +48 -0
  11. alioune/gabarits/auth/app/services/auth.py +41 -0
  12. alioune/gabarits/auth/tests/test_auth.py +51 -0
  13. alioune/gabarits/generer/config.py.j2 +25 -0
  14. alioune/gabarits/generer/migration.py.j2 +24 -0
  15. alioune/gabarits/generer/modele.py.j2 +16 -0
  16. alioune/gabarits/generer/routeur.py.j2 +61 -0
  17. alioune/gabarits/generer/schema.py.j2 +31 -0
  18. alioune/gabarits/generer/service.py.j2 +39 -0
  19. alioune/gabarits/generer/test.py.j2 +65 -0
  20. alioune/gabarits/projet/README.md.j2 +56 -0
  21. alioune/gabarits/projet/alembic/env.py +56 -0
  22. alioune/gabarits/projet/alembic/script.py.mako +25 -0
  23. alioune/gabarits/projet/alembic/versions/dot_gitkeep +0 -0
  24. alioune/gabarits/projet/alembic.ini +40 -0
  25. alioune/gabarits/projet/alioune.json.j2 +6 -0
  26. alioune/gabarits/projet/app/__init__.py +0 -0
  27. alioune/gabarits/projet/app/base_de_donnees.py.j2 +39 -0
  28. alioune/gabarits/projet/app/config.py.j2 +40 -0
  29. alioune/gabarits/projet/app/gabarits/accueil.html +55 -0
  30. alioune/gabarits/projet/app/main.py +25 -0
  31. alioune/gabarits/projet/app/modeles/__init__.py +11 -0
  32. alioune/gabarits/projet/app/modeles/base.py +19 -0
  33. alioune/gabarits/projet/app/routeurs/__init__.py +13 -0
  34. alioune/gabarits/projet/app/routeurs/accueil.py +26 -0
  35. alioune/gabarits/projet/app/routeurs/sante.py +18 -0
  36. alioune/gabarits/projet/app/schemas/__init__.py +1 -0
  37. alioune/gabarits/projet/app/services/__init__.py +1 -0
  38. alioune/gabarits/projet/dot_env.example.j2 +8 -0
  39. alioune/gabarits/projet/dot_gitignore +9 -0
  40. alioune/gabarits/projet/pytest.ini +3 -0
  41. alioune/gabarits/projet/requirements-dev.txt +3 -0
  42. alioune/gabarits/projet/requirements.txt.j2 +9 -0
  43. alioune/gabarits/projet/tests/__init__.py +0 -0
  44. alioune/gabarits/projet/tests/conftest.py +35 -0
  45. alioune/gabarits/projet/tests/test_accueil.py +16 -0
  46. alioune/gabarits/projet/tests/test_sante.py +8 -0
  47. alioune/generateurs.py +294 -0
  48. alioune/migrations.py +100 -0
  49. alioune/moteur.py +87 -0
  50. alioune/noms.py +55 -0
  51. alioune/nouveau.py +87 -0
  52. alioune/plan.py +107 -0
  53. alioune/projet.py +38 -0
  54. alioune-0.1.0.dist-info/METADATA +87 -0
  55. alioune-0.1.0.dist-info/RECORD +58 -0
  56. alioune-0.1.0.dist-info/WHEEL +4 -0
  57. alioune-0.1.0.dist-info/entry_points.txt +2 -0
  58. alioune-0.1.0.dist-info/licenses/LICENSE +21 -0
alioune/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """alioune : générateur de projets et de code pour FastAPI."""
2
+
3
+ __version__ = "0.1.0"
alioune/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from alioune.cli import app
2
+
3
+ if __name__ == "__main__":
4
+ app()
alioune/auth.py ADDED
@@ -0,0 +1,59 @@
1
+ """Logique de `alioune auth` : installe l'authentification (JWT) dans un projet."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from alioune.generateurs import (
8
+ CHEMIN_MODELES_INIT,
9
+ CHEMIN_ROUTEURS_INIT,
10
+ MARQUEUR_IMPORTS,
11
+ MARQUEUR_INCLUSIONS,
12
+ MARQUEUR_MODELES,
13
+ )
14
+ from alioune.migrations import lignes_creation_table, preparer_migration
15
+ from alioune.moteur import rendre_en_memoire
16
+ from alioune.plan import Insertion, Plan
17
+
18
+ DEPENDANCES = [
19
+ ("pyjwt>=2.8", "pyjwt"),
20
+ ("pwdlib[argon2]>=0.2", "pwdlib"),
21
+ ("email-validator>=2.1", "email-validator"),
22
+ ("python-multipart>=0.0.9", "python-multipart"),
23
+ ]
24
+
25
+
26
+ def preparer_auth(racine: Path) -> Plan:
27
+ plan = Plan()
28
+ plan.creations += rendre_en_memoire("auth", {})
29
+
30
+ colonnes = [
31
+ 'sa.Column("email", sa.String(length=255), nullable=False)',
32
+ 'sa.Column("nom_complet", sa.String(length=255), nullable=False)',
33
+ 'sa.Column("mot_de_passe_hache", sa.String(length=255), nullable=False)',
34
+ 'sa.Column("role", sa.String(length=50), nullable=False)',
35
+ 'sa.Column("est_actif", sa.Boolean(), nullable=False)',
36
+ ]
37
+ haut, bas = lignes_creation_table(
38
+ "utilisateurs", colonnes, index=[("ix_utilisateurs_email", "email", True)]
39
+ )
40
+ plan.creations.append(preparer_migration(racine, "creer_table_utilisateurs", haut, bas))
41
+
42
+ plan.insertions += [
43
+ Insertion(
44
+ CHEMIN_MODELES_INIT,
45
+ "from app.modeles.utilisateur import Utilisateur # noqa: F401",
46
+ MARQUEUR_MODELES,
47
+ ),
48
+ Insertion(
49
+ CHEMIN_ROUTEURS_INIT,
50
+ "from app.routeurs.auth import routeur as routeur_auth",
51
+ MARQUEUR_IMPORTS,
52
+ ),
53
+ Insertion(
54
+ CHEMIN_ROUTEURS_INIT, "routeur_api.include_router(routeur_auth)", MARQUEUR_INCLUSIONS
55
+ ),
56
+ ]
57
+ for ligne, cle in DEPENDANCES:
58
+ plan.insertions.append(Insertion(Path("requirements.txt"), ligne, cle=cle))
59
+ return plan
alioune/cli.py ADDED
@@ -0,0 +1,289 @@
1
+ """Point d'entrée de la commande `alioune`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+ from enum import Enum
7
+ from pathlib import Path
8
+ from typing import Annotated, Optional
9
+
10
+ import typer
11
+ from rich.console import Console
12
+ from rich.table import Table
13
+
14
+ from alioune import __version__
15
+ from alioune.auth import preparer_auth
16
+ from alioune.generateurs import preparer_generation
17
+ from alioune.nouveau import ErreurCreation, creer_projet
18
+ from alioune.noms import nom_projet_valide
19
+ from alioune.plan import ErreurPlan, Rapport, appliquer
20
+ from alioune.projet import lire_configuration, python_a_utiliser, trouver_racine
21
+
22
+ app = typer.Typer(
23
+ name="alioune",
24
+ help="Générateur de projets et de code pour FastAPI.",
25
+ no_args_is_help=True,
26
+ add_completion=False,
27
+ rich_markup_mode="rich",
28
+ )
29
+ console = Console()
30
+
31
+
32
+ class TypeBase(str, Enum):
33
+ postgresql = "postgresql"
34
+ sqlite = "sqlite"
35
+
36
+
37
+ def _afficher_version(valeur: bool) -> None:
38
+ if valeur:
39
+ console.print(f"alioune {__version__}")
40
+ raise typer.Exit()
41
+
42
+
43
+ @app.callback()
44
+ def principal(
45
+ version: Annotated[
46
+ Optional[bool],
47
+ typer.Option("--version", "-v", callback=_afficher_version, is_eager=True,
48
+ help="Affiche la version et quitte."),
49
+ ] = None,
50
+ ) -> None:
51
+ pass
52
+
53
+
54
+ def _racine_ou_quitter() -> Path:
55
+ racine = trouver_racine()
56
+ if racine is None:
57
+ console.print(
58
+ "[red]Aucun projet alioune ici.[/red] "
59
+ "Place-toi dans un projet créé avec [bold]alioune new[/bold]."
60
+ )
61
+ raise typer.Exit(code=1)
62
+ return racine
63
+
64
+
65
+ @app.command("new")
66
+ def nouveau(
67
+ nom: Annotated[str, typer.Argument(help="Nom du projet (devient le nom du dossier).")],
68
+ base: Annotated[
69
+ TypeBase, typer.Option("--base", help="Base de données du projet.")
70
+ ] = TypeBase.postgresql,
71
+ sans_installation: Annotated[
72
+ bool, typer.Option("--sans-installation", help="Ne crée pas le .venv et n'installe rien.")
73
+ ] = False,
74
+ sans_git: Annotated[
75
+ bool, typer.Option("--sans-git", help="N'initialise pas de dépôt Git.")
76
+ ] = False,
77
+ ) -> None:
78
+ """Crée un projet FastAPI complet, prêt à être lancé avec uvicorn."""
79
+ if not nom_projet_valide(nom):
80
+ console.print(
81
+ f"[red]Nom invalide :[/red] « {nom} ». "
82
+ "Utilise des lettres, chiffres, tirets, underscores ou points."
83
+ )
84
+ raise typer.Exit(code=1)
85
+
86
+ try:
87
+ with console.status("[bold]Création du projet..." if sans_installation
88
+ else "[bold]Création du projet et installation des dépendances..."):
89
+ resultat = creer_projet(
90
+ nom=nom,
91
+ base=base.value,
92
+ installer=not sans_installation,
93
+ initialiser_git=not sans_git,
94
+ dossier_parent=Path.cwd(),
95
+ )
96
+ except ErreurCreation as erreur:
97
+ console.print(f"[red]{erreur}[/red]")
98
+ raise typer.Exit(code=1)
99
+
100
+ for fichier in sorted(resultat.fichiers):
101
+ console.print(f" [green]CREATE[/green] {nom}/{fichier.as_posix()}")
102
+ if resultat.git_initialise:
103
+ console.print(" [green]git[/green] dépôt initialisé")
104
+ console.print(f"\n[bold green]Projet « {nom} » créé.[/bold green]\n")
105
+
106
+ console.print("Pour démarrer :")
107
+ console.print(f" cd {nom}")
108
+ if resultat.venv_cree:
109
+ console.print(" alioune serve [dim]# ou : uvicorn app.main:app --reload[/dim]")
110
+ else:
111
+ console.print(" python -m venv .venv && source .venv/bin/activate")
112
+ console.print(" pip install -r requirements-dev.txt")
113
+ console.print(" uvicorn app.main:app --reload")
114
+ console.print("\nPuis ouvre [bold]http://127.0.0.1:8000[/bold]")
115
+
116
+
117
+ class TypeGeneration(str, Enum):
118
+ ressource = "ressource"
119
+ modele = "modele"
120
+ schema = "schema"
121
+ service = "service"
122
+ routeur = "routeur"
123
+ migration = "migration"
124
+ config = "config"
125
+
126
+
127
+ def _afficher_rapport(rapport: Rapport, simuler: bool) -> None:
128
+ prefixe = "[dim](simulation)[/dim] " if simuler else ""
129
+ for chemin in rapport.crees:
130
+ console.print(f" {prefixe}[green]CREATE[/green] {chemin.as_posix()}")
131
+ for chemin in rapport.modifies:
132
+ console.print(f" {prefixe}[cyan]UPDATE[/cyan] {chemin.as_posix()}")
133
+ for message in rapport.avertissements:
134
+ console.print(f" [yellow]ATTENTION[/yellow] {message}")
135
+
136
+
137
+ @app.command("generate")
138
+ @app.command("g", hidden=True)
139
+ def generer(
140
+ type_generation: Annotated[
141
+ TypeGeneration, typer.Argument(help="Ce qu'il faut générer.", metavar="TYPE")
142
+ ],
143
+ nom: Annotated[str, typer.Argument(help="Nom au singulier (produit, ligne_commande...).")],
144
+ champs: Annotated[
145
+ Optional[str],
146
+ typer.Option(
147
+ "--champs", "-c",
148
+ help="Champs : nom:str,prix:decimal,note:text? (types : str text int float decimal bool date datetime ; ? = facultatif).",
149
+ ),
150
+ ] = None,
151
+ pluriel: Annotated[
152
+ Optional[str], typer.Option("--pluriel", help="Pluriel si la règle automatique se trompe.")
153
+ ] = None,
154
+ protege: Annotated[
155
+ bool, typer.Option("--protege", help="Exige un utilisateur connecté (après alioune auth).")
156
+ ] = False,
157
+ force: Annotated[bool, typer.Option("--force", "-f", help="Remplace les fichiers existants.")] = False,
158
+ simuler: Annotated[bool, typer.Option("--simuler", help="Affiche ce qui serait fait, sans écrire.")] = False,
159
+ ) -> None:
160
+ """Génère du code prêt à l'emploi : ressource, modele, schema, service, routeur, migration, config."""
161
+ racine = _racine_ou_quitter()
162
+ try:
163
+ plan = preparer_generation(
164
+ racine, type_generation.value, nom, champs=champs, pluriel=pluriel, protege=protege
165
+ )
166
+ rapport = appliquer(plan, racine, ecraser=force, simuler=simuler)
167
+ except ErreurPlan as erreur:
168
+ console.print(f"[red]{erreur}[/red]")
169
+ raise typer.Exit(code=1)
170
+ _afficher_rapport(rapport, simuler)
171
+ if type_generation in (TypeGeneration.ressource, TypeGeneration.migration) and not simuler:
172
+ console.print("\nPuis : [bold]alioune migrate[/bold]")
173
+
174
+
175
+ @app.command("auth")
176
+ def installer_auth(
177
+ force: Annotated[bool, typer.Option("--force", "-f", help="Remplace les fichiers existants.")] = False,
178
+ sans_installation: Annotated[
179
+ bool, typer.Option("--sans-installation", help="N'installe pas les nouvelles dépendances.")
180
+ ] = False,
181
+ simuler: Annotated[bool, typer.Option("--simuler", help="Affiche ce qui serait fait, sans écrire.")] = False,
182
+ ) -> None:
183
+ """Installe l'authentification (inscription, connexion JWT, rôles) dans le projet."""
184
+ racine = _racine_ou_quitter()
185
+ try:
186
+ rapport = appliquer(preparer_auth(racine), racine, ecraser=force, simuler=simuler)
187
+ except ErreurPlan as erreur:
188
+ console.print(f"[red]{erreur}[/red]")
189
+ raise typer.Exit(code=1)
190
+ _afficher_rapport(rapport, simuler)
191
+ if simuler:
192
+ return
193
+
194
+ python, venv_trouve = python_a_utiliser(racine)
195
+ if not sans_installation and venv_trouve:
196
+ with console.status("[bold]Installation des dépendances..."):
197
+ resultat = subprocess.run(
198
+ [python, "-m", "pip", "install", "--disable-pip-version-check", "-q",
199
+ "-r", "requirements.txt"],
200
+ cwd=racine, capture_output=True, text=True,
201
+ )
202
+ if resultat.returncode != 0:
203
+ console.print(f"[red]Échec de pip :[/red]\n{resultat.stderr.strip()[-800:]}")
204
+ raise typer.Exit(code=1)
205
+ elif not venv_trouve:
206
+ console.print("[yellow].venv introuvable : lance pip install -r requirements.txt toi-même.[/yellow]")
207
+
208
+ console.print("\n[bold green]Authentification installée.[/bold green]")
209
+ console.print(" 1. [bold]alioune migrate[/bold] crée la table des utilisateurs")
210
+ console.print(" 2. [bold]python -m app.creer_admin admin@exemple.com[/bold] crée un administrateur")
211
+ console.print(" 3. Routes : POST /api/auth/inscription, POST /api/auth/connexion, GET /api/auth/moi")
212
+ console.print(" 4. Protéger une ressource : [bold]alioune g ressource produit --protege[/bold]")
213
+
214
+
215
+ @app.command("serve")
216
+ def servir(
217
+ hote: Annotated[str, typer.Option("--hote", help="Adresse d'écoute.")] = "127.0.0.1",
218
+ port: Annotated[int, typer.Option("--port", "-p", help="Port d'écoute.")] = 8000,
219
+ sans_rechargement: Annotated[
220
+ bool, typer.Option("--sans-rechargement", help="Désactive le rechargement automatique.")
221
+ ] = False,
222
+ ) -> None:
223
+ """Lance le serveur de développement (uvicorn) du projet."""
224
+ racine = _racine_ou_quitter()
225
+ python, venv_trouve = python_a_utiliser(racine)
226
+ if not venv_trouve:
227
+ console.print("[yellow].venv introuvable : utilisation de l'interpréteur courant.[/yellow]")
228
+
229
+ commande = [python, "-m", "uvicorn", "app.main:app", "--host", hote, "--port", str(port)]
230
+ if not sans_rechargement:
231
+ commande.append("--reload")
232
+ try:
233
+ subprocess.run(commande, cwd=racine)
234
+ except KeyboardInterrupt:
235
+ pass
236
+
237
+
238
+ @app.command("migrate")
239
+ def migrer(
240
+ annuler: Annotated[
241
+ bool, typer.Option("--annuler", help="Annule la dernière migration au lieu d'appliquer.")
242
+ ] = False,
243
+ ) -> None:
244
+ """Applique les migrations Alembic (ou annule la dernière avec --annuler)."""
245
+ racine = _racine_ou_quitter()
246
+ python, _ = python_a_utiliser(racine)
247
+ arguments = ["downgrade", "-1"] if annuler else ["upgrade", "head"]
248
+ code = subprocess.run([python, "-m", "alembic", *arguments], cwd=racine).returncode
249
+ raise typer.Exit(code=code)
250
+
251
+
252
+ # On s'appuie sur le schéma OpenAPI (API publique de FastAPI) plutôt que sur
253
+ # `app.routes`, dont la structure interne change selon les versions.
254
+ _SCRIPT_ROUTES = """
255
+ from app.main import app
256
+ for chemin, operations in app.openapi()["paths"].items():
257
+ for methode, details in operations.items():
258
+ print(f"{methode.upper()}\\t{chemin}\\t{details.get('summary', '')}")
259
+ """
260
+
261
+
262
+ @app.command("routes")
263
+ def lister_routes() -> None:
264
+ """Liste les routes documentées (OpenAPI) de l'application."""
265
+ racine = _racine_ou_quitter()
266
+ python, _ = python_a_utiliser(racine)
267
+ resultat = subprocess.run([python, "-c", _SCRIPT_ROUTES], cwd=racine, capture_output=True, text=True)
268
+ if resultat.returncode != 0:
269
+ console.print(f"[red]{resultat.stderr.strip()}[/red]")
270
+ raise typer.Exit(code=1)
271
+
272
+ tableau = Table(show_header=True, header_style="bold")
273
+ tableau.add_column("Méthodes")
274
+ tableau.add_column("Chemin")
275
+ tableau.add_column("Résumé")
276
+ for ligne in resultat.stdout.strip().splitlines():
277
+ methodes, chemin, resume = ligne.split("\t")
278
+ tableau.add_row(methodes, chemin, resume)
279
+ console.print(tableau)
280
+
281
+
282
+ @app.command("info")
283
+ def informations() -> None:
284
+ """Affiche les informations du projet courant."""
285
+ racine = _racine_ou_quitter()
286
+ configuration = lire_configuration(racine)
287
+ console.print(f"[bold]{configuration['nom']}[/bold] ({racine})")
288
+ console.print(f" base de données : {configuration['base']}")
289
+ console.print(f" généré avec alioune {configuration['version_alioune']}")
@@ -0,0 +1,49 @@
1
+ """Crée un administrateur (ou promeut un compte existant).
2
+
3
+ python -m app.creer_admin admin@exemple.com --nom "Nom Complet"
4
+ """
5
+
6
+ import argparse
7
+ import getpass
8
+ import sys
9
+
10
+ from pydantic import ValidationError
11
+
12
+ from app.base_de_donnees import SessionLocale
13
+ from app.modeles.utilisateur import ROLE_ADMIN
14
+ from app.schemas.auth import UtilisateurCreation
15
+ from app.services import auth as service_auth
16
+
17
+
18
+ def principal() -> int:
19
+ analyseur = argparse.ArgumentParser(description="Crée ou promeut un administrateur.")
20
+ analyseur.add_argument("email")
21
+ analyseur.add_argument("--nom", default="Administrateur", help="Nom complet")
22
+ arguments = analyseur.parse_args()
23
+
24
+ with SessionLocale() as session:
25
+ existant = service_auth.obtenir_par_email(session, arguments.email)
26
+ if existant is not None:
27
+ existant.role = ROLE_ADMIN
28
+ session.commit()
29
+ print(f"Le compte {existant.email} est maintenant administrateur.")
30
+ return 0
31
+
32
+ mot_de_passe = getpass.getpass("Mot de passe (8 caractères minimum) : ")
33
+ if mot_de_passe != getpass.getpass("Confirmation : "):
34
+ print("Les mots de passe ne correspondent pas.", file=sys.stderr)
35
+ return 1
36
+ try:
37
+ donnees = UtilisateurCreation(
38
+ email=arguments.email, nom_complet=arguments.nom, mot_de_passe=mot_de_passe
39
+ )
40
+ except ValidationError as erreur:
41
+ print(erreur, file=sys.stderr)
42
+ return 1
43
+ utilisateur = service_auth.creer_utilisateur(session, donnees, role=ROLE_ADMIN)
44
+ print(f"Administrateur {utilisateur.email} créé.")
45
+ return 0
46
+
47
+
48
+ if __name__ == "__main__":
49
+ raise SystemExit(principal())
@@ -0,0 +1,57 @@
1
+ """Dépendances FastAPI d'authentification.
2
+
3
+ Usage dans une route :
4
+
5
+ @routeur.get("/secret")
6
+ def secret(utilisateur: UtilisateurCourant): ...
7
+
8
+ @routeur.delete("/{id}")
9
+ def supprimer(id: int, admin: UtilisateurAdmin): ...
10
+ """
11
+
12
+ from collections.abc import Callable
13
+ from typing import Annotated
14
+
15
+ from fastapi import Depends, HTTPException, status
16
+ from fastapi.security import OAuth2PasswordBearer
17
+
18
+ from app.base_de_donnees import SessionDep
19
+ from app.modeles.utilisateur import ROLE_ADMIN, Utilisateur
20
+ from app.securite import decoder_jeton
21
+ from app.services import auth as service_auth
22
+
23
+ schema_oauth2 = OAuth2PasswordBearer(tokenUrl="/api/auth/connexion")
24
+
25
+
26
+ def utilisateur_courant(
27
+ jeton: Annotated[str, Depends(schema_oauth2)], session: SessionDep
28
+ ) -> Utilisateur:
29
+ erreur = HTTPException(
30
+ status_code=status.HTTP_401_UNAUTHORIZED,
31
+ detail="Identifiants invalides ou expirés",
32
+ headers={"WWW-Authenticate": "Bearer"},
33
+ )
34
+ email = decoder_jeton(jeton)
35
+ if email is None:
36
+ raise erreur
37
+ utilisateur = service_auth.obtenir_par_email(session, email)
38
+ if utilisateur is None or not utilisateur.est_actif:
39
+ raise erreur
40
+ return utilisateur
41
+
42
+
43
+ UtilisateurCourant = Annotated[Utilisateur, Depends(utilisateur_courant)]
44
+
45
+
46
+ def exiger_role(*roles: str) -> Callable[[Utilisateur], Utilisateur]:
47
+ """Fabrique une dépendance qui n'accepte que les utilisateurs ayant l'un de ces rôles."""
48
+
49
+ def verifier(utilisateur: UtilisateurCourant) -> Utilisateur:
50
+ if utilisateur.role not in roles:
51
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Accès refusé")
52
+ return utilisateur
53
+
54
+ return verifier
55
+
56
+
57
+ UtilisateurAdmin = Annotated[Utilisateur, Depends(exiger_role(ROLE_ADMIN))]
@@ -0,0 +1,18 @@
1
+ from sqlalchemy import Boolean, String
2
+ from sqlalchemy.orm import Mapped, mapped_column
3
+
4
+ from app.modeles.base import Base, HorodatageMixin
5
+
6
+ ROLE_UTILISATEUR = "utilisateur"
7
+ ROLE_ADMIN = "admin"
8
+
9
+
10
+ class Utilisateur(HorodatageMixin, Base):
11
+ __tablename__ = "utilisateurs"
12
+
13
+ id: Mapped[int] = mapped_column(primary_key=True)
14
+ email: Mapped[str] = mapped_column(String(255), unique=True, index=True)
15
+ nom_complet: Mapped[str] = mapped_column(String(255))
16
+ mot_de_passe_hache: Mapped[str] = mapped_column(String(255))
17
+ role: Mapped[str] = mapped_column(String(50), default=ROLE_UTILISATEUR)
18
+ est_actif: Mapped[bool] = mapped_column(Boolean, default=True)
@@ -0,0 +1,39 @@
1
+ from typing import Annotated
2
+
3
+ from fastapi import APIRouter, Depends, HTTPException, status
4
+ from fastapi.security import OAuth2PasswordRequestForm
5
+
6
+ from app.base_de_donnees import SessionDep
7
+ from app.dependances import UtilisateurCourant
8
+ from app.schemas.auth import Jeton, UtilisateurCreation, UtilisateurLecture
9
+ from app.securite import creer_jeton_acces
10
+ from app.services import auth as service_auth
11
+
12
+ routeur = APIRouter(prefix="/auth", tags=["Authentification"])
13
+
14
+
15
+ @routeur.post("/inscription", response_model=UtilisateurLecture, status_code=status.HTTP_201_CREATED)
16
+ def inscrire(donnees: UtilisateurCreation, session: SessionDep):
17
+ if service_auth.obtenir_par_email(session, donnees.email) is not None:
18
+ raise HTTPException(
19
+ status_code=status.HTTP_409_CONFLICT, detail="Un compte existe déjà avec cet e-mail"
20
+ )
21
+ return service_auth.creer_utilisateur(session, donnees)
22
+
23
+
24
+ @routeur.post("/connexion", response_model=Jeton)
25
+ def connecter(formulaire: Annotated[OAuth2PasswordRequestForm, Depends()], session: SessionDep):
26
+ """Connexion OAuth2 (formulaire) : `username` = e-mail, `password` = mot de passe."""
27
+ utilisateur = service_auth.authentifier(session, formulaire.username, formulaire.password)
28
+ if utilisateur is None:
29
+ raise HTTPException(
30
+ status_code=status.HTTP_401_UNAUTHORIZED,
31
+ detail="E-mail ou mot de passe incorrect",
32
+ headers={"WWW-Authenticate": "Bearer"},
33
+ )
34
+ return Jeton(access_token=creer_jeton_acces(utilisateur.email))
35
+
36
+
37
+ @routeur.get("/moi", response_model=UtilisateurLecture)
38
+ def lire_profil(utilisateur: UtilisateurCourant):
39
+ return utilisateur
@@ -0,0 +1,25 @@
1
+ from datetime import datetime
2
+
3
+ from pydantic import BaseModel, ConfigDict, EmailStr, Field
4
+
5
+
6
+ class UtilisateurCreation(BaseModel):
7
+ email: EmailStr
8
+ nom_complet: str = Field(min_length=1, max_length=255)
9
+ mot_de_passe: str = Field(min_length=8, max_length=128)
10
+
11
+
12
+ class UtilisateurLecture(BaseModel):
13
+ model_config = ConfigDict(from_attributes=True)
14
+
15
+ id: int
16
+ email: EmailStr
17
+ nom_complet: str
18
+ role: str
19
+ est_actif: bool
20
+ cree_le: datetime
21
+
22
+
23
+ class Jeton(BaseModel):
24
+ access_token: str
25
+ token_type: str = "bearer"
@@ -0,0 +1,48 @@
1
+ """Hachage des mots de passe (Argon2) et jetons d'accès JWT."""
2
+
3
+ from datetime import datetime, timedelta, timezone
4
+
5
+ import jwt
6
+ from pwdlib import PasswordHash
7
+
8
+ from app.config import obtenir_parametres
9
+
10
+ _hacheur = PasswordHash.recommended()
11
+
12
+ CLE_PAR_DEFAUT = "changez-moi"
13
+
14
+
15
+ def hacher_mot_de_passe(mot_de_passe: str) -> str:
16
+ return _hacheur.hash(mot_de_passe)
17
+
18
+
19
+ def verifier_mot_de_passe(mot_de_passe: str, hache: str) -> bool:
20
+ return _hacheur.verify(mot_de_passe, hache)
21
+
22
+
23
+ def creer_jeton_acces(sujet: str, duree: timedelta | None = None) -> str:
24
+ """Crée un JWT signé dont le sujet (`sub`) est l'e-mail de l'utilisateur."""
25
+ parametres = obtenir_parametres()
26
+ if parametres.environnement != "developpement" and parametres.cle_secrete == CLE_PAR_DEFAUT:
27
+ raise RuntimeError("CLE_SECRETE doit être définie (autre que la valeur par défaut) hors développement.")
28
+ expiration = datetime.now(timezone.utc) + (
29
+ duree or timedelta(minutes=parametres.duree_jeton_minutes)
30
+ )
31
+ return jwt.encode(
32
+ {"sub": sujet, "exp": expiration},
33
+ parametres.cle_secrete,
34
+ algorithm=parametres.algorithme_jwt,
35
+ )
36
+
37
+
38
+ def decoder_jeton(jeton: str) -> str | None:
39
+ """Retourne le sujet du jeton, ou None s'il est invalide ou expiré."""
40
+ parametres = obtenir_parametres()
41
+ try:
42
+ charge = jwt.decode(
43
+ jeton, parametres.cle_secrete, algorithms=[parametres.algorithme_jwt]
44
+ )
45
+ except jwt.InvalidTokenError:
46
+ return None
47
+ sujet = charge.get("sub")
48
+ return sujet if isinstance(sujet, str) else None
@@ -0,0 +1,41 @@
1
+ """Logique métier de l'authentification."""
2
+
3
+ from sqlalchemy import select
4
+ from sqlalchemy.orm import Session
5
+
6
+ from app.modeles.utilisateur import ROLE_UTILISATEUR, Utilisateur
7
+ from app.schemas.auth import UtilisateurCreation
8
+ from app.securite import hacher_mot_de_passe, verifier_mot_de_passe
9
+
10
+ # Hachage factice : permet de vérifier un mot de passe même quand l'e-mail est inconnu,
11
+ # pour que le temps de réponse ne révèle pas si un compte existe.
12
+ _HACHE_FACTICE = hacher_mot_de_passe("mot-de-passe-factice")
13
+
14
+
15
+ def obtenir_par_email(session: Session, email: str) -> Utilisateur | None:
16
+ return session.scalar(select(Utilisateur).where(Utilisateur.email == email.lower()))
17
+
18
+
19
+ def creer_utilisateur(
20
+ session: Session, donnees: UtilisateurCreation, role: str = ROLE_UTILISATEUR
21
+ ) -> Utilisateur:
22
+ utilisateur = Utilisateur(
23
+ email=donnees.email.lower(),
24
+ nom_complet=donnees.nom_complet,
25
+ mot_de_passe_hache=hacher_mot_de_passe(donnees.mot_de_passe),
26
+ role=role,
27
+ )
28
+ session.add(utilisateur)
29
+ session.commit()
30
+ session.refresh(utilisateur)
31
+ return utilisateur
32
+
33
+
34
+ def authentifier(session: Session, email: str, mot_de_passe: str) -> Utilisateur | None:
35
+ utilisateur = obtenir_par_email(session, email)
36
+ if utilisateur is None:
37
+ verifier_mot_de_passe(mot_de_passe, _HACHE_FACTICE)
38
+ return None
39
+ if not verifier_mot_de_passe(mot_de_passe, utilisateur.mot_de_passe_hache):
40
+ return None
41
+ return utilisateur if utilisateur.est_actif else None