Ajout de l'authentification (compte unique, JWT, reset par email)

Application mono-utilisateur : inscription unique, connexion par JWT (12 h),
protection de toutes les routes de données, réinitialisation de mot de passe
par email avec repli de journalisation, onboarding réorganisé en deux étapes
(inscription → connexion → profil + véhicule).

Backend (SchotzIadKmTracker.Api) :
- Entités Compte (singleton) et ResetPasswordToken + migration AjoutAuthentification.
- Hachage PasswordHasher, JwtService (HS256, durée configurable), IEmailService
  (MailKit + repli LoggingEmailService selon Smtp:Host).
- AuthService (register 409 si compte existant, login 401 générique, forgot-password
  non-divulgation, reset à usage unique + expiration), AuthController (5 endpoints
  publics), DTOs + validateurs FluentValidation.
- Sécurité pipeline : JwtBearer + filtre d'autorisation global, UseAuthentication
  avant UseAuthorization ; /health et /api/auth/* publics.

Frontend (schotziad-km-tracker, zoneless + signals) :
- AuthService (localStorage), authInterceptor (Bearer + purge/redirection 401),
  authGuard, écrans Login/Register/ForgotPassword/ResetPassword, routes publiques
  et protection [authGuard, profilConfigureGuard].

Configuration : .env.example et docker-compose.yml (JWT__SecretKey, durées, Smtp__*).

Tests : 54 tests backend (propriétés FsCheck P1–P14, exemples, intégration
WebApplicationFactory) + tests frontend (AuthService, authGuard, authInterceptor,
ResetPasswordComponent). Suite complète au vert.

Spec : .kiro/specs/authentification (requirements, design, tasks).
This commit is contained in:
2026-09-14 09:07:08 +02:00
parent 0e6a97ca61
commit dd36bbc425
66 changed files with 6282 additions and 27 deletions
@@ -0,0 +1,13 @@
namespace SchotzIadKmTracker.Api.Configuration;
/// <summary>Options de configuration de l'authentification (réinitialisation de mot de passe).</summary>
public class AuthOptions
{
public const string SectionName = "Auth";
/// <summary>Durée de validité d'un jeton de réinitialisation en minutes.</summary>
public int ResetTokenLifetimeMinutes { get; set; } = 60;
/// <summary>URL de base du frontend, utilisée pour construire le lien de réinitialisation.</summary>
public string FrontendBaseUrl { get; set; } = "http://localhost:8080";
}
@@ -0,0 +1,19 @@
namespace SchotzIadKmTracker.Api.Configuration;
/// <summary>Options de configuration des jetons JWT d'authentification.</summary>
public class JwtOptions
{
public const string SectionName = "Jwt";
/// <summary>Clé secrète utilisée pour signer les jetons (HS256).</summary>
public string SecretKey { get; set; } = string.Empty;
/// <summary>Émetteur (issuer) des jetons.</summary>
public string Issuer { get; set; } = "SchotzIadKmTracker";
/// <summary>Audience attendue des jetons.</summary>
public string Audience { get; set; } = "SchotzIadKmTracker";
/// <summary>Durée de validité d'un jeton en minutes (720 = 12 h).</summary>
public int ExpirationMinutes { get; set; } = 720;
}
@@ -0,0 +1,22 @@
namespace SchotzIadKmTracker.Api.Configuration;
/// <summary>Options de configuration du serveur SMTP pour l'envoi d'emails.</summary>
public class SmtpOptions
{
public const string SectionName = "Smtp";
/// <summary>Hôte du serveur SMTP (vide = envoi désactivé, repli sur la journalisation).</summary>
public string Host { get; set; } = string.Empty;
/// <summary>Port du serveur SMTP.</summary>
public int Port { get; set; } = 587;
/// <summary>Nom d'utilisateur pour l'authentification SMTP.</summary>
public string User { get; set; } = string.Empty;
/// <summary>Mot de passe pour l'authentification SMTP.</summary>
public string Password { get; set; } = string.Empty;
/// <summary>Adresse email expéditrice.</summary>
public string From { get; set; } = string.Empty;
}
@@ -0,0 +1,132 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SchotzIadKmTracker.Api.Models.DTOs;
using SchotzIadKmTracker.Api.Services;
using SchotzIadKmTracker.Api.Services.Exceptions;
namespace SchotzIadKmTracker.Api.Controllers;
/// <summary>
/// Endpoints publics d'authentification de l'application mono-utilisateur :
/// inscription, connexion, demande et application de la réinitialisation du
/// mot de passe, ainsi que la vérification de l'existence du compte.
/// Toutes les routes sont anonymes (<see cref="AllowAnonymousAttribute"/>) : elles
/// restent accessibles même une fois l'autorisation globale activée (Exigence 9.1).
/// Les erreurs sont renvoyées au format <c>ProblemDetails</c>, comme les autres controllers.
/// </summary>
[ApiController]
[Route("api/auth")]
[AllowAnonymous]
public class AuthController : ControllerBase
{
private readonly IAuthService _authService;
public AuthController(IAuthService authService)
{
_authService = authService;
}
/// <summary>
/// Inscrit le compte unique de l'application. Les erreurs de validation
/// (email invalide, mot de passe trop court) sont renvoyées automatiquement
/// en 400 par FluentValidation (Exigences 1.3, 1.4). Un compte déjà existant
/// est rejeté en 409 (Exigence 1.2).
/// </summary>
[HttpPost("register")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public async Task<IActionResult> Register(
[FromBody] RegisterDto dto,
CancellationToken cancellationToken)
{
try
{
await _authService.RegisterAsync(dto, cancellationToken);
return Ok();
}
catch (CompteDejaExistantException ex)
{
return Problem(detail: ex.Message, statusCode: StatusCodes.Status409Conflict);
}
}
/// <summary>
/// Authentifie le compte et retourne le jeton JWT accompagné de sa date
/// d'expiration. En cas d'identifiants invalides, renvoie un 401 avec un
/// message générique afin de ne pas distinguer email inconnu et mot de passe
/// erroné (Exigences 2.1, 2.2).
/// </summary>
[HttpPost("login")]
[ProducesResponseType(typeof(LoginResultDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public async Task<ActionResult<LoginResultDto>> Login(
[FromBody] LoginDto dto,
CancellationToken cancellationToken)
{
try
{
var resultat = await _authService.LoginAsync(dto, cancellationToken);
return Ok(resultat);
}
catch (IdentifiantsInvalidesException)
{
return Problem(detail: "Identifiants invalides.", statusCode: StatusCodes.Status401Unauthorized);
}
}
/// <summary>
/// Traite une demande de réinitialisation de mot de passe. Par principe de
/// non-divulgation, renvoie toujours 200 avec la même réponse, que l'email
/// corresponde ou non à un compte (Exigence 6.6). La logique de non-divulgation
/// est portée par le service ; les erreurs techniques réelles remontent.
/// </summary>
[HttpPost("forgot-password")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> ForgotPassword(
[FromBody] ForgotPasswordDto dto,
CancellationToken cancellationToken)
{
await _authService.ForgotPasswordAsync(dto, cancellationToken);
return Ok();
}
/// <summary>
/// Réinitialise le mot de passe à partir d'un jeton de réinitialisation.
/// Un jeton expiré (Exigence 7.3) ou invalide/déjà utilisé (Exigence 7.4)
/// est rejeté en 400. Les erreurs de validation du nouveau mot de passe sont
/// renvoyées automatiquement en 400 par FluentValidation (Exigence 7.5).
/// </summary>
[HttpPost("reset-password")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ResetPassword(
[FromBody] ResetPasswordDto dto,
CancellationToken cancellationToken)
{
try
{
await _authService.ResetPasswordAsync(dto, cancellationToken);
return Ok();
}
catch (LienResetExpireException)
{
return Problem(detail: "Le lien de réinitialisation a expiré.", statusCode: StatusCodes.Status400BadRequest);
}
catch (LienResetInvalideException)
{
return Problem(detail: "Le lien de réinitialisation est invalide.", statusCode: StatusCodes.Status400BadRequest);
}
}
/// <summary>
/// Indique si un compte existe déjà, afin d'orienter le frontend entre
/// inscription et connexion (Exigences 1.2, 9.1).
/// </summary>
[HttpGet("compte-existe")]
[ProducesResponseType(typeof(CompteExisteDto), StatusCodes.Status200OK)]
public async Task<ActionResult<CompteExisteDto>> CompteExiste(CancellationToken cancellationToken)
{
return Ok(new CompteExisteDto(await _authService.CompteExisteAsync(cancellationToken)));
}
}
@@ -20,6 +20,8 @@ public class AppDbContext : DbContext
public DbSet<AdresseNommee> AdressesNommees => Set<AdresseNommee>();
public DbSet<TrancheBareme> TranchesBareme => Set<TrancheBareme>();
public DbSet<MontantRegle> MontantsRegles => Set<MontantRegle>();
public DbSet<Compte> Comptes => Set<Compte>();
public DbSet<ResetPasswordToken> ResetPasswordTokens => Set<ResetPasswordToken>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
@@ -110,5 +112,22 @@ public class AppDbContext : DbContext
.HasForeignKey(m => m.VehiculeId)
.OnDelete(DeleteBehavior.Restrict);
});
// --- Comptes (singleton Id = 1) ---
modelBuilder.Entity<Compte>(entity =>
{
entity.ToTable("Comptes");
entity.HasKey(c => c.Id);
entity.Property(c => c.Id).ValueGeneratedNever();
entity.HasIndex(c => c.Email, "UX_Comptes_Email").IsUnique();
});
// --- ResetPasswordTokens (jetons de réinitialisation à usage unique) ---
modelBuilder.Entity<ResetPasswordToken>(entity =>
{
entity.ToTable("ResetPasswordTokens");
entity.HasIndex(t => t.TokenHash, "UX_ResetTokens_TokenHash").IsUnique();
entity.HasIndex(t => t.Expiration, "IX_ResetTokens_Expiration");
});
}
}
@@ -0,0 +1,390 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SchotzIadKmTracker.Api.Data;
#nullable disable
namespace SchotzIadKmTracker.Api.Data.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260914064431_AjoutAuthentification")]
partial class AjoutAuthentification
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "8.0.8");
modelBuilder.Entity("SchotzIadKmTracker.Api.Models.Entities.AdresseCache", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Adresse")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("TEXT");
b.Property<DateTime>("DerniereUtilisation")
.HasColumnType("TEXT");
b.Property<string>("GeometrieJson")
.HasColumnType("TEXT");
b.Property<double>("Latitude")
.HasColumnType("REAL");
b.Property<double>("Longitude")
.HasColumnType("REAL");
b.HasKey("Id");
b.HasIndex("Adresse")
.IsUnique();
b.ToTable("AdresseCache", (string)null);
});
modelBuilder.Entity("SchotzIadKmTracker.Api.Models.Entities.AdresseNommee", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Adresse")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("Denomination")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<string>("DenominationNormalisee")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<bool>("GeocodageReussi")
.HasColumnType("INTEGER");
b.Property<double?>("Latitude")
.HasColumnType("REAL");
b.Property<double?>("Longitude")
.HasColumnType("REAL");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex(new[] { "DenominationNormalisee" }, "UX_AdresseNommee_Denomination")
.IsUnique();
b.ToTable("AdressesNommees", (string)null);
});
modelBuilder.Entity("SchotzIadKmTracker.Api.Models.Entities.Compte", b =>
{
b.Property<int>("Id")
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("TEXT");
b.Property<string>("MotDePasseHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex(new[] { "Email" }, "UX_Comptes_Email")
.IsUnique();
b.ToTable("Comptes", (string)null);
});
modelBuilder.Entity("SchotzIadKmTracker.Api.Models.Entities.MontantRegle", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("Annee")
.HasColumnType("INTEGER");
b.Property<int>("Mois")
.HasColumnType("INTEGER");
b.Property<decimal>("Montant")
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.Property<int>("VehiculeId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("VehiculeId");
b.HasIndex(new[] { "Annee", "Mois", "VehiculeId" }, "UX_MontantsRegles_Periode_Vehicule")
.IsUnique();
b.ToTable("MontantsRegles", null, t =>
{
t.HasCheckConstraint("CK_MontantsRegles_Mois", "\"Mois\" BETWEEN 1 AND 12");
t.HasCheckConstraint("CK_MontantsRegles_Montant", "\"Montant\" >= 0");
});
});
modelBuilder.Entity("SchotzIadKmTracker.Api.Models.Entities.Profil", b =>
{
b.Property<int>("Id")
.HasColumnType("INTEGER");
b.Property<string>("AdresseDomicile")
.HasMaxLength(255)
.HasColumnType("TEXT");
b.Property<bool>("DomicileGeocode")
.HasColumnType("INTEGER");
b.Property<double?>("DomicileLatitude")
.HasColumnType("REAL");
b.Property<double?>("DomicileLongitude")
.HasColumnType("REAL");
b.Property<string>("Matricule")
.HasMaxLength(8)
.HasColumnType("TEXT");
b.Property<string>("Nom")
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<string>("Prenom")
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex(new[] { "Id" }, "UX_Profil_Singleton")
.IsUnique();
b.ToTable("Profil", (string)null);
});
modelBuilder.Entity("SchotzIadKmTracker.Api.Models.Entities.ResetPasswordToken", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTime>("Expiration")
.HasColumnType("TEXT");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<DateTime?>("UsedAt")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex(new[] { "Expiration" }, "IX_ResetTokens_Expiration");
b.HasIndex(new[] { "TokenHash" }, "UX_ResetTokens_TokenHash")
.IsUnique();
b.ToTable("ResetPasswordTokens", (string)null);
});
modelBuilder.Entity("SchotzIadKmTracker.Api.Models.Entities.Trajet", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("AdresseArrivee")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("TEXT");
b.Property<string>("AdresseDepart")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("TEXT");
b.Property<string>("Commentaire")
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateOnly>("Date")
.HasColumnType("TEXT");
b.Property<decimal?>("Distance")
.HasColumnType("TEXT");
b.Property<string>("GeometrieJson")
.HasColumnType("TEXT");
b.Property<decimal>("Position")
.HasColumnType("TEXT");
b.Property<int>("PuissanceFiscale")
.HasColumnType("INTEGER");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.Property<int>("VehiculeId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex(new[] { "Date" }, "IX_Trajets_Date");
b.HasIndex(new[] { "Date", "Position" }, "IX_Trajets_Date_Position");
b.HasIndex(new[] { "VehiculeId" }, "IX_Trajets_Vehicule");
b.ToTable("Trajets", null, t =>
{
t.HasCheckConstraint("CK_Trajets_Distance", "\"Distance\" IS NULL OR \"Distance\" > 0");
t.HasCheckConstraint("CK_Trajets_PuissanceFiscale", "\"PuissanceFiscale\" > 0");
});
});
modelBuilder.Entity("SchotzIadKmTracker.Api.Models.Entities.TrancheBareme", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("Annee")
.HasColumnType("INTEGER");
b.Property<decimal>("Base")
.HasColumnType("TEXT");
b.Property<decimal>("Coefficient")
.HasColumnType("TEXT");
b.Property<decimal?>("KmMax")
.HasColumnType("TEXT");
b.Property<decimal>("KmMin")
.HasColumnType("TEXT");
b.Property<int>("PuissanceFiscale")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex(new[] { "Annee", "PuissanceFiscale" }, "IX_TranchesBareme_Annee_PF");
b.ToTable("TranchesBareme", null, t =>
{
t.HasCheckConstraint("CK_TranchesBareme_Km", "\"KmMax\" IS NULL OR CAST(\"KmMin\" AS REAL) < CAST(\"KmMax\" AS REAL)");
});
});
modelBuilder.Entity("SchotzIadKmTracker.Api.Models.Entities.Vehicule", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateOnly>("DateEffet")
.HasColumnType("TEXT");
b.Property<string>("Denomination")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<string>("Plaque")
.IsRequired()
.HasMaxLength(15)
.HasColumnType("TEXT");
b.Property<int>("PuissanceFiscale")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex(new[] { "DateEffet" }, "IX_Vehicules_DateEffet");
b.ToTable("Vehicules", null, t =>
{
t.HasCheckConstraint("CK_Vehicules_PuissanceFiscale", "\"PuissanceFiscale\" > 0");
});
});
modelBuilder.Entity("SchotzIadKmTracker.Api.Models.Entities.MontantRegle", b =>
{
b.HasOne("SchotzIadKmTracker.Api.Models.Entities.Vehicule", "Vehicule")
.WithMany()
.HasForeignKey("VehiculeId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Vehicule");
});
modelBuilder.Entity("SchotzIadKmTracker.Api.Models.Entities.Trajet", b =>
{
b.HasOne("SchotzIadKmTracker.Api.Models.Entities.Vehicule", "Vehicule")
.WithMany("Trajets")
.HasForeignKey("VehiculeId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Vehicule");
});
modelBuilder.Entity("SchotzIadKmTracker.Api.Models.Entities.Vehicule", b =>
{
b.Navigation("Trajets");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,73 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SchotzIadKmTracker.Api.Data.Migrations
{
/// <inheritdoc />
public partial class AjoutAuthentification : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Comptes",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false),
Email = table.Column<string>(type: "TEXT", maxLength: 255, nullable: false),
MotDePasseHash = table.Column<string>(type: "TEXT", nullable: false),
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Comptes", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ResetPasswordTokens",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
TokenHash = table.Column<string>(type: "TEXT", nullable: false),
Expiration = table.Column<DateTime>(type: "TEXT", nullable: false),
UsedAt = table.Column<DateTime>(type: "TEXT", nullable: true),
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ResetPasswordTokens", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "UX_Comptes_Email",
table: "Comptes",
column: "Email",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_ResetTokens_Expiration",
table: "ResetPasswordTokens",
column: "Expiration");
migrationBuilder.CreateIndex(
name: "UX_ResetTokens_TokenHash",
table: "ResetPasswordTokens",
column: "TokenHash",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Comptes");
migrationBuilder.DropTable(
name: "ResetPasswordTokens");
}
}
}
@@ -92,6 +92,34 @@ namespace SchotzIadKmTracker.Api.Data.Migrations
b.ToTable("AdressesNommees", (string)null);
});
modelBuilder.Entity("SchotzIadKmTracker.Api.Models.Entities.Compte", b =>
{
b.Property<int>("Id")
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("TEXT");
b.Property<string>("MotDePasseHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex(new[] { "Email" }, "UX_Comptes_Email")
.IsUnique();
b.ToTable("Comptes", (string)null);
});
modelBuilder.Entity("SchotzIadKmTracker.Api.Models.Entities.MontantRegle", b =>
{
b.Property<int>("Id")
@@ -169,6 +197,35 @@ namespace SchotzIadKmTracker.Api.Data.Migrations
b.ToTable("Profil", (string)null);
});
modelBuilder.Entity("SchotzIadKmTracker.Api.Models.Entities.ResetPasswordToken", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTime>("Expiration")
.HasColumnType("TEXT");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<DateTime?>("UsedAt")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex(new[] { "Expiration" }, "IX_ResetTokens_Expiration");
b.HasIndex(new[] { "TokenHash" }, "UX_ResetTokens_TokenHash")
.IsUnique();
b.ToTable("ResetPasswordTokens", (string)null);
});
modelBuilder.Entity("SchotzIadKmTracker.Api.Models.Entities.Trajet", b =>
{
b.Property<int>("Id")
@@ -0,0 +1,21 @@
namespace SchotzIadKmTracker.Api.Models.DTOs;
// DTOs d'authentification. Aucun n'expose le hash du mot de passe (Requirement 8.2).
// Inscription du compte unique (Requirement 1).
public record RegisterDto(string Email, string MotDePasse);
// Connexion (Requirement 2).
public record LoginDto(string Email, string MotDePasse);
// Réponse de connexion : jeton JWT et date d'expiration (Requirement 2.1, 2.4).
public record LoginResultDto(string Token, DateTime Expiration);
// Demande de réinitialisation de mot de passe (Requirement 6).
public record ForgotPasswordDto(string Email);
// Réinitialisation via jeton de reset (Requirement 7).
public record ResetPasswordDto(string Token, string NouveauMotDePasse);
// Indique si un compte existe déjà, pour orienter le frontend (Requirement 1.2, 9.1).
public record CompteExisteDto(bool Existe);
@@ -0,0 +1,24 @@
using System.ComponentModel.DataAnnotations;
namespace SchotzIadKmTracker.Api.Models.Entities;
/// <summary>Compte unique de l'application mono-utilisateur (singleton, comme le Profil).</summary>
public class Compte
{
/// <summary>Identifiant du compte. Valeur fixe (1) non générée : le compte est un singleton.</summary>
public int Id { get; set; } = 1;
/// <summary>Adresse email du compte, unique, utilisée comme identifiant de connexion (1–255 caractères).</summary>
[Required, MaxLength(255)]
public string Email { get; set; } = string.Empty;
/// <summary>Hachage salé du mot de passe (PBKDF2 via <c>PasswordHasher</c>). Jamais exposé ni journalisé (Exigence 8.2).</summary>
[Required]
public string MotDePasseHash { get; set; } = string.Empty;
/// <summary>Date de création du compte (UTC).</summary>
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
/// <summary>Date de dernière modification du compte (UTC), mise à jour notamment lors d'une réinitialisation du mot de passe.</summary>
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
}
@@ -0,0 +1,23 @@
using System.ComponentModel.DataAnnotations;
namespace SchotzIadKmTracker.Api.Models.Entities;
/// <summary>Jeton de réinitialisation de mot de passe à usage unique et à durée de vie limitée.</summary>
public class ResetPasswordToken
{
/// <summary>Identifiant technique du jeton.</summary>
public int Id { get; set; }
/// <summary>Hachage SHA-256 du jeton. Le jeton en clair n'est jamais persisté : seul celui transmis par email permet la réinitialisation.</summary>
[Required]
public string TokenHash { get; set; } = string.Empty;
/// <summary>Date d'expiration du jeton (UTC). Au-delà, le jeton est rejeté (Exigence 6.2, défaut création + 60 min).</summary>
public DateTime Expiration { get; set; }
/// <summary>Date d'utilisation du jeton (UTC). <c>null</c> tant que le jeton n'a pas servi ; renseignée à l'usage pour garantir l'usage unique (Exigence 7.2).</summary>
public DateTime? UsedAt { get; set; }
/// <summary>Date de création du jeton (UTC).</summary>
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}
+54 -1
View File
@@ -1,9 +1,14 @@
using System.Text;
using FluentValidation;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using SchotzIadKmTracker.Api.Data;
using SchotzIadKmTracker.Api.Models.Entities;
using SchotzIadKmTracker.Api.Validators;
using SchotzIadKmTracker.Api.Configuration;
@@ -20,6 +25,12 @@ builder.Services.Configure<BANOptions>(
builder.Configuration.GetSection(BANOptions.SectionName));
builder.Services.Configure<ORSOptions>(
builder.Configuration.GetSection(ORSOptions.SectionName));
builder.Services.Configure<JwtOptions>(
builder.Configuration.GetSection(JwtOptions.SectionName));
builder.Services.Configure<AuthOptions>(
builder.Configuration.GetSection(AuthOptions.SectionName));
builder.Services.Configure<SmtpOptions>(
builder.Configuration.GetSection(SmtpOptions.SectionName));
// --- Client typé BAN (Base Adresses Nationale) ---
// BaseAddress et Timeout proviennent de BANOptions (appsettings.json).
@@ -70,7 +81,15 @@ builder.Services.AddScoped<IAdresseCacheRepository, AdresseCacheRepository>();
builder.Services.AddScoped<IAdresseCacheService, AdresseCacheService>();
// --- Services de base ---
builder.Services.AddControllers();
// Autorisation GLOBALE par défaut : toutes les routes MVC exigent un utilisateur authentifié.
// AuthController porte [AllowAnonymous] ; /health (endpoint minimal) n'est pas couvert par les filtres MVC.
builder.Services.AddControllers(options =>
{
var policy = new Microsoft.AspNetCore.Authorization.AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter(policy));
});
// --- Health checks (endpoint GET /health, utilisé par Docker Compose) ---
builder.Services.AddHealthChecks();
@@ -87,7 +106,39 @@ var connectionString = builder.Configuration.GetConnectionString("Default")
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlite(connectionString));
// --- Hachage des mots de passe (ASP.NET Core Identity PasswordHasher) ---
builder.Services.AddSingleton<IPasswordHasher<Compte>, PasswordHasher<Compte>>();
// --- Repositories & services métier ---
builder.Services.AddScoped<IJwtService, JwtService>();
// --- Sélection de l'implémentation Email selon la présence de config SMTP ---
var smtpOptions = builder.Configuration.GetSection(SmtpOptions.SectionName).Get<SmtpOptions>() ?? new SmtpOptions();
if (string.IsNullOrWhiteSpace(smtpOptions.Host))
builder.Services.AddScoped<IEmailService, LoggingEmailService>(); // repli journalisation (Exigence 6.5)
else
builder.Services.AddScoped<IEmailService, SmtpEmailService>(); // MailKit (Exigence 6.4)
builder.Services.AddScoped<IAuthService, AuthService>();
// --- Authentification JWT Bearer ---
var jwtOptions = builder.Configuration.GetSection(JwtOptions.SectionName).Get<JwtOptions>() ?? new JwtOptions();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true, // rejette les jetons expirés (Exigence 5.2)
ValidateIssuerSigningKey = true, // rejette les signatures invalides (Exigence 5.3)
ValidIssuer = jwtOptions.Issuer,
ValidAudience = jwtOptions.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.SecretKey)),
ClockSkew = TimeSpan.FromSeconds(30) // tolérance d'horloge réduite
};
});
builder.Services.AddScoped<SchotzIadKmTracker.Api.Repositories.IVehiculeRepository,
SchotzIadKmTracker.Api.Repositories.VehiculeRepository>();
builder.Services.AddScoped<IVehiculeService, VehiculeService>();
@@ -152,6 +203,8 @@ app.UseHttpsRedirection();
app.UseCors(CorsPolicyName);
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
@@ -9,6 +9,8 @@
<ItemGroup>
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.0" />
<PackageReference Include="MailKit" Version="4.18.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.8">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
@@ -17,6 +19,7 @@
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.8" />
<PackageReference Include="QuestPDF" Version="2024.10.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.22.0" />
</ItemGroup>
</Project>
@@ -0,0 +1,217 @@
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using SchotzIadKmTracker.Api.Configuration;
using SchotzIadKmTracker.Api.Data;
using SchotzIadKmTracker.Api.Models.DTOs;
using SchotzIadKmTracker.Api.Models.Entities;
using SchotzIadKmTracker.Api.Services.Exceptions;
namespace SchotzIadKmTracker.Api.Services;
/// <inheritdoc />
public class AuthService : IAuthService
{
private readonly AppDbContext _context;
private readonly IPasswordHasher<Compte> _hasher;
private readonly IJwtService _jwt;
private readonly IEmailService _email;
private readonly AuthOptions _authOptions;
private readonly JwtOptions _jwtOptions;
private readonly ILogger<AuthService> _logger;
public AuthService(
AppDbContext context,
IPasswordHasher<Compte> hasher,
IJwtService jwt,
IEmailService email,
IOptions<AuthOptions> authOptions,
IOptions<JwtOptions> jwtOptions,
ILogger<AuthService> logger)
{
_context = context;
_hasher = hasher;
_jwt = jwt;
_email = email;
_authOptions = authOptions.Value;
_jwtOptions = jwtOptions.Value;
_logger = logger;
}
/// <inheritdoc />
public async Task<bool> CompteExisteAsync(CancellationToken ct)
{
// Vrai s'il existe au moins un compte (Exigences 1.2, 9.1).
return await _context.Comptes.AnyAsync(ct);
}
/// <inheritdoc />
public async Task RegisterAsync(RegisterDto dto, CancellationToken ct)
{
// L'application est mono-utilisateur : refus si un compte existe déjà (Exigence 1.2).
if (await _context.Comptes.AnyAsync(ct))
{
throw new CompteDejaExistantException("Un compte existe déjà.");
}
// La longueur >= 8 et la validité de l'email sont garanties par FluentValidation en amont.
var compte = new Compte
{
Id = 1, // singleton
Email = dto.Email.Trim(),
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow,
};
// Hachage salé du mot de passe (PBKDF2 via PasswordHasher). Le clair n'est jamais persisté (Exigence 8).
compte.MotDePasseHash = _hasher.HashPassword(compte, dto.MotDePasse);
_context.Comptes.Add(compte);
await _context.SaveChangesAsync(ct);
}
/// <inheritdoc />
public async Task<LoginResultDto> LoginAsync(LoginDto dto, CancellationToken ct)
{
var email = dto.Email.Trim();
// Récupération du compte par email (comparaison insensible à la casse).
var compte = await _context.Comptes
.FirstOrDefaultAsync(c => c.Email.ToLower() == email.ToLower(), ct);
// Message générique : ne distingue pas email inconnu et mot de passe erroné (Exigence 2.2).
if (compte is null)
{
throw new IdentifiantsInvalidesException("Identifiants invalides.");
}
var resultat = _hasher.VerifyHashedPassword(compte, compte.MotDePasseHash, dto.MotDePasse);
if (resultat == PasswordVerificationResult.Failed)
{
throw new IdentifiantsInvalidesException("Identifiants invalides.");
}
// Émission du jeton JWT et de sa date d'expiration (Exigences 2.1, 2.4).
var token = _jwt.GenererJeton(compte);
var expiration = DateTime.UtcNow.AddMinutes(_jwtOptions.ExpirationMinutes);
return new LoginResultDto(token, expiration);
}
/// <inheritdoc />
public async Task ForgotPasswordAsync(ForgotPasswordDto dto, CancellationToken ct)
{
var email = dto.Email.Trim();
// Principe de non-divulgation (Exigence 6.6) : on ne révèle jamais si l'email correspond à un compte.
// La méthode se termine toujours sans exception ; le controller renvoie une réponse générique 200.
var compte = await _context.Comptes
.FirstOrDefaultAsync(c => c.Email.ToLower() == email.ToLower(), ct);
if (compte is null)
{
// Email inconnu : aucune action, aucun jeton créé.
return;
}
// Génération d'un jeton aléatoire sûr (32 octets), transmis EN CLAIR dans le lien.
var tokenClair = GenererTokenAleatoire();
// Seul le hachage SHA-256 du jeton est persisté (Exigence 6 / 7).
var resetToken = new ResetPasswordToken
{
TokenHash = HacherToken(tokenClair),
Expiration = DateTime.UtcNow.AddMinutes(_authOptions.ResetTokenLifetimeMinutes),
UsedAt = null,
CreatedAt = DateTime.UtcNow,
};
_context.ResetPasswordTokens.Add(resetToken);
await _context.SaveChangesAsync(ct);
// Construction du lien de réinitialisation (token en clair) et envoi par email.
var lien = $"{_authOptions.FrontendBaseUrl}/reset-password?token={tokenClair}";
await _email.EnvoyerLienResetAsync(compte.Email, lien, ct);
}
/// <inheritdoc />
public async Task ResetPasswordAsync(ResetPasswordDto dto, CancellationToken ct)
{
// Recherche du jeton par son hachage SHA-256 (le clair n'est jamais persisté).
var tokenHash = HacherToken(dto.Token);
var resetToken = await _context.ResetPasswordTokens
.FirstOrDefaultAsync(t => t.TokenHash == tokenHash, ct);
// Jeton inconnu ou déjà utilisé : invalide (usage unique, Exigences 7.2, 7.4).
if (resetToken is null || resetToken.UsedAt is not null)
{
throw new LienResetInvalideException("Le lien de réinitialisation est invalide.");
}
// Jeton expiré (Exigence 7.3).
if (resetToken.Expiration < DateTime.UtcNow)
{
throw new LienResetExpireException("Le lien de réinitialisation a expiré.");
}
var compte = await _context.Comptes.FirstOrDefaultAsync(ct);
if (compte is null)
{
// Cas théorique : jeton présent mais aucun compte. On traite comme un lien invalide.
throw new LienResetInvalideException("Le lien de réinitialisation est invalide.");
}
// Mise à jour du mot de passe et invalidation du jeton (usage unique), en transaction
// car plusieurs écritures doivent aboutir de façon atomique.
var maintenant = DateTime.UtcNow;
await using var transaction = await _context.Database.BeginTransactionAsync(ct);
try
{
// La longueur >= 8 du nouveau mot de passe est garantie par FluentValidation en amont.
compte.MotDePasseHash = _hasher.HashPassword(compte, dto.NouveauMotDePasse);
compte.UpdatedAt = maintenant;
resetToken.UsedAt = maintenant;
await _context.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
}
catch
{
await transaction.RollbackAsync(ct);
throw;
}
}
/// <summary>
/// Génère un jeton aléatoire cryptographiquement sûr (32 octets) encodé en base64url.
/// </summary>
private static string GenererTokenAleatoire()
{
var octets = RandomNumberGenerator.GetBytes(32);
return Base64UrlEncode(octets);
}
/// <summary>
/// Calcule le hachage SHA-256 d'un jeton et le retourne en base64.
/// </summary>
private static string HacherToken(string token)
{
var octets = SHA256.HashData(Encoding.UTF8.GetBytes(token));
return Convert.ToBase64String(octets);
}
/// <summary>
/// Encode des octets en base64url (sans remplissage), adapté à une transmission en query string.
/// </summary>
private static string Base64UrlEncode(byte[] octets)
{
return Convert.ToBase64String(octets)
.TrimEnd('=')
.Replace('+', '-')
.Replace('/', '_');
}
}
@@ -0,0 +1,19 @@
namespace SchotzIadKmTracker.Api.Services.Exceptions;
/// <summary>
/// Levée lorsqu'une tentative d'inscription est effectuée alors qu'un compte existe déjà.
/// L'application étant mono-utilisateur, un seul compte peut être créé.
/// Convertie en réponse HTTP 409 (Conflict) par le controller (Exigence 1.2).
/// </summary>
public class CompteDejaExistantException : Exception
{
public CompteDejaExistantException(string message)
: base(message)
{
}
public CompteDejaExistantException(string message, Exception innerException)
: base(message, innerException)
{
}
}
@@ -0,0 +1,19 @@
namespace SchotzIadKmTracker.Api.Services.Exceptions;
/// <summary>
/// Levée lorsque les identifiants de connexion sont invalides (email inconnu ou mot de passe erroné).
/// Le message est volontairement générique afin de ne pas distinguer les deux cas (Exigence 2.2).
/// Convertie en réponse HTTP 401 (Unauthorized) par le controller.
/// </summary>
public class IdentifiantsInvalidesException : Exception
{
public IdentifiantsInvalidesException(string message)
: base(message)
{
}
public IdentifiantsInvalidesException(string message, Exception innerException)
: base(message, innerException)
{
}
}
@@ -0,0 +1,18 @@
namespace SchotzIadKmTracker.Api.Services.Exceptions;
/// <summary>
/// Levée lorsqu'un jeton de réinitialisation a expiré (date d'expiration dépassée).
/// Convertie en réponse HTTP 400 (Bad Request) par le controller (Exigence 7.3).
/// </summary>
public class LienResetExpireException : Exception
{
public LienResetExpireException(string message)
: base(message)
{
}
public LienResetExpireException(string message, Exception innerException)
: base(message, innerException)
{
}
}
@@ -0,0 +1,18 @@
namespace SchotzIadKmTracker.Api.Services.Exceptions;
/// <summary>
/// Levée lorsqu'un jeton de réinitialisation est inconnu ou a déjà été utilisé (usage unique).
/// Convertie en réponse HTTP 400 (Bad Request) par le controller (Exigences 7.2, 7.4).
/// </summary>
public class LienResetInvalideException : Exception
{
public LienResetInvalideException(string message)
: base(message)
{
}
public LienResetInvalideException(string message, Exception innerException)
: base(message, innerException)
{
}
}
@@ -0,0 +1,52 @@
using SchotzIadKmTracker.Api.Models.DTOs;
namespace SchotzIadKmTracker.Api.Services;
/// <summary>
/// Logique métier d'authentification de l'application mono-utilisateur :
/// existence du compte, inscription, connexion, demande et application de la
/// réinitialisation du mot de passe.
/// </summary>
public interface IAuthService
{
/// <summary>
/// Indique si un compte existe déjà, afin d'orienter le frontend (inscription vs connexion).
/// </summary>
/// <param name="ct">Jeton d'annulation de l'opération.</param>
/// <returns><c>true</c> s'il existe au moins un compte, <c>false</c> sinon (Exigences 1.2, 9.1).</returns>
Task<bool> CompteExisteAsync(CancellationToken ct);
/// <summary>
/// Inscrit le compte unique. Lève <see cref="Exceptions.CompteDejaExistantException"/>
/// si un compte existe déjà (Exigence 1).
/// </summary>
/// <param name="dto">Email et mot de passe fournis à l'inscription.</param>
/// <param name="ct">Jeton d'annulation de l'opération.</param>
Task RegisterAsync(RegisterDto dto, CancellationToken ct);
/// <summary>
/// Authentifie le compte et émet un jeton JWT. Lève
/// <see cref="Exceptions.IdentifiantsInvalidesException"/> si les identifiants sont invalides (Exigence 2).
/// </summary>
/// <param name="dto">Identifiants de connexion (email et mot de passe).</param>
/// <param name="ct">Jeton d'annulation de l'opération.</param>
/// <returns>Le jeton JWT émis et sa date d'expiration.</returns>
Task<LoginResultDto> LoginAsync(LoginDto dto, CancellationToken ct);
/// <summary>
/// Traite une demande de réinitialisation de mot de passe. Par principe de non-divulgation,
/// se termine toujours sans exception, que l'email corresponde ou non à un compte (Exigence 6.6).
/// </summary>
/// <param name="dto">Email pour lequel demander la réinitialisation.</param>
/// <param name="ct">Jeton d'annulation de l'opération.</param>
Task ForgotPasswordAsync(ForgotPasswordDto dto, CancellationToken ct);
/// <summary>
/// Réinitialise le mot de passe à partir d'un jeton de réinitialisation. Lève
/// <see cref="Exceptions.LienResetInvalideException"/> si le jeton est inconnu ou déjà utilisé,
/// <see cref="Exceptions.LienResetExpireException"/> s'il a expiré (Exigence 7).
/// </summary>
/// <param name="dto">Jeton de réinitialisation et nouveau mot de passe.</param>
/// <param name="ct">Jeton d'annulation de l'opération.</param>
Task ResetPasswordAsync(ResetPasswordDto dto, CancellationToken ct);
}
@@ -0,0 +1,18 @@
namespace SchotzIadKmTracker.Api.Services;
/// <summary>
/// Service d'envoi d'emails de l'application. L'implémentation concrète
/// (SMTP via MailKit ou repli par journalisation) est sélectionnée en DI
/// dans <c>Program.cs</c> selon la présence d'une configuration SMTP.
/// Le service appelant ignore l'implémentation retenue (transparence).
/// </summary>
public interface IEmailService
{
/// <summary>
/// Envoie au destinataire le lien de réinitialisation de mot de passe.
/// </summary>
/// <param name="destinataire">Adresse email du destinataire.</param>
/// <param name="lienReset">Lien de réinitialisation à transmettre au destinataire.</param>
/// <param name="ct">Jeton d'annulation de l'opération.</param>
Task EnvoyerLienResetAsync(string destinataire, string lienReset, CancellationToken ct);
}
@@ -0,0 +1,24 @@
using SchotzIadKmTracker.Api.Models.Entities;
namespace SchotzIadKmTracker.Api.Services;
/// <summary>
/// Service d'émission des jetons JWT d'authentification.
/// </summary>
public interface IJwtService
{
/// <summary>
/// Émet un Jeton_JWT signé en HS256 pour le compte fourni.
/// </summary>
/// <remarks>
/// Le jeton porte les claims <c>sub</c> (identifiant du compte), <c>email</c> et un
/// identifiant unique <c>jti</c>. Sa date d'expiration vaut l'instant courant plus
/// <c>JwtOptions.ExpirationMinutes</c> (720 minutes / 12 h par défaut). Aucune donnée
/// sensible n'est incluse (jamais le hachage du mot de passe).
/// Exigences 2.1 (émission du jeton à la connexion), 2.4 (date d'expiration associée),
/// 5.4 (expiration à 12 h par défaut).
/// </remarks>
/// <param name="compte">Le compte pour lequel émettre le jeton.</param>
/// <returns>Le Jeton_JWT sérialisé (chaîne compacte).</returns>
string GenererJeton(Compte compte);
}
@@ -0,0 +1,57 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using SchotzIadKmTracker.Api.Configuration;
using SchotzIadKmTracker.Api.Models.Entities;
namespace SchotzIadKmTracker.Api.Services;
/// <summary>
/// Implémentation de <see cref="IJwtService"/> émettant des jetons JWT signés en HMAC-SHA256
/// à partir des options <see cref="JwtOptions"/>.
/// </summary>
public class JwtService : IJwtService
{
private readonly JwtOptions _options;
/// <summary>
/// Initialise le service à partir des options JWT liées à la configuration.
/// </summary>
/// <param name="options">Options JWT (clé secrète, émetteur, audience, durée d'expiration).</param>
public JwtService(IOptions<JwtOptions> options)
{
_options = options.Value;
}
/// <inheritdoc />
public string GenererJeton(Compte compte)
{
// Claims émis : sub = identifiant du compte, email = adresse du compte,
// jti = identifiant unique du jeton. Aucune donnée sensible (jamais le hash du mot de passe).
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, compte.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Email, compte.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
// Signature symétrique HMAC-SHA256 à partir de la clé secrète configurée.
var cleSignature = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.SecretKey));
var identifiants = new SigningCredentials(cleSignature, SecurityAlgorithms.HmacSha256);
// Expiration = instant courant + durée configurée (720 min / 12 h par défaut).
var expiration = DateTime.UtcNow.AddMinutes(_options.ExpirationMinutes);
var jeton = new JwtSecurityToken(
issuer: _options.Issuer,
audience: _options.Audience,
claims: claims,
notBefore: DateTime.UtcNow,
expires: expiration,
signingCredentials: identifiants);
return new JwtSecurityTokenHandler().WriteToken(jeton);
}
}
@@ -0,0 +1,26 @@
namespace SchotzIadKmTracker.Api.Services;
/// <summary>
/// Implémentation de repli de <see cref="IEmailService"/> qui n'envoie aucun
/// email mais journalise le lien de réinitialisation via <see cref="ILogger"/>
/// au niveau <c>Information</c>. Utilisée lorsqu'aucun serveur SMTP n'est
/// configuré (<c>Smtp:Host</c> vide), notamment en développement.
/// </summary>
public class LoggingEmailService : IEmailService
{
private readonly ILogger<LoggingEmailService> _logger;
public LoggingEmailService(ILogger<LoggingEmailService> logger)
{
_logger = logger;
}
/// <inheritdoc />
public Task EnvoyerLienResetAsync(string destinataire, string lienReset, CancellationToken ct)
{
_logger.LogInformation(
"Lien de réinitialisation pour {Destinataire} : {LienReset}",
destinataire, lienReset);
return Task.CompletedTask;
}
}
@@ -0,0 +1,69 @@
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Options;
using MimeKit;
using SchotzIadKmTracker.Api.Configuration;
namespace SchotzIadKmTracker.Api.Services;
/// <summary>
/// Implémentation de <see cref="IEmailService"/> reposant sur MailKit pour
/// l'envoi d'emails via un serveur SMTP. La configuration (hôte, port,
/// identifiants, expéditeur) provient de <see cref="SmtpOptions"/>. Cette
/// implémentation est enregistrée en DI lorsque <c>Smtp:Host</c> est renseigné.
/// </summary>
public class SmtpEmailService : IEmailService
{
private readonly SmtpOptions _options;
private readonly ILogger<SmtpEmailService> _logger;
public SmtpEmailService(IOptions<SmtpOptions> options, ILogger<SmtpEmailService> logger)
{
_options = options.Value;
_logger = logger;
}
/// <inheritdoc />
public async Task EnvoyerLienResetAsync(string destinataire, string lienReset, CancellationToken ct)
{
var message = new MimeMessage();
message.From.Add(MailboxAddress.Parse(_options.From));
message.To.Add(MailboxAddress.Parse(destinataire));
message.Subject = "Réinitialisation de votre mot de passe";
var corps = new BodyBuilder
{
TextBody =
"Bonjour,\r\n\r\n" +
"Vous avez demandé la réinitialisation de votre mot de passe.\r\n" +
"Cliquez sur le lien suivant pour définir un nouveau mot de passe :\r\n\r\n" +
lienReset + "\r\n\r\n" +
"Si vous n'êtes pas à l'origine de cette demande, ignorez cet email.",
HtmlBody =
"<p>Bonjour,</p>" +
"<p>Vous avez demandé la réinitialisation de votre mot de passe.</p>" +
"<p>Cliquez sur le lien suivant pour définir un nouveau mot de passe :</p>" +
$"<p><a href=\"{lienReset}\">{lienReset}</a></p>" +
"<p>Si vous n'êtes pas à l'origine de cette demande, ignorez cet email.</p>"
};
message.Body = corps.ToMessageBody();
using var client = new SmtpClient();
_logger.LogInformation(
"Envoi de l'email de réinitialisation à {Destinataire} via {Host}:{Port}.",
destinataire, _options.Host, _options.Port);
await client.ConnectAsync(_options.Host, _options.Port, SecureSocketOptions.StartTls, ct);
if (!string.IsNullOrEmpty(_options.User))
{
await client.AuthenticateAsync(_options.User, _options.Password, ct);
}
await client.SendAsync(message, ct);
await client.DisconnectAsync(true, ct);
_logger.LogInformation(
"Email de réinitialisation envoyé à {Destinataire}.", destinataire);
}
}
@@ -0,0 +1,58 @@
using FluentValidation;
using SchotzIadKmTracker.Api.Models.DTOs;
namespace SchotzIadKmTracker.Api.Validators;
// Validation de l'inscription (Requirements 1.3, 1.4, 8.2).
public class RegisterDtoValidator : AbstractValidator<RegisterDto>
{
public RegisterDtoValidator()
{
RuleFor(x => x.Email)
.NotEmpty().WithMessage("L'adresse email est obligatoire.")
.EmailAddress().WithMessage("Adresse email invalide.");
RuleFor(x => x.MotDePasse)
.NotEmpty().WithMessage("Le mot de passe est obligatoire.")
.MinimumLength(8).WithMessage("Le mot de passe doit comporter au moins 8 caractères.");
}
}
// Validation de la connexion (Requirements 1.4, 2.2).
public class LoginDtoValidator : AbstractValidator<LoginDto>
{
public LoginDtoValidator()
{
RuleFor(x => x.Email)
.NotEmpty().WithMessage("L'adresse email est obligatoire.")
.EmailAddress().WithMessage("Adresse email invalide.");
RuleFor(x => x.MotDePasse)
.NotEmpty().WithMessage("Le mot de passe est obligatoire.");
}
}
// Validation de la demande de réinitialisation (Requirements 1.4, 6).
public class ForgotPasswordDtoValidator : AbstractValidator<ForgotPasswordDto>
{
public ForgotPasswordDtoValidator()
{
RuleFor(x => x.Email)
.NotEmpty().WithMessage("L'adresse email est obligatoire.")
.EmailAddress().WithMessage("Adresse email invalide.");
}
}
// Validation de la réinitialisation du mot de passe (Requirements 7.4, 7.5).
public class ResetPasswordDtoValidator : AbstractValidator<ResetPasswordDto>
{
public ResetPasswordDtoValidator()
{
RuleFor(x => x.Token)
.NotEmpty().WithMessage("Le jeton de réinitialisation est obligatoire.");
RuleFor(x => x.NouveauMotDePasse)
.NotEmpty().WithMessage("Le mot de passe est obligatoire.")
.MinimumLength(8).WithMessage("Le mot de passe doit comporter au moins 8 caractères.");
}
}
@@ -0,0 +1,242 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using FluentAssertions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using SchotzIadKmTracker.Api.Models.DTOs;
namespace SchotzIadKmTracker.Tests.Auth;
/// <summary>
/// Tests d'intégration de l'authentification (feature authentification), exécutés sur
/// l'hôte réel via <see cref="WebApplicationFactory{TEntryPoint}"/> (Program expose
/// <c>public partial class Program {}</c>).
///
/// Contexte de conception (design.md, section « Testing Strategy » — Tests d'intégration) :
/// - Toutes les routes MVC de données sont protégées par un filtre d'autorisation global
/// (RequireAuthenticatedUser) ; AuthController est [AllowAnonymous] et /health est public.
/// - La configuration exige JWT__SecretKey (>= 32 octets) : fournie ici via une config de test.
/// - La base est ISOLÉE par test : chaque test crée sa propre factory pointant vers un fichier
/// SQLite temporaire unique (Guid). Cela évite le conflit « compte unique » entre tests
/// (un seul register possible par base). Le fichier est supprimé en fin de test (IDisposable).
/// - Smtp__Host est laissé VIDE pour forcer le repli journalisation (LoggingEmailService),
/// afin de ne jamais tenter d'envoi SMTP réel pendant les tests.
///
/// Chaque test instancie <see cref="IsolatedAuthFactory"/> dans un bloc <c>using</c> :
/// base neuve garantie et nettoyage du fichier temporaire.
/// </summary>
public class AuthIntegrationTests
{
// Clé JWT de test : >= 32 octets (exigence de configuration). Valeur factice, jamais utilisée en production.
private const string JwtTestSecretKey = "test-secret-key-integration-authentification-0123456789";
/// <summary>
/// Factory de test isolée : chaque instance possède son propre fichier SQLite temporaire
/// (nom unique via Guid) et surcharge la configuration (ConnectionStrings__Default,
/// JWT__SecretKey, Smtp__Host vide) via AddInMemoryCollection. Le fichier est supprimé
/// à la libération de la factory.
/// </summary>
private sealed class IsolatedAuthFactory : WebApplicationFactory<Program>
{
private readonly string _dbPath =
Path.Combine(Path.GetTempPath(), $"schotz-auth-it-{Guid.NewGuid():N}.db");
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Development");
// Program.cs lit la configuration (Jwt, ConnectionStrings, Smtp) DÈS la construction
// du builder (via builder.Configuration.GetSection(...).Get<...>() pour enregistrer
// AddJwtBearer et le DbContext). Ces valeurs doivent donc être présentes très tôt.
// UseSetting alimente la configuration de l'hôte web, disponible au moment où Program
// consomme ces sections (contrairement à ConfigureAppConfiguration, appliquée trop tard
// pour ces lectures « eager »). On isole ainsi la base par factory sans variable d'env
// globale au process (qui casserait l'isolation entre factories parallèles).
builder.UseSetting("ConnectionStrings:Default", $"Data Source={_dbPath}");
builder.UseSetting("Jwt:SecretKey", JwtTestSecretKey);
builder.UseSetting("Smtp:Host", string.Empty);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
TryDeleteDbFiles();
}
}
private void TryDeleteDbFiles()
{
// SQLite peut créer des fichiers annexes (-wal, -shm) : on les nettoie aussi.
foreach (var path in new[] { _dbPath, _dbPath + "-wal", _dbPath + "-shm" })
{
try
{
if (File.Exists(path))
{
File.Delete(path);
}
}
catch
{
// Nettoyage best-effort : un fichier temporaire résiduel ne doit pas faire échouer le test.
}
}
}
}
/// <summary>
/// Crée un client HTTP sans redirection auto ni cookies : on teste les codes de statut bruts.
/// </summary>
private static HttpClient CreerClient(IsolatedAuthFactory factory) =>
factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false,
});
private static RegisterDto NouveauCompte() =>
new($"user-{Guid.NewGuid():N}@example.com", "MotDePasse123!");
// ---------------------------------------------------------------------
// Tâche 8.2 — Protection des routes (Requirements 4.1, 4.2, 4.4, 4.5)
// ---------------------------------------------------------------------
[Theory]
[InlineData("/api/vehicules")]
[InlineData("/api/profil")]
[InlineData("/api/bareme/2025")]
public async Task Route_de_donnees_sans_jeton_renvoie_401(string route)
{
// Requirement 4.2 / 4.5 : sans jeton, une route de données est rejetée (401).
using var factory = new IsolatedAuthFactory();
var client = CreerClient(factory);
var response = await client.GetAsync(route);
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}
[Theory]
[InlineData("/api/auth/compte-existe")]
[InlineData("/health")]
public async Task Route_publique_accessible_sans_jeton_renvoie_200(string route)
{
// Requirement 4.4 : les endpoints publics (auth + /health) restent accessibles sans jeton.
using var factory = new IsolatedAuthFactory();
var client = CreerClient(factory);
var response = await client.GetAsync(route);
response.StatusCode.Should().Be(HttpStatusCode.OK);
}
[Fact]
public async Task Route_de_donnees_avec_jeton_valide_renvoie_2xx()
{
// Requirement 4.1 : avec un jeton valide, la route de données est autorisée (2xx).
using var factory = new IsolatedAuthFactory();
var client = CreerClient(factory);
var token = await RegisterEtLoginAsync(client);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await client.GetAsync("/api/vehicules");
response.IsSuccessStatusCode.Should().BeTrue(
"un jeton valide doit autoriser l'accès à une route protégée (statut {0})", response.StatusCode);
((int)response.StatusCode).Should().BeInRange(200, 299);
}
// ---------------------------------------------------------------------
// Tâche 8.3 — Parcours bout en bout (Requirements 1.1, 2.1, 7.1)
// ---------------------------------------------------------------------
[Fact]
public async Task Bout_en_bout_register_puis_login_puis_route_protegee()
{
// Requirement 1.1 (register) -> 2.1 (login + token) -> accès protégé avec le token.
using var factory = new IsolatedAuthFactory();
var client = CreerClient(factory);
var compte = NouveauCompte();
// Register (200) — Requirement 1.1.
var registerResponse = await client.PostAsJsonAsync(
"/api/auth/register", new RegisterDto(compte.Email, compte.MotDePasse));
registerResponse.StatusCode.Should().Be(HttpStatusCode.OK);
// Login (200 + token) — Requirement 2.1.
var loginResponse = await client.PostAsJsonAsync(
"/api/auth/login", new LoginDto(compte.Email, compte.MotDePasse));
loginResponse.StatusCode.Should().Be(HttpStatusCode.OK);
var loginResult = await loginResponse.Content.ReadFromJsonAsync<LoginResultDto>();
loginResult.Should().NotBeNull();
loginResult!.Token.Should().NotBeNullOrWhiteSpace();
// Accès à une route protégée avec le token obtenu (2xx).
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult.Token);
var protectedResponse = await client.GetAsync("/api/profil");
protectedResponse.IsSuccessStatusCode.Should().BeTrue(
"le token émis par login doit ouvrir l'accès protégé (statut {0})", protectedResponse.StatusCode);
}
[Fact]
public async Task Bout_en_bout_forgot_password_puis_reset_password_avec_token_invalide()
{
// Requirement 7.1 (cycle de réinitialisation).
//
// Choix d'implémentation pour l'e2e du reset (option b, documentée) :
// le jeton de reset n'est jamais persisté en clair (seul son hachage SHA-256 est stocké
// dans ResetPasswordTokens.TokenHash) et le jeton en clair n'est disponible que dans le
// lien journalisé par LoggingEmailService. Le reconstituer depuis la base ou les logs
// n'est pas fiable en intégration. On vérifie donc de façon déterministe :
// - forgot-password renvoie toujours 200 (non-divulgation, Requirement 6.6) ;
// - reset-password avec un jeton bidon renvoie 400 (lien invalide, Requirement 7.4).
// Le remplacement effectif du mot de passe via un jeton valide est couvert par les
// tests de propriété (P11) au niveau du service, où le jeton en clair est accessible.
using var factory = new IsolatedAuthFactory();
var client = CreerClient(factory);
var compte = NouveauCompte();
// Prérequis : un compte existe.
var registerResponse = await client.PostAsJsonAsync(
"/api/auth/register", new RegisterDto(compte.Email, compte.MotDePasse));
registerResponse.StatusCode.Should().Be(HttpStatusCode.OK);
// forgot-password renvoie 200 (email connu).
var forgotResponse = await client.PostAsJsonAsync(
"/api/auth/forgot-password", new ForgotPasswordDto(compte.Email));
forgotResponse.StatusCode.Should().Be(HttpStatusCode.OK);
// reset-password avec un token bidon => 400 (lien invalide).
var resetResponse = await client.PostAsJsonAsync(
"/api/auth/reset-password", new ResetPasswordDto("token-bidon-inexistant", "NouveauMotDePasse123!"));
resetResponse.StatusCode.Should().Be(HttpStatusCode.BadRequest);
}
/// <summary>
/// Inscrit puis connecte un nouveau compte et retourne le jeton JWT obtenu.
/// </summary>
private static async Task<string> RegisterEtLoginAsync(HttpClient client)
{
var compte = NouveauCompte();
var registerResponse = await client.PostAsJsonAsync(
"/api/auth/register", new RegisterDto(compte.Email, compte.MotDePasse));
registerResponse.StatusCode.Should().Be(HttpStatusCode.OK);
var loginResponse = await client.PostAsJsonAsync(
"/api/auth/login", new LoginDto(compte.Email, compte.MotDePasse));
loginResponse.StatusCode.Should().Be(HttpStatusCode.OK);
var loginResult = await loginResponse.Content.ReadFromJsonAsync<LoginResultDto>();
loginResult.Should().NotBeNull();
loginResult!.Token.Should().NotBeNullOrWhiteSpace();
return loginResult.Token;
}
}
@@ -0,0 +1,60 @@
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SchotzIadKmTracker.Api.Configuration;
using SchotzIadKmTracker.Api.Services;
using Xunit;
namespace SchotzIadKmTracker.Tests.Auth;
/// <summary>
/// Vérifie la logique de sélection en DI de l'implémentation d'<see cref="IEmailService"/>,
/// telle que décrite dans <c>Program.cs</c> :
/// Smtp:Host vide => LoggingEmailService (repli journalisation, Exigence 6.5)
/// Smtp:Host renseigné => SmtpEmailService (MailKit, Exigence 6.4)
///
/// On reconstruit un <see cref="ServiceCollection"/> minimal appliquant la même condition
/// (<c>string.IsNullOrWhiteSpace(smtpOptions.Host)</c>) puis on résout le service pour
/// confirmer le type concret retenu, sans démarrer l'hôte complet (évite l'accès à la base réelle).
/// </summary>
public class AuthServiceEmailSelectionTests
{
private static IEmailService ResoudreEmailService(string host)
{
var smtpOptions = new SmtpOptions { Host = host };
var services = new ServiceCollection();
services.AddLogging();
services.Configure<SmtpOptions>(o => o.Host = host);
// Réplique exacte de la condition de Program.cs (section « Sélection de l'implémentation Email »).
if (string.IsNullOrWhiteSpace(smtpOptions.Host))
services.AddScoped<IEmailService, LoggingEmailService>();
else
services.AddScoped<IEmailService, SmtpEmailService>();
var provider = services.BuildServiceProvider();
return provider.GetRequiredService<IEmailService>();
}
// Feature: authentification, sélection DI email (5.3) : Host vide => LoggingEmailService.
// Validates: Requirements 6.5
[Theory]
[InlineData("")]
[InlineData(" ")]
public void Host_vide_selectionne_LoggingEmailService(string host)
{
var service = ResoudreEmailService(host);
service.Should().BeOfType<LoggingEmailService>();
}
// Feature: authentification, sélection DI email (5.3) : Host renseigné => SmtpEmailService.
// Validates: Requirements 6.4
[Fact]
public void Host_renseigne_selectionne_SmtpEmailService()
{
var service = ResoudreEmailService("smtp.example.com");
service.Should().BeOfType<SmtpEmailService>();
}
}
@@ -0,0 +1,304 @@
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using FsCheck;
using FsCheck.Xunit;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using SchotzIadKmTracker.Api.Models.DTOs;
using SchotzIadKmTracker.Api.Models.Entities;
using SchotzIadKmTracker.Api.Services.Exceptions;
using Xunit;
namespace SchotzIadKmTracker.Tests.Auth;
/// <summary>
/// Tests de propriétés (FsCheck.Xunit, >= 100 itérations) du service d'authentification,
/// couvrant les Correctness Properties P5–P14 de la conception.
///
/// Les tests de flux s'exécutent sur un <see cref="AuthTestHarness"/> avec une base SQLite
/// en mémoire recréée à chaque cas (isolation), un vrai PasswordHasher / JwtService et un
/// IEmailService mocké.
/// </summary>
public class AuthServiceProperties
{
// --- Générateurs contraints à l'espace d'entrée pertinent ------------------
/// <summary>Emails syntaxiquement valides (locale@domaine.tld).</summary>
private static Arbitrary<string> EmailArb()
{
var lettre = Gen.Elements("abcdefghijklmnopqrstuvwxyz0123456789".ToCharArray());
Gen<string> partie(int min, int max) =>
from n in Gen.Choose(min, max)
from cs in Gen.ArrayOf(n, lettre)
select new string(cs);
var tld = Gen.Elements("com", "fr", "org", "net", "io");
var email =
from local in partie(1, 10)
from domaine in partie(1, 10)
from t in tld
select $"{local}@{domaine}.{t}";
return Arb.From(email);
}
/// <summary>Mots de passe d'au moins 8 caractères (imprimables ASCII).</summary>
private static Arbitrary<string> MotDePasseValideArb()
{
var carac = Gen.Elements("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%".ToCharArray());
var g =
from n in Gen.Choose(8, 24)
from cs in Gen.ArrayOf(n, carac)
select new string(cs);
return Arb.From(g);
}
private static Property ForEmailEtMdp(Func<string, string, Task> corps)
{
return Prop.ForAll(EmailArb(), MotDePasseValideArb(), (email, mdp) =>
{
corps(email, mdp).GetAwaiter().GetResult();
});
}
// ---------------------------------------------------------------------------
// Feature: authentification, Property 5: L'inscription crée le compte lorsqu'aucun compte n'existe
// Pour toute paire (email valide, mdp >= 8), base vide + RegisterAsync => exactement 1 compte avec cet email.
// Validates: Requirements 1.1
[Property(MaxTest = 100)]
public Property P5_Inscription_cree_le_compte_sur_base_vide()
{
return ForEmailEtMdp(async (email, mdp) =>
{
using var h = new AuthTestHarness();
await h.Service.RegisterAsync(new RegisterDto(email, mdp), CancellationToken.None);
var comptes = await h.Context.Comptes.ToListAsync();
comptes.Should().ContainSingle();
comptes.Single().Email.Should().Be(email.Trim());
});
}
// Feature: authentification, Property 6: L'inscription est rejetée lorsqu'un compte existe déjà
// Compte déjà présent + 2e RegisterAsync => CompteDejaExistantException, toujours 1 compte.
// Validates: Requirements 1.2
[Property(MaxTest = 100)]
public Property P6_Deuxieme_inscription_rejetee()
{
return Prop.ForAll(EmailArb(), EmailArb(), MotDePasseValideArb(),
(email1, email2, mdp) =>
{
using var h = new AuthTestHarness();
h.Service.RegisterAsync(new RegisterDto(email1, mdp), CancellationToken.None)
.GetAwaiter().GetResult();
Func<Task> deuxieme = () =>
h.Service.RegisterAsync(new RegisterDto(email2, mdp), CancellationToken.None);
deuxieme.Should().ThrowAsync<CompteDejaExistantException>().GetAwaiter().GetResult();
h.Context.Comptes.Count().Should().Be(1);
});
}
// Feature: authentification, Property 8: La connexion émet un jeton sur identifiants corrects et rejette les invalides
// Bons identifiants => LoginResultDto avec token non vide validable ;
// mauvais mdp ou email inconnu => IdentifiantsInvalidesException.
// Validates: Requirements 2.1, 2.2
[Property(MaxTest = 100)]
public Property P8_Login_emet_jeton_ou_rejette()
{
return ForEmailEtMdp(async (email, mdp) =>
{
using var h = new AuthTestHarness();
await h.Service.RegisterAsync(new RegisterDto(email, mdp), CancellationToken.None);
// Bons identifiants => token validable.
var resultat = await h.Service.LoginAsync(new LoginDto(email, mdp), CancellationToken.None);
resultat.Token.Should().NotBeNullOrWhiteSpace();
JwtTestUtils.EstValide(resultat.Token, AuthTestHarness.SecretKey).Should().BeTrue();
// Mauvais mot de passe => rejet.
Func<Task> mauvaisMdp = () =>
h.Service.LoginAsync(new LoginDto(email, mdp + "X"), CancellationToken.None);
await mauvaisMdp.Should().ThrowAsync<IdentifiantsInvalidesException>();
// Email inconnu => rejet.
Func<Task> emailInconnu = () =>
h.Service.LoginAsync(new LoginDto("inconnu-" + email, mdp), CancellationToken.None);
await emailInconnu.Should().ThrowAsync<IdentifiantsInvalidesException>();
});
}
// Feature: authentification, Property 9: Non-divulgation lors de la demande de réinitialisation
// ForgotPasswordAsync ne lève jamais ; email inconnu => aucun token créé et email NON appelé ;
// email du compte => exactement un token créé et EnvoyerLienResetAsync appelé une fois.
// Validates: Requirements 6.6
[Property(MaxTest = 100)]
public Property P9_Non_divulgation_forgot_password()
{
return ForEmailEtMdp(async (email, mdp) =>
{
using var h = new AuthTestHarness();
await h.Service.RegisterAsync(new RegisterDto(email, mdp), CancellationToken.None);
// Email inconnu : ne lève pas, ne crée aucun token, n'appelle pas l'email.
Func<Task> inconnu = () =>
h.Service.ForgotPasswordAsync(new ForgotPasswordDto("autre-" + email), CancellationToken.None);
await inconnu.Should().NotThrowAsync();
(await h.Context.ResetPasswordTokens.CountAsync()).Should().Be(0);
h.NbAppelsEmail.Should().Be(0);
// Email du compte : ne lève pas, crée exactement un token, appelle l'email une fois.
Func<Task> connu = () =>
h.Service.ForgotPasswordAsync(new ForgotPasswordDto(email), CancellationToken.None);
await connu.Should().NotThrowAsync();
(await h.Context.ResetPasswordTokens.CountAsync()).Should().Be(1);
h.NbAppelsEmail.Should().Be(1);
});
}
// Feature: authentification, Property 10: Expiration du jeton de reset paramétrée
// Pour toute ResetTokenLifetimeMinutes > 0, le token créé a Expiration ≈ CreatedAt + minutes et UsedAt == null.
// Validates: Requirements 6.1, 6.2, 6.3
[Property(MaxTest = 100)]
public Property P10_Expiration_reset_parametree()
{
var minutesArb = Arb.From(Gen.Choose(1, 100_000));
return Prop.ForAll(EmailArb(), MotDePasseValideArb(), minutesArb, (email, mdp, minutes) =>
{
using var h = new AuthTestHarness(resetTokenLifetimeMinutes: minutes);
h.Service.RegisterAsync(new RegisterDto(email, mdp), CancellationToken.None)
.GetAwaiter().GetResult();
h.Service.ForgotPasswordAsync(new ForgotPasswordDto(email), CancellationToken.None)
.GetAwaiter().GetResult();
var token = h.Context.ResetPasswordTokens.Single();
token.UsedAt.Should().BeNull();
var attendu = token.CreatedAt.AddMinutes(minutes);
token.Expiration.Should().BeCloseTo(attendu, TimeSpan.FromSeconds(5));
});
}
// Feature: authentification, Property 11: Une réinitialisation valide remplace le mot de passe
// Après ForgotPassword (token capturé via le lien mocké), ResetPasswordAsync(token, nouveauMdp>=8)
// => LoginAsync réussit avec le nouveau mdp et échoue avec l'ancien.
// Validates: Requirements 7.1
[Property(MaxTest = 100)]
public Property P11_Reset_valide_remplace_mdp()
{
return Prop.ForAll(EmailArb(), MotDePasseValideArb(), MotDePasseValideArb(),
(email, ancienMdp, nouveauMdp) =>
{
// On veut deux mots de passe distincts pour tester l'ancien vs le nouveau.
if (ancienMdp == nouveauMdp)
{
nouveauMdp += "Z9";
}
using var h = new AuthTestHarness();
h.Service.RegisterAsync(new RegisterDto(email, ancienMdp), CancellationToken.None)
.GetAwaiter().GetResult();
h.Service.ForgotPasswordAsync(new ForgotPasswordDto(email), CancellationToken.None)
.GetAwaiter().GetResult();
var tokenClair = AuthTestHarness.ExtraireToken(h.DernierLienReset!);
h.Service.ResetPasswordAsync(new ResetPasswordDto(tokenClair, nouveauMdp), CancellationToken.None)
.GetAwaiter().GetResult();
// Login OK avec le nouveau mot de passe.
Func<Task> nouveau = () =>
h.Service.LoginAsync(new LoginDto(email, nouveauMdp), CancellationToken.None);
nouveau.Should().NotThrowAsync().GetAwaiter().GetResult();
// Login KO avec l'ancien mot de passe.
Func<Task> ancien = () =>
h.Service.LoginAsync(new LoginDto(email, ancienMdp), CancellationToken.None);
ancien.Should().ThrowAsync<IdentifiantsInvalidesException>().GetAwaiter().GetResult();
});
}
// Feature: authentification, Property 12: Un jeton de reset est à usage unique
// Un token utilisé une fois => 2e ResetPasswordAsync avec le même token lève LienResetInvalideException ; UsedAt renseigné.
// Validates: Requirements 7.2, 7.4
[Property(MaxTest = 100)]
public Property P12_Reset_usage_unique()
{
return Prop.ForAll(EmailArb(), MotDePasseValideArb(), MotDePasseValideArb(),
(email, mdp, nouveau) =>
{
using var h = new AuthTestHarness();
h.Service.RegisterAsync(new RegisterDto(email, mdp), CancellationToken.None)
.GetAwaiter().GetResult();
h.Service.ForgotPasswordAsync(new ForgotPasswordDto(email), CancellationToken.None)
.GetAwaiter().GetResult();
var tokenClair = AuthTestHarness.ExtraireToken(h.DernierLienReset!);
// Premier usage : succès.
h.Service.ResetPasswordAsync(new ResetPasswordDto(tokenClair, nouveau), CancellationToken.None)
.GetAwaiter().GetResult();
// UsedAt renseigné.
h.Context.ResetPasswordTokens.Single().UsedAt.Should().NotBeNull();
// Deuxième usage du même token : rejeté (avant toute prise en compte du mot de passe).
Func<Task> deuxieme = () =>
h.Service.ResetPasswordAsync(new ResetPasswordDto(tokenClair, nouveau), CancellationToken.None);
deuxieme.Should().ThrowAsync<LienResetInvalideException>().GetAwaiter().GetResult();
});
}
// Feature: authentification, Property 13: Un jeton de reset expiré ou inconnu est rejeté
// Token expiré (Expiration forcée dans le passé) => LienResetExpireException ;
// token inconnu => LienResetInvalideException ; le mdp du compte reste inchangé.
// Validates: Requirements 7.3, 7.4
[Property(MaxTest = 100)]
public Property P13_Reset_expire_ou_inconnu_rejete()
{
return Prop.ForAll(EmailArb(), MotDePasseValideArb(), MotDePasseValideArb(),
(email, mdp, nouveauMdp) =>
{
using var h = new AuthTestHarness();
h.Service.RegisterAsync(new RegisterDto(email, mdp), CancellationToken.None)
.GetAwaiter().GetResult();
var hashInitial = h.Context.Comptes.Single().MotDePasseHash;
// --- Token inconnu de la base ---
Func<Task> inconnu = () =>
h.Service.ResetPasswordAsync(new ResetPasswordDto("token-inexistant", nouveauMdp), CancellationToken.None);
inconnu.Should().ThrowAsync<LienResetInvalideException>().GetAwaiter().GetResult();
// --- Token expiré : on génère un token via forgot puis on force Expiration dans le passé ---
h.Service.ForgotPasswordAsync(new ForgotPasswordDto(email), CancellationToken.None)
.GetAwaiter().GetResult();
var tokenClair = AuthTestHarness.ExtraireToken(h.DernierLienReset!);
var token = h.Context.ResetPasswordTokens.Single();
token.Expiration = DateTime.UtcNow.AddMinutes(-1);
h.Context.SaveChanges();
Func<Task> expire = () =>
h.Service.ResetPasswordAsync(new ResetPasswordDto(tokenClair, nouveauMdp), CancellationToken.None);
expire.Should().ThrowAsync<LienResetExpireException>().GetAwaiter().GetResult();
// Le mot de passe du compte reste inchangé dans les deux cas.
h.Context.Entry(h.Context.Comptes.Single()).Reload();
h.Context.Comptes.Single().MotDePasseHash.Should().Be(hashInitial);
});
}
}
@@ -0,0 +1,163 @@
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using SchotzIadKmTracker.Api.Models.DTOs;
using SchotzIadKmTracker.Api.Services.Exceptions;
using Xunit;
namespace SchotzIadKmTracker.Tests.Auth;
/// <summary>
/// Tests unitaires / d'exemples du flux d'authentification (exemples ciblés
/// complémentaires aux tests de propriétés) : login, non-divulgation,
/// réinitialisation valide et cas d'erreur.
/// </summary>
public class AuthServiceTests
{
private const string Email = "utilisateur@example.com";
private const string MotDePasse = "MotDePasse123";
// Feature: authentification, Property 8 (exemple) : login OK puis rejet mauvais mdp / email inconnu.
// Validates: Requirements 2.1, 2.2
[Fact]
public async Task Login_avec_bons_identifiants_emet_un_jeton_validable()
{
using var h = new AuthTestHarness();
await h.Service.RegisterAsync(new RegisterDto(Email, MotDePasse), CancellationToken.None);
var resultat = await h.Service.LoginAsync(new LoginDto(Email, MotDePasse), CancellationToken.None);
resultat.Token.Should().NotBeNullOrWhiteSpace();
JwtTestUtils.EstValide(resultat.Token, AuthTestHarness.SecretKey).Should().BeTrue();
resultat.Expiration.Should().BeAfter(DateTime.UtcNow);
}
[Fact]
public async Task Login_avec_mauvais_mot_de_passe_est_rejete()
{
using var h = new AuthTestHarness();
await h.Service.RegisterAsync(new RegisterDto(Email, MotDePasse), CancellationToken.None);
Func<Task> acte = () => h.Service.LoginAsync(new LoginDto(Email, "MauvaisMotDePasse"), CancellationToken.None);
await acte.Should().ThrowAsync<IdentifiantsInvalidesException>();
}
[Fact]
public async Task Login_avec_email_inconnu_est_rejete()
{
using var h = new AuthTestHarness();
await h.Service.RegisterAsync(new RegisterDto(Email, MotDePasse), CancellationToken.None);
Func<Task> acte = () => h.Service.LoginAsync(new LoginDto("autre@example.com", MotDePasse), CancellationToken.None);
await acte.Should().ThrowAsync<IdentifiantsInvalidesException>();
}
// Feature: authentification, Property 9 (exemple) : forgot-password réponse identique connu/inconnu.
// Validates: Requirements 6.6
[Fact]
public async Task ForgotPassword_email_inconnu_ne_cree_aucun_token_et_n_appelle_pas_email()
{
using var h = new AuthTestHarness();
await h.Service.RegisterAsync(new RegisterDto(Email, MotDePasse), CancellationToken.None);
await h.Service.ForgotPasswordAsync(new ForgotPasswordDto("inconnu@example.com"), CancellationToken.None);
(await h.Context.ResetPasswordTokens.CountAsync()).Should().Be(0);
h.NbAppelsEmail.Should().Be(0);
}
[Fact]
public async Task ForgotPassword_email_connu_cree_un_token_et_appelle_email_une_fois()
{
using var h = new AuthTestHarness();
await h.Service.RegisterAsync(new RegisterDto(Email, MotDePasse), CancellationToken.None);
await h.Service.ForgotPasswordAsync(new ForgotPasswordDto(Email), CancellationToken.None);
(await h.Context.ResetPasswordTokens.CountAsync()).Should().Be(1);
h.NbAppelsEmail.Should().Be(1);
h.DernierLienReset.Should().Contain("/reset-password?token=");
}
// Feature: authentification, Property 11 (exemple) : reset valide remplace le mot de passe.
// Validates: Requirements 7.1
[Fact]
public async Task ResetPassword_valide_permet_login_avec_nouveau_mdp()
{
using var h = new AuthTestHarness();
await h.Service.RegisterAsync(new RegisterDto(Email, MotDePasse), CancellationToken.None);
await h.Service.ForgotPasswordAsync(new ForgotPasswordDto(Email), CancellationToken.None);
var tokenClair = AuthTestHarness.ExtraireToken(h.DernierLienReset!);
const string nouveauMdp = "NouveauMdp456";
await h.Service.ResetPasswordAsync(new ResetPasswordDto(tokenClair, nouveauMdp), CancellationToken.None);
var ok = await h.Service.LoginAsync(new LoginDto(Email, nouveauMdp), CancellationToken.None);
ok.Token.Should().NotBeNullOrWhiteSpace();
Func<Task> ancien = () => h.Service.LoginAsync(new LoginDto(Email, MotDePasse), CancellationToken.None);
await ancien.Should().ThrowAsync<IdentifiantsInvalidesException>();
}
// Feature: authentification, Property 12 (exemple) : usage unique du token de reset.
// Validates: Requirements 7.2, 7.4
[Fact]
public async Task ResetPassword_deuxieme_usage_du_meme_token_est_rejete()
{
using var h = new AuthTestHarness();
await h.Service.RegisterAsync(new RegisterDto(Email, MotDePasse), CancellationToken.None);
await h.Service.ForgotPasswordAsync(new ForgotPasswordDto(Email), CancellationToken.None);
var tokenClair = AuthTestHarness.ExtraireToken(h.DernierLienReset!);
await h.Service.ResetPasswordAsync(new ResetPasswordDto(tokenClair, "PremierMdp123"), CancellationToken.None);
h.Context.ResetPasswordTokens.Single().UsedAt.Should().NotBeNull();
Func<Task> reuse = () =>
h.Service.ResetPasswordAsync(new ResetPasswordDto(tokenClair, "DeuxiemeMdp123"), CancellationToken.None);
await reuse.Should().ThrowAsync<LienResetInvalideException>();
}
// Feature: authentification, Property 13 (exemples) : token inconnu / expiré rejetés, mdp inchangé.
// Validates: Requirements 7.3, 7.4
[Fact]
public async Task ResetPassword_token_inconnu_est_rejete()
{
using var h = new AuthTestHarness();
await h.Service.RegisterAsync(new RegisterDto(Email, MotDePasse), CancellationToken.None);
var hashInitial = h.Context.Comptes.Single().MotDePasseHash;
Func<Task> acte = () =>
h.Service.ResetPasswordAsync(new ResetPasswordDto("inexistant", "PeuImporte123"), CancellationToken.None);
await acte.Should().ThrowAsync<LienResetInvalideException>();
h.Context.Comptes.Single().MotDePasseHash.Should().Be(hashInitial);
}
[Fact]
public async Task ResetPassword_token_expire_est_rejete()
{
using var h = new AuthTestHarness();
await h.Service.RegisterAsync(new RegisterDto(Email, MotDePasse), CancellationToken.None);
await h.Service.ForgotPasswordAsync(new ForgotPasswordDto(Email), CancellationToken.None);
var hashInitial = h.Context.Comptes.Single().MotDePasseHash;
var tokenClair = AuthTestHarness.ExtraireToken(h.DernierLienReset!);
var token = h.Context.ResetPasswordTokens.Single();
token.Expiration = DateTime.UtcNow.AddMinutes(-1);
await h.Context.SaveChangesAsync();
Func<Task> acte = () =>
h.Service.ResetPasswordAsync(new ResetPasswordDto(tokenClair, "PeuImporte123"), CancellationToken.None);
await acte.Should().ThrowAsync<LienResetExpireException>();
h.Context.Entry(h.Context.Comptes.Single()).Reload();
h.Context.Comptes.Single().MotDePasseHash.Should().Be(hashInitial);
}
}
@@ -0,0 +1,123 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Moq;
using SchotzIadKmTracker.Api.Configuration;
using SchotzIadKmTracker.Api.Data;
using SchotzIadKmTracker.Api.Models.Entities;
using SchotzIadKmTracker.Api.Services;
namespace SchotzIadKmTracker.Tests.Auth;
/// <summary>
/// Banc d'essai pour tester <see cref="AuthService"/> en isolation.
///
/// Utilise un <see cref="AppDbContext"/> adossé à une base SQLite EN MÉMOIRE
/// ("Data Source=:memory:") dont la connexion est maintenue ouverte pour la
/// durée du harnais (la base disparaît à la fermeture de la connexion).
/// On emploie de vrais <see cref="PasswordHasher{Compte}"/> et <see cref="JwtService"/>
/// (JWT signé HS256 avec une clé >= 32 octets), et on mocke <see cref="IEmailService"/>
/// (Moq) afin de capturer le lien de réinitialisation transmis.
///
/// Chaque instance crée une base fraîche : l'isolation entre itérations de
/// propriété est obtenue en instanciant un nouveau harnais par cas.
/// </summary>
public sealed class AuthTestHarness : IDisposable
{
// Clé secrète >= 32 octets (exigée par HMAC-SHA256).
public const string SecretKey = "cle-secrete-de-test-suffisamment-longue-1234567890";
private readonly SqliteConnection _connection;
public AppDbContext Context { get; }
public AuthService Service { get; }
public Mock<IEmailService> EmailMock { get; }
public JwtService Jwt { get; }
public PasswordHasher<Compte> Hasher { get; }
public JwtOptions JwtOptions { get; }
public AuthOptions AuthOptions { get; }
/// <summary>Dernier lien de réinitialisation capturé via le mock IEmailService.</summary>
public string? DernierLienReset { get; private set; }
/// <summary>Nombre d'appels à EnvoyerLienResetAsync capturés.</summary>
public int NbAppelsEmail { get; private set; }
public AuthTestHarness(int jwtExpirationMinutes = 720, int resetTokenLifetimeMinutes = 60)
{
_connection = new SqliteConnection("Data Source=:memory:");
_connection.Open(); // maintenue ouverte : garde la base en vie
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(_connection)
.Options;
Context = new AppDbContext(options);
Context.Database.EnsureCreated();
Hasher = new PasswordHasher<Compte>();
JwtOptions = new JwtOptions
{
SecretKey = SecretKey,
Issuer = "SchotzIadKmTracker",
Audience = "SchotzIadKmTracker",
ExpirationMinutes = jwtExpirationMinutes,
};
AuthOptions = new AuthOptions
{
ResetTokenLifetimeMinutes = resetTokenLifetimeMinutes,
FrontendBaseUrl = "http://localhost:8080",
};
Jwt = new JwtService(Options.Create(JwtOptions));
EmailMock = new Mock<IEmailService>();
EmailMock
.Setup(e => e.EnvoyerLienResetAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Callback<string, string, CancellationToken>((_, lien, _) =>
{
DernierLienReset = lien;
NbAppelsEmail++;
})
.Returns(Task.CompletedTask);
Service = new AuthService(
Context,
Hasher,
Jwt,
EmailMock.Object,
Options.Create(AuthOptions),
Options.Create(JwtOptions),
NullLogger<AuthService>.Instance);
}
/// <summary>Extrait la valeur du paramètre "token" de la query string d'un lien de reset.</summary>
public static string ExtraireToken(string lienReset)
{
var uri = new Uri(lienReset);
var query = uri.Query.TrimStart('?');
foreach (var paire in query.Split('&', StringSplitOptions.RemoveEmptyEntries))
{
var kv = paire.Split('=', 2);
if (kv.Length == 2 && kv[0] == "token")
{
return Uri.UnescapeDataString(kv[1]);
}
}
throw new InvalidOperationException($"Aucun paramètre 'token' dans le lien : {lienReset}");
}
public void Dispose()
{
Context.Dispose();
_connection.Dispose();
}
}
@@ -0,0 +1,152 @@
using System.Linq;
using FluentAssertions;
using FluentValidation.Results;
using FsCheck;
using FsCheck.Xunit;
using SchotzIadKmTracker.Api.Models.DTOs;
using SchotzIadKmTracker.Api.Validators;
using Xunit;
namespace SchotzIadKmTracker.Tests.Auth;
/// <summary>
/// Tests de la validation FluentValidation des DTOs d'authentification.
/// La longueur du mot de passe et la validité syntaxique de l'email sont
/// contrôlées au niveau du validateur (en amont d'AuthService).
/// </summary>
public class AuthValidatorTests
{
private static readonly RegisterDtoValidator RegisterValidator = new();
private static readonly LoginDtoValidator LoginValidator = new();
private static readonly ResetPasswordDtoValidator ResetValidator = new();
private const string EmailValide = "utilisateur@example.com";
// Feature: authentification, Property 7: Un mot de passe trop court est refusé à l'inscription
// Toute chaîne de longueur 0..7 => invalide ; >= 8 => valide (avec email valide).
// Validates: Requirements 1.3
[Property(MaxTest = 100)]
public Property P7_RegisterValidator_rejette_mdp_court_accepte_mdp_long()
{
// Génère des mots de passe de longueur 0..20 à partir de caractères imprimables.
var carac = Gen.Elements("abcdefghijklmnopqrstuvwxyz0123456789ABCDEF!@#".ToCharArray());
var mdpArb = Arb.From(
from n in Gen.Choose(0, 20)
from cs in Gen.ArrayOf(n, carac)
select new string(cs));
return Prop.ForAll(mdpArb, mdp =>
{
var resultat = RegisterValidator.Validate(new RegisterDto(EmailValide, mdp));
if (mdp.Length < 8)
{
resultat.IsValid.Should().BeFalse($"un mot de passe de longueur {mdp.Length} (< 8) doit être rejeté");
}
else
{
resultat.IsValid.Should().BeTrue($"un mot de passe de longueur {mdp.Length} (>= 8) doit être accepté");
}
});
}
// Feature: authentification, Property 14: Un nouveau mot de passe trop court est refusé à la réinitialisation
// ResetPasswordDtoValidator : NouveauMotDePasse < 8 => invalide ; >= 8 (token non vide) => valide.
// Validates: Requirements 7.5
[Property(MaxTest = 100)]
public Property P14_ResetValidator_rejette_nouveau_mdp_court()
{
var carac = Gen.Elements("abcdefghijklmnopqrstuvwxyz0123456789ABCDEF!@#".ToCharArray());
var mdpArb = Arb.From(
from n in Gen.Choose(0, 20)
from cs in Gen.ArrayOf(n, carac)
select new string(cs));
return Prop.ForAll(mdpArb, mdp =>
{
var resultat = ResetValidator.Validate(new ResetPasswordDto("un-jeton-non-vide", mdp));
if (mdp.Length < 8)
{
resultat.IsValid.Should().BeFalse($"un nouveau mot de passe de longueur {mdp.Length} (< 8) doit être rejeté");
}
else
{
resultat.IsValid.Should().BeTrue($"un nouveau mot de passe de longueur {mdp.Length} (>= 8) doit être accepté");
}
});
}
// Feature: authentification, Property 7 (exemples) : bornes de longueur du mot de passe.
// Validates: Requirements 1.3
[Theory]
[InlineData("", false)]
[InlineData("1234567", false)] // 7 caractères
[InlineData("12345678", true)] // 8 caractères
[InlineData("123456789", true)] // 9 caractères
public void RegisterValidator_longueur_mdp_bornes(string mdp, bool valideAttendu)
{
var resultat = RegisterValidator.Validate(new RegisterDto(EmailValide, mdp));
resultat.IsValid.Should().Be(valideAttendu);
}
// Feature: authentification, tests d'exemples (6.13) : emails invalides rejetés.
// Validates: Requirements 1.4
[Theory]
[InlineData("a@")]
[InlineData("abc")]
[InlineData("@x")]
[InlineData("")]
public void RegisterValidator_rejette_les_emails_invalides(string email)
{
var resultat = RegisterValidator.Validate(new RegisterDto(email, "MotDePasse123"));
resultat.IsValid.Should().BeFalse();
}
[Theory]
[InlineData("a@")]
[InlineData("abc")]
[InlineData("@x")]
[InlineData("")]
public void LoginValidator_rejette_les_emails_invalides(string email)
{
var resultat = LoginValidator.Validate(new LoginDto(email, "MotDePasse123"));
resultat.IsValid.Should().BeFalse();
}
[Fact]
public void RegisterValidator_accepte_un_email_valide()
{
var resultat = RegisterValidator.Validate(new RegisterDto(EmailValide, "MotDePasse123"));
resultat.IsValid.Should().BeTrue();
}
// Feature: authentification, tests d'exemples (6.13) : aucun DTO d'auth n'expose de champ de hash.
// LoginResultDto ne comporte que Token + Expiration (Requirement 8.2).
// Validates: Requirements 8.2
[Fact]
public void LoginResultDto_n_expose_que_token_et_expiration()
{
var proprietes = typeof(LoginResultDto).GetProperties().Select(p => p.Name).ToArray();
proprietes.Should().BeEquivalentTo(new[] { "Token", "Expiration" });
proprietes.Should().NotContain(n => n.ToLowerInvariant().Contains("hash"));
proprietes.Should().NotContain(n => n.ToLowerInvariant().Contains("motdepasse"));
}
[Fact]
public void Aucun_dto_d_auth_ne_comporte_de_champ_hash_ou_mot_de_passe_hash()
{
var types = new[]
{
typeof(RegisterDto), typeof(LoginDto), typeof(LoginResultDto),
typeof(ForgotPasswordDto), typeof(ResetPasswordDto), typeof(CompteExisteDto)
};
foreach (var type in types)
{
var noms = type.GetProperties().Select(p => p.Name.ToLowerInvariant());
noms.Should().NotContain(n => n.Contains("hash"), $"{type.Name} ne doit exposer aucun champ de hash");
}
}
}
@@ -0,0 +1,214 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using FluentAssertions;
using FsCheck;
using FsCheck.Xunit;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using SchotzIadKmTracker.Api.Configuration;
using SchotzIadKmTracker.Api.Models.Entities;
using SchotzIadKmTracker.Api.Services;
namespace SchotzIadKmTracker.Tests.Auth;
/// <summary>
/// Propriétés de correction du service JWT (feature authentification).
/// Couvre l'émission/validation des jetons (Property 2), le rejet des jetons expirés
/// (Property 3) et le rejet des signatures invalides (Property 4).
/// </summary>
public class JwtServiceProperties
{
// Clé de signature >= 32 octets requise pour HS256 (sinon SecurityTokenEncryptionKeySizeException).
private const string CleSecrete = "clef-secrete-de-test-suffisamment-longue-0123456789";
private const string Issuer = "SchotzIadKmTracker";
private const string Audience = "SchotzIadKmTracker";
/// <summary>Construit un JwtService réel avec la durée d'expiration fournie.</summary>
private static JwtService CreerService(int expirationMinutes)
{
var options = Options.Create(new JwtOptions
{
SecretKey = CleSecrete,
Issuer = Issuer,
Audience = Audience,
ExpirationMinutes = expirationMinutes
});
return new JwtService(options);
}
/// <summary>Paramètres de validation alignés sur ceux du pipeline (Program.cs).</summary>
private static TokenValidationParameters CreerParametresValidation(string cleSecrete = CleSecrete)
=> new()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Issuer,
ValidAudience = Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(cleSecrete)),
ClockSkew = TimeSpan.FromSeconds(30)
};
/// <summary>Générateur d'ExpirationMinutes borné (1..100000) pour éviter les valeurs absurdes.</summary>
private static Arbitrary<int> ExpirationMinutesArb()
=> Gen.Choose(1, 100_000).ToArbitrary();
/// <summary>Générateur d'emails non vides (bornés) pour les comptes de test.</summary>
private static Gen<string> EmailGen()
=> from local in Gen.Elements("alice", "bob", "carol", "utilisateur", "compte.unique")
from domaine in Gen.Elements("example.com", "test.fr", "mail.org")
select $"{local}@{domaine}";
// Feature: authentification, Property 2: Pour toute valeur d'ExpirationMinutes positive et tout
// compte, le jeton émis est validable avec les paramètres de validation, préserve les claims
// sub et email, et son exp vaut iat + ExpirationMinutes (à la tolérance d'horloge près).
// Validates: Requirements 2.1, 2.4, 5.1, 5.4, 5.5
[Property(MaxTest = 100)]
public Property Le_jeton_emis_est_validable_et_preserve_les_claims()
{
var arb = Arb.From(
from expiration in ExpirationMinutesArb().Generator
from id in Gen.Choose(1, 1_000_000)
from email in EmailGen()
select (expiration, id, email));
return Prop.ForAll(arb, tuple =>
{
var (expirationMinutes, id, email) = tuple;
var service = CreerService(expirationMinutes);
var compte = new Compte { Id = id, Email = email };
var jeton = service.GenererJeton(compte);
// Ne pas remapper les noms de claims entrants (sub reste "sub", email reste "email").
var handler = new JwtSecurityTokenHandler { MapInboundClaims = false };
handler.ValidateToken(jeton, CreerParametresValidation(), out var validated);
var jwt = (JwtSecurityToken)validated;
// Claims sub et email préservés (lecture sur le jeton validé, noms d'origine).
var sub = jwt.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Sub)?.Value;
var emailClaim = jwt.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Email)?.Value;
sub.Should().Be(id.ToString());
emailClaim.Should().Be(email);
// exp ≈ iat + ExpirationMinutes (tolérance de 5 secondes pour l'écart d'exécution).
var ecart = jwt.ValidTo - jwt.ValidFrom;
ecart.Should().BeCloseTo(TimeSpan.FromMinutes(expirationMinutes), TimeSpan.FromSeconds(5));
});
}
// Feature: authentification, Property 3: Pour tout jeton dont la date d'expiration est antérieure
// à l'instant courant, la validation échoue (SecurityTokenExpiredException).
// Validates: Requirements 4.3, 5.2
[Property(MaxTest = 100)]
public Property Un_jeton_expire_est_rejete()
{
// On fabrique un jeton déjà expiré via le handler avec la même clé.
// minutesEcoulees > ClockSkew (30 s) pour dépasser la tolérance d'horloge.
var arb = Gen.Choose(2, 10_000).ToArbitrary();
return Prop.ForAll(arb, minutesEcoulees =>
{
var maintenant = DateTime.UtcNow;
var cle = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(CleSecrete));
var credentials = new SigningCredentials(cle, SecurityAlgorithms.HmacSha256);
var jetonExpire = new JwtSecurityToken(
issuer: Issuer,
audience: Audience,
claims: new[] { new Claim(JwtRegisteredClaimNames.Sub, "1") },
notBefore: maintenant.AddMinutes(-minutesEcoulees - 1),
expires: maintenant.AddMinutes(-minutesEcoulees),
signingCredentials: credentials);
var jeton = new JwtSecurityTokenHandler().WriteToken(jetonExpire);
var handler = new JwtSecurityTokenHandler();
Action validation = () => handler.ValidateToken(jeton, CreerParametresValidation(), out _);
validation.Should().Throw<SecurityTokenExpiredException>();
});
}
// Feature: authentification, Property 4: Pour tout jeton signé avec une clé différente de la clé
// de validation, ou dont la charge utile a été altérée, la validation échoue.
// Validates: Requirements 5.3, 4.2
[Property(MaxTest = 100)]
public Property Une_signature_invalide_est_rejetee()
{
// Deux cas : (a) jeton signé avec une autre clé, (b) charge utile altérée.
var arb = Arb.From(
from id in Gen.Choose(1, 1_000_000)
from email in EmailGen()
from altererCharge in Gen.Elements(true, false)
select (id, email, altererCharge));
return Prop.ForAll(arb, tuple =>
{
var (id, email, altererCharge) = tuple;
var handler = new JwtSecurityTokenHandler();
var parametres = CreerParametresValidation();
string jeton;
if (altererCharge)
{
// Jeton valide dont on altère la charge utile (segment central).
var service = CreerService(720);
var valide = service.GenererJeton(new Compte { Id = id, Email = email });
var segments = valide.Split('.');
// Inverser deux caractères de la charge (payload) pour casser la signature.
var charge = segments[1].ToCharArray();
if (charge.Length >= 2)
{
(charge[0], charge[1]) = (charge[1], charge[0]);
}
else
{
charge = (segments[1] + "X").ToCharArray();
}
segments[1] = new string(charge);
jeton = string.Join('.', segments);
}
else
{
// Jeton signé avec une clé DIFFÉRENTE (>= 32 octets) de celle de validation.
const string autreCle = "AUTRE-clef-secrete-differente-mais-assez-longue-9876543210";
var cle = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(autreCle));
var credentials = new SigningCredentials(cle, SecurityAlgorithms.HmacSha256);
var maintenant = DateTime.UtcNow;
var jwt = new JwtSecurityToken(
issuer: Issuer,
audience: Audience,
claims: new[]
{
new Claim(JwtRegisteredClaimNames.Sub, id.ToString()),
new Claim(JwtRegisteredClaimNames.Email, email)
},
notBefore: maintenant,
expires: maintenant.AddMinutes(720),
signingCredentials: credentials);
jeton = new JwtSecurityTokenHandler().WriteToken(jwt);
}
// La validation doit échouer : soit une exception de signature (SecurityTokenException,
// p. ex. SecurityTokenInvalidSignatureException / SecurityTokenSignatureKeyNotFoundException),
// soit un rejet au décodage lorsque la charge altérée n'est plus décodable (ArgumentException).
Exception? levee = null;
try
{
handler.ValidateToken(jeton, parametres, out _);
}
catch (Exception ex)
{
levee = ex;
}
levee.Should().NotBeNull("un jeton à signature invalide ou charge altérée doit être rejeté");
levee.Should().Match(e => e is SecurityTokenException || e is ArgumentException);
});
}
}
@@ -0,0 +1,48 @@
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using Microsoft.IdentityModel.Tokens;
namespace SchotzIadKmTracker.Tests.Auth;
/// <summary>
/// Utilitaires de validation de jetons JWT pour les tests, alignés sur les
/// paramètres de validation de <c>Program.cs</c> (issuer / audience / clé de
/// signature / durée de vie).
/// </summary>
internal static class JwtTestUtils
{
/// <summary>
/// Valide un jeton HS256 avec la clé fournie. Retourne <c>true</c> si le jeton
/// est signé par cette clé, non expiré et porte l'issuer/audience attendus.
/// </summary>
public static bool EstValide(
string token,
string secretKey,
string issuer = "SchotzIadKmTracker",
string audience = "SchotzIadKmTracker")
{
var handler = new JwtSecurityTokenHandler();
var parameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = issuer,
ValidAudience = audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)),
ClockSkew = TimeSpan.FromSeconds(30),
};
try
{
handler.ValidateToken(token, parameters, out _);
return true;
}
catch
{
return false;
}
}
}
@@ -0,0 +1,85 @@
using FluentAssertions;
using Microsoft.Extensions.Configuration;
using SchotzIadKmTracker.Api.Configuration;
namespace SchotzIadKmTracker.Tests.Auth;
/// <summary>
/// Tests d'exemple vérifiant la liaison des options d'authentification depuis une configuration
/// in-memory, ainsi que les valeurs par défaut attendues (feature authentification, tâche 2.2).
/// </summary>
public class OptionsBindingTests
{
private static IConfiguration ConstruireConfiguration(IEnumerable<KeyValuePair<string, string?>> valeurs)
=> new ConfigurationBuilder()
.AddInMemoryCollection(valeurs)
.Build();
// Validates: Requirements 5.5
[Fact]
public void JwtOptions_se_lie_depuis_la_configuration_et_applique_les_defauts()
{
// Seul SecretKey est fourni : Issuer/Audience/ExpirationMinutes doivent prendre leurs défauts.
var config = ConstruireConfiguration(new Dictionary<string, string?>
{
["Jwt:SecretKey"] = "clef-secrete-de-test-suffisamment-longue-0123456789"
});
var options = new JwtOptions();
config.GetSection(JwtOptions.SectionName).Bind(options);
options.SecretKey.Should().Be("clef-secrete-de-test-suffisamment-longue-0123456789");
options.Issuer.Should().Be("SchotzIadKmTracker");
options.Audience.Should().Be("SchotzIadKmTracker");
options.ExpirationMinutes.Should().Be(720);
}
[Fact]
public void JwtOptions_prend_les_valeurs_fournies_par_la_configuration()
{
var config = ConstruireConfiguration(new Dictionary<string, string?>
{
["Jwt:SecretKey"] = "une-autre-clef-de-test-tres-longue-abcdefghijklmnop",
["Jwt:Issuer"] = "MonIssuer",
["Jwt:Audience"] = "MonAudience",
["Jwt:ExpirationMinutes"] = "60"
});
var options = new JwtOptions();
config.GetSection(JwtOptions.SectionName).Bind(options);
options.Issuer.Should().Be("MonIssuer");
options.Audience.Should().Be("MonAudience");
options.ExpirationMinutes.Should().Be(60);
}
// Validates: Requirements 6.3
[Fact]
public void AuthOptions_se_lie_depuis_la_configuration_et_applique_les_defauts()
{
// Configuration vide : les défauts doivent s'appliquer.
var config = ConstruireConfiguration(new Dictionary<string, string?>());
var options = new AuthOptions();
config.GetSection(AuthOptions.SectionName).Bind(options);
options.ResetTokenLifetimeMinutes.Should().Be(60);
options.FrontendBaseUrl.Should().Be("http://localhost:8080");
}
// Validates: Requirements 6.7
[Fact]
public void SmtpOptions_se_lie_depuis_la_configuration_et_applique_les_defauts()
{
var config = ConstruireConfiguration(new Dictionary<string, string?>());
var options = new SmtpOptions();
config.GetSection(SmtpOptions.SectionName).Bind(options);
options.Host.Should().BeEmpty();
options.Port.Should().Be(587);
options.User.Should().BeEmpty();
options.Password.Should().BeEmpty();
options.From.Should().BeEmpty();
}
}
@@ -0,0 +1,49 @@
using FluentAssertions;
using FsCheck;
using FsCheck.Xunit;
using Microsoft.AspNetCore.Identity;
using SchotzIadKmTracker.Api.Models.Entities;
namespace SchotzIadKmTracker.Tests.Auth;
/// <summary>
/// Propriété de correction du hachage de mot de passe (feature authentification).
/// Utilise le PasswordHasher&lt;Compte&gt; réel d'ASP.NET Core Identity.
/// </summary>
public class PasswordHasherProperties
{
// Feature: authentification, Property 1: Pour tout mot de passe non vide, le hachage produit une
// valeur différente du clair, VerifyHashedPassword retourne Success, et deux hachages du même
// mot de passe diffèrent (présence de sel).
// Validates: Requirements 1.5, 8.1, 8.3
[Property(MaxTest = 100)]
public Property Le_hachage_est_verifiable_et_sale()
{
// Générateur de mots de passe non vides et bornés (1..64 caractères imprimables).
var arb = Arb.From(
Gen.Choose(1, 64)
.SelectMany(longueur =>
Gen.ArrayOf(longueur, Gen.Choose(33, 126).Select(c => (char)c))
.Select(chars => new string(chars))));
return Prop.ForAll(arb, motDePasse =>
{
var hasher = new PasswordHasher<Compte>();
var compte = new Compte { Id = 1, Email = "test@example.com" };
var hash1 = hasher.HashPassword(compte, motDePasse);
var hash2 = hasher.HashPassword(compte, motDePasse);
// Le hash diffère du clair.
hash1.Should().NotBe(motDePasse);
// La vérification réussit.
hasher.VerifyHashedPassword(compte, hash1, motDePasse)
.Should().BeOneOf(PasswordVerificationResult.Success,
PasswordVerificationResult.SuccessRehashNeeded);
// Deux hachages du même mot de passe diffèrent (sel aléatoire).
hash1.Should().NotBe(hash2);
});
}
}