From 2d8afac3bcaf50fb2af8591b11f943e5c88373ed Mon Sep 17 00:00:00 2001 From: BuildTools Date: Thu, 15 Feb 2024 21:39:17 +0100 Subject: [PATCH 01/18] =?UTF-8?q?Impl=C3=A9mentation=20des=20diff=C3=A9ren?= =?UTF-8?q?tes=20m=C3=A9thodes=20CRUD=20pour=20la=20classe=20User,=20Cr?= =?UTF-8?q?=C3=A9ation=20d'un=20InquiriesController=20pour=20pouvoir=20man?= =?UTF-8?q?ipuler=20la=20classe=20Inquiry=20plus=20tard.=20Ajout=20du=20sy?= =?UTF-8?q?st=C3=A8me=20d'authentification=20pour=20am=C3=A9liorer=20la=20?= =?UTF-8?q?s=C3=A9curit=C3=A9=20de=20l'API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../API/Controllers/InquiriesController.cs | 26 +++++++ API_SQLuedo/API/Controllers/UserController.cs | 32 ++++++++ API_SQLuedo/API/Program.cs | 36 ++++++++- API_SQLuedo/DbContextLib/DbContextLib.csproj | 1 + API_SQLuedo/DbContextLib/UserDbContext.cs | 4 +- API_SQLuedo/Services/IDataService.cs | 8 +- API_SQLuedo/Services/UserDataService.cs | 73 +++++++++++++++++-- 7 files changed, 168 insertions(+), 12 deletions(-) create mode 100644 API_SQLuedo/API/Controllers/InquiriesController.cs diff --git a/API_SQLuedo/API/Controllers/InquiriesController.cs b/API_SQLuedo/API/Controllers/InquiriesController.cs new file mode 100644 index 0000000..688c379 --- /dev/null +++ b/API_SQLuedo/API/Controllers/InquiriesController.cs @@ -0,0 +1,26 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Model.DTO; +using Services; + +namespace API.Controllers +{ + [Route("api/[controller]")] + [Authorize] + [ApiController] + public class InquiriesController : Controller + { + private IDataService _inquiryDataService; + + public InquiriesController(IDataService inquiryDataService) + { + _inquiryDataService = inquiryDataService; + } + + [HttpGet("inquiries/{page}/{number}")] + public IActionResult GetInquiries(int page, int number) + { + return Ok(_inquiryDataService.GetInquiries(page, number)); + } + } +} \ No newline at end of file diff --git a/API_SQLuedo/API/Controllers/UserController.cs b/API_SQLuedo/API/Controllers/UserController.cs index 1708d72..2440372 100644 --- a/API_SQLuedo/API/Controllers/UserController.cs +++ b/API_SQLuedo/API/Controllers/UserController.cs @@ -1,4 +1,5 @@ using DbContextLib; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Model.DTO; @@ -7,6 +8,7 @@ using Services; namespace API.Controllers { [Route("api/[controller]")] + [Authorize] [ApiController] public class UserController : Controller { @@ -22,5 +24,35 @@ namespace API.Controllers { return Ok(_userDataService.GetUsers(page, number)); } + + [HttpGet("user/{id}")] + public IActionResult GetUserById(int id) + { + return Ok(_userDataService.GetUserById(id)); + } + + [HttpGet("user/{username}")] + public IActionResult GetUserByUsername(string username) + { + return Ok(_userDataService.GetUserByUsername(username)); + } + + [HttpDelete] + public IActionResult DeleteUser(int id) + { + return Ok(_userDataService.DeleteUser(id)); + } + + [HttpPost] + public IActionResult UpdateUser(int id, UserDTO user) + { + return Ok(_userDataService.UpdateUser(id, user)); + } + + [HttpPut] + public IActionResult CreateUser(string username, string password, string email, bool isAdmin) + { + return Ok(_userDataService.CreateUser(username, password, email, isAdmin)); + } } } diff --git a/API_SQLuedo/API/Program.cs b/API_SQLuedo/API/Program.cs index ce122da..a8e96f7 100644 --- a/API_SQLuedo/API/Program.cs +++ b/API_SQLuedo/API/Program.cs @@ -1,5 +1,7 @@ using DbContextLib; +using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; +using Microsoft.OpenApi.Models; using Services; var builder = WebApplication.CreateBuilder(args); @@ -10,8 +12,38 @@ builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); -builder.Services.AddScoped(); +builder.Services.AddScoped(); builder.Services.AddDbContext(); +builder.Services.AddAuthorization(); +builder.Services.AddIdentityApiEndpoints() + .AddEntityFrameworkStores(); +builder.Services.AddSwaggerGen(option => +{ + option.SwaggerDoc("v1", new OpenApiInfo { Title = "Demo API", Version = "v1" }); + option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme + { + In = ParameterLocation.Header, + Description = "Please enter a valid token", + Name = "Authorization", + Type = SecuritySchemeType.Http, + BearerFormat = "JWT", + Scheme = "Bearer" + }); + option.AddSecurityRequirement(new OpenApiSecurityRequirement + { + { + new OpenApiSecurityScheme + { + Reference = new OpenApiReference + { + Type=ReferenceType.SecurityScheme, + Id="Bearer" + } + }, + new string[]{} + } + }); +}); var app = builder.Build(); @@ -28,4 +60,6 @@ app.UseAuthorization(); app.MapControllers(); +app.MapIdentityApi(); + app.Run(); diff --git a/API_SQLuedo/DbContextLib/DbContextLib.csproj b/API_SQLuedo/DbContextLib/DbContextLib.csproj index 38862a9..4611898 100644 --- a/API_SQLuedo/DbContextLib/DbContextLib.csproj +++ b/API_SQLuedo/DbContextLib/DbContextLib.csproj @@ -8,6 +8,7 @@ + all diff --git a/API_SQLuedo/DbContextLib/UserDbContext.cs b/API_SQLuedo/DbContextLib/UserDbContext.cs index c8d8a4f..9e5d5ba 100644 --- a/API_SQLuedo/DbContextLib/UserDbContext.cs +++ b/API_SQLuedo/DbContextLib/UserDbContext.cs @@ -1,11 +1,13 @@ using Entities.SQLudeoDB; +using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.AspNetCore.Cryptography.KeyDerivation; using Microsoft.EntityFrameworkCore; using System.Security.Cryptography; +using Microsoft.AspNetCore.Identity; namespace DbContextLib { - public class UserDbContext : DbContext + public class UserDbContext : IdentityDbContext { public DbSet Users { get; set; } public DbSet BlackList { get; set; } diff --git a/API_SQLuedo/Services/IDataService.cs b/API_SQLuedo/Services/IDataService.cs index 2919cc7..a0c1a57 100644 --- a/API_SQLuedo/Services/IDataService.cs +++ b/API_SQLuedo/Services/IDataService.cs @@ -1,4 +1,5 @@ -using Model.DTO; +using Model.Business; +using Model.DTO; namespace Services { @@ -7,7 +8,10 @@ namespace Services public IEnumerable GetUsers(int page, int number); public UserDTO GetUserById(int id); public UserDTO GetUserByUsername(string username); - public IEnumerable GetInquiries(); + public bool DeleteUser(int id); + public UserDTO UpdateUser(int id, UserDTO user); + public UserDTO CreateUser(string username, string password, string email, bool isAdmin); + public IEnumerable GetInquiries(int page, int number); } } diff --git a/API_SQLuedo/Services/UserDataService.cs b/API_SQLuedo/Services/UserDataService.cs index c3206d9..ce82782 100644 --- a/API_SQLuedo/Services/UserDataService.cs +++ b/API_SQLuedo/Services/UserDataService.cs @@ -7,35 +7,92 @@ using System.Text; using System.Threading.Tasks; using Model.Mappers; using Model.Business; +using Microsoft.EntityFrameworkCore; namespace Services { - public class UserDataService : IDataService + public class InquiryDataService : IDataService { private UserDbContext DbContext { get; set; } - public UserDataService(UserDbContext context) + public InquiryDataService(UserDbContext context) { DbContext = context; context.Database.EnsureCreated(); } - public IEnumerable GetInquiries() - { - throw new NotImplementedException(); - } public UserDTO GetUserById(int id) { - throw new NotImplementedException(); + var userEntity = DbContext.Users.FirstOrDefault(u => u.Id == id); + if (userEntity == null) + { + throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(id)); + } + return userEntity.FromEntityToModel().FromModelToDTO(); + } public UserDTO GetUserByUsername(string username) { - throw new NotImplementedException(); + var userEntity = DbContext.Users.FirstOrDefault(u => u.Username == username); + if (userEntity == null) + { + throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(username)); + } + return userEntity.FromEntityToModel().FromModelToDTO(); } public IEnumerable GetUsers(int page, int number) { return DbContext.Users.Skip((page - 1) * number).Take(number).ToList().Select(u => u.FromEntityToModel().FromModelToDTO()); } + + public bool DeleteUser(int id) + { + var userEntity = DbContext.Users.FirstOrDefault(u => u.Id == id); + if (userEntity == null) + { + return false; + } + DbContext.Users.Remove(userEntity); + DbContext.SaveChanges(); + return true; + } + + public UserDTO UpdateUser(int id, UserDTO user) + { + var updatingUser = GetUserById(id); + if(updatingUser == null) + { + throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(id)); + } + updatingUser.Username = user.Username; + updatingUser.Password = user.Password; + updatingUser.Email = user.Email; + updatingUser.IsAdmin = user.IsAdmin; + + var updatedUser = updatingUser.FromDTOToModel().FromModelToEntity(); + // Permet d'indiquer en Db que l'entité a été modifiée. + DbContext.Entry(updatedUser).State = EntityState.Modified; + return updatedUser.FromEntityToModel().FromModelToDTO(); + } + + public UserDTO CreateUser(string username, string password, string email, bool isAdmin) + { + var newUserEntity = new UserDTO + { + Username = username, + Password = password, + Email = email, + IsAdmin = isAdmin + }; + DbContext.Users.Add(newUserEntity.FromDTOToModel().FromModelToEntity()); + DbContext.SaveChanges(); + return newUserEntity; + } + + public IEnumerable GetInquiries(int page, int number) + { + throw new NotImplementedException(); + } } } From 8ffb40d8152a746bf96315df6403310472c9126b Mon Sep 17 00:00:00 2001 From: Erwan MENAGER Date: Thu, 15 Feb 2024 21:42:31 +0100 Subject: [PATCH 02/18] =?UTF-8?q?Correction=20d'une=20ambigu=C3=AFt=C3=A9?= =?UTF-8?q?=20entre=20deux=20m=C3=A9thodes=20HttpGet?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- API_SQLuedo/API/Controllers/UserController.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/API_SQLuedo/API/Controllers/UserController.cs b/API_SQLuedo/API/Controllers/UserController.cs index 2440372..81f1f59 100644 --- a/API_SQLuedo/API/Controllers/UserController.cs +++ b/API_SQLuedo/API/Controllers/UserController.cs @@ -25,13 +25,13 @@ namespace API.Controllers return Ok(_userDataService.GetUsers(page, number)); } - [HttpGet("user/{id}")] + [HttpGet("user/id/{id}")] public IActionResult GetUserById(int id) { return Ok(_userDataService.GetUserById(id)); } - [HttpGet("user/{username}")] + [HttpGet("user/username/{username}")] public IActionResult GetUserByUsername(string username) { return Ok(_userDataService.GetUserByUsername(username)); From 0611a5ca3e7c1f82002323743519fcd497782bde Mon Sep 17 00:00:00 2001 From: "victor.gaborit" Date: Fri, 16 Feb 2024 08:02:17 +0100 Subject: [PATCH 03/18] =?UTF-8?q?fix=20security=20pour=20la=20WebAPI=20:?= =?UTF-8?q?=20ajout=20dbContext=20pour=20acceder=20=C3=A0=20la=20base=20ou?= =?UTF-8?q?=20sont=20stocker=20les=20tokens=20et=20ajout=20des=20nuggets?= =?UTF-8?q?=20necessaire=20(Identity.EntityFramework=20et=20EntityFramewor?= =?UTF-8?q?kCore.InMemory.=20Changements=20aport=C3=A9s=20dans=20le=20prog?= =?UTF-8?q?ram.cs=20(utilisation=20du=20context=20avec=20une=20base=20de?= =?UTF-8?q?=20donn=C3=A9es=20en=20m=C3=A9moire=20InMemory=20et=20utilisati?= =?UTF-8?q?on=20du=20EndPoint)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- API_SQLuedo/API/API.csproj | 4 +++- API_SQLuedo/API/Controllers/UserController.cs | 3 ++- API_SQLuedo/API/Program.cs | 7 +++++-- API_SQLuedo/API/WebAPIDbContext.cs | 11 +++++++++++ 4 files changed, 21 insertions(+), 4 deletions(-) create mode 100644 API_SQLuedo/API/WebAPIDbContext.cs diff --git a/API_SQLuedo/API/API.csproj b/API_SQLuedo/API/API.csproj index 74687fb..cd3cbe6 100644 --- a/API_SQLuedo/API/API.csproj +++ b/API_SQLuedo/API/API.csproj @@ -1,4 +1,4 @@ - + net8.0 @@ -8,11 +8,13 @@ + all runtime; build; native; contentfiles; analyzers; buildtransitive + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/API_SQLuedo/API/Controllers/UserController.cs b/API_SQLuedo/API/Controllers/UserController.cs index 81f1f59..08ac4c5 100644 --- a/API_SQLuedo/API/Controllers/UserController.cs +++ b/API_SQLuedo/API/Controllers/UserController.cs @@ -52,7 +52,8 @@ namespace API.Controllers [HttpPut] public IActionResult CreateUser(string username, string password, string email, bool isAdmin) { - return Ok(_userDataService.CreateUser(username, password, email, isAdmin)); + // return Ok(_userDataService.CreateUser(username, password, email, isAdmin)); + return CreatedAtAction(nameof(GetUsers), _userDataService.CreateUser(username, password, email, isAdmin)); } } } diff --git a/API_SQLuedo/API/Program.cs b/API_SQLuedo/API/Program.cs index a8e96f7..80f106f 100644 --- a/API_SQLuedo/API/Program.cs +++ b/API_SQLuedo/API/Program.cs @@ -1,3 +1,4 @@ +using API; using DbContextLib; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; @@ -14,9 +15,11 @@ builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddScoped(); builder.Services.AddDbContext(); +builder.Services.AddDbContext(options => options.UseInMemoryDatabase("appDb")); +builder.Services.AddIdentityApiEndpoints().AddEntityFrameworkStores(); builder.Services.AddAuthorization(); -builder.Services.AddIdentityApiEndpoints() - .AddEntityFrameworkStores(); +//builder.Services.AddIdentityApiEndpoints() +// .AddEntityFrameworkStores(); builder.Services.AddSwaggerGen(option => { option.SwaggerDoc("v1", new OpenApiInfo { Title = "Demo API", Version = "v1" }); diff --git a/API_SQLuedo/API/WebAPIDbContext.cs b/API_SQLuedo/API/WebAPIDbContext.cs new file mode 100644 index 0000000..afc8996 --- /dev/null +++ b/API_SQLuedo/API/WebAPIDbContext.cs @@ -0,0 +1,11 @@ +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Identity.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; + +namespace API +{ + public class WebAPIDbContext : IdentityDbContext + { + public WebAPIDbContext(DbContextOptions options) : base(options) { } + } +} From 9d261f56b35cc46127c25528d6bc34aca3348dec Mon Sep 17 00:00:00 2001 From: "victor.gaborit" Date: Fri, 16 Feb 2024 08:51:33 +0100 Subject: [PATCH 04/18] =?UTF-8?q?changement=20du=20retour=20pour=20les=20m?= =?UTF-8?q?=C3=A9thodes=20POST=20et=20PUT=20dans=20UserController=20:=20Po?= =?UTF-8?q?st=20c'est=20un=20pour=20envoyer=20un=20=C3=A9l=C3=A9ment=20?= =?UTF-8?q?=C3=A0=20l'API=20alors=20que=20PUT=20c'est=20pour=20modifier=20?= =?UTF-8?q?un=20=C3=A9l=C3=A9ment=20existant.=20meilleur=20utilisation=20d?= =?UTF-8?q?es=20code=20de=20retour=20:=20POST=20renvoie=20CreateAtAction.?= =?UTF-8?q?=20Utilisation=20des=20exception=20renvoyer=20par=20le=20servic?= =?UTF-8?q?e=20pour=20envoyer=20les=20bon=20codes=20de=20retour=20(BadRequ?= =?UTF-8?q?est=20ou=20NotFount=20ou=20personalis=C3=A9=20:=20GetUsers=20re?= =?UTF-8?q?nvoie=20un=20204=20si=20le=20nombre=20d'item=20renvoy=C3=A9=20e?= =?UTF-8?q?st=20de=200),=20utilisation=20du=20FromBody=20pour=20la=20metho?= =?UTF-8?q?de=20PUT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- API_SQLuedo/API/Controllers/UserController.cs | 57 ++++++++++++++++--- 1 file changed, 49 insertions(+), 8 deletions(-) diff --git a/API_SQLuedo/API/Controllers/UserController.cs b/API_SQLuedo/API/Controllers/UserController.cs index 08ac4c5..7b61bf7 100644 --- a/API_SQLuedo/API/Controllers/UserController.cs +++ b/API_SQLuedo/API/Controllers/UserController.cs @@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Model.Business; using Model.DTO; using Services; @@ -22,38 +23,78 @@ namespace API.Controllers [HttpGet("users/{page}/{number}")] public IActionResult GetUsers(int page, int number) { + var nbUser = _userDataService.GetUsers(page, number).Count(); + if(nbUser == 0) + { + return StatusCode(204); + } return Ok(_userDataService.GetUsers(page, number)); } [HttpGet("user/id/{id}")] public IActionResult GetUserById(int id) { - return Ok(_userDataService.GetUserById(id)); + try + { + return Ok(_userDataService.GetUserById(id)); + } catch (ArgumentException ex) + { + return NotFound(); + } + } [HttpGet("user/username/{username}")] public IActionResult GetUserByUsername(string username) { - return Ok(_userDataService.GetUserByUsername(username)); + try + { + return Ok(_userDataService.GetUserByUsername(username)); + }catch (ArgumentException ex) + { + return NotFound(); + } + } [HttpDelete] public IActionResult DeleteUser(int id) { - return Ok(_userDataService.DeleteUser(id)); + var sucess = _userDataService.DeleteUser(id); + if(sucess) + { + return Ok(_userDataService.DeleteUser(id)); + } else + { + return NotFound(); + } + } [HttpPost] - public IActionResult UpdateUser(int id, UserDTO user) + public IActionResult UpdateUser(string username, string password, string email, bool isAdmin) { - return Ok(_userDataService.UpdateUser(id, user)); + + // return Ok(_userDataService.CreateUser(username, password, email, isAdmin)); + return CreatedAtAction(nameof(GetUsers), _userDataService.CreateUser(username, password, email, isAdmin)); } [HttpPut] - public IActionResult CreateUser(string username, string password, string email, bool isAdmin) + public IActionResult CreateUser(int id, [FromBody] UserDTO userDTO) { - // return Ok(_userDataService.CreateUser(username, password, email, isAdmin)); - return CreatedAtAction(nameof(GetUsers), _userDataService.CreateUser(username, password, email, isAdmin)); + if(id != userDTO.Id) + { + return BadRequest(); + } + if(!ModelState.IsValid) + { + return BadRequest(); + } + if(userDTO != null) + { + return Ok(_userDataService.UpdateUser(id, userDTO)); + } + return NotFound(); } } } From e2abab3905b51ee28c8009071dedf8626a31de29 Mon Sep 17 00:00:00 2001 From: "victor.gaborit" Date: Fri, 16 Feb 2024 08:55:04 +0100 Subject: [PATCH 05/18] =?UTF-8?q?ajout=20des=20annotations=20Authorize=20p?= =?UTF-8?q?our=20les=20m=C3=A9thode=20de=20UserController=20pour=20utilise?= =?UTF-8?q?r=20la=20s=C3=A9curit=C3=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- API_SQLuedo/API/Controllers/UserController.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/API_SQLuedo/API/Controllers/UserController.cs b/API_SQLuedo/API/Controllers/UserController.cs index 7b61bf7..480179f 100644 --- a/API_SQLuedo/API/Controllers/UserController.cs +++ b/API_SQLuedo/API/Controllers/UserController.cs @@ -21,6 +21,7 @@ namespace API.Controllers } [HttpGet("users/{page}/{number}")] + [Authorize] public IActionResult GetUsers(int page, int number) { var nbUser = _userDataService.GetUsers(page, number).Count(); @@ -32,6 +33,7 @@ namespace API.Controllers } [HttpGet("user/id/{id}")] + [Authorize] public IActionResult GetUserById(int id) { try @@ -45,6 +47,7 @@ namespace API.Controllers } [HttpGet("user/username/{username}")] + [Authorize] public IActionResult GetUserByUsername(string username) { try @@ -58,6 +61,7 @@ namespace API.Controllers } [HttpDelete] + [Authorize] public IActionResult DeleteUser(int id) { var sucess = _userDataService.DeleteUser(id); @@ -72,6 +76,7 @@ namespace API.Controllers } [HttpPost] + [Authorize] public IActionResult UpdateUser(string username, string password, string email, bool isAdmin) { @@ -80,6 +85,7 @@ namespace API.Controllers } [HttpPut] + [Authorize] public IActionResult CreateUser(int id, [FromBody] UserDTO userDTO) { if(id != userDTO.Id) From e8754ab2478c53425689ae8a869acf54d93042ad Mon Sep 17 00:00:00 2001 From: Erwan MENAGER Date: Fri, 16 Feb 2024 11:41:05 +0100 Subject: [PATCH 06/18] =?UTF-8?q?Pas=20besoin=20de=20mettre=20[Authorize]?= =?UTF-8?q?=20dans=20les=20m=C3=A9thodes=20si=20d=C3=A9j=C3=A0=20pr=C3=A9s?= =?UTF-8?q?ent=20dans=20le=20controlleur?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- API_SQLuedo/API/Controllers/UserController.cs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/API_SQLuedo/API/Controllers/UserController.cs b/API_SQLuedo/API/Controllers/UserController.cs index 480179f..7b61bf7 100644 --- a/API_SQLuedo/API/Controllers/UserController.cs +++ b/API_SQLuedo/API/Controllers/UserController.cs @@ -21,7 +21,6 @@ namespace API.Controllers } [HttpGet("users/{page}/{number}")] - [Authorize] public IActionResult GetUsers(int page, int number) { var nbUser = _userDataService.GetUsers(page, number).Count(); @@ -33,7 +32,6 @@ namespace API.Controllers } [HttpGet("user/id/{id}")] - [Authorize] public IActionResult GetUserById(int id) { try @@ -47,7 +45,6 @@ namespace API.Controllers } [HttpGet("user/username/{username}")] - [Authorize] public IActionResult GetUserByUsername(string username) { try @@ -61,7 +58,6 @@ namespace API.Controllers } [HttpDelete] - [Authorize] public IActionResult DeleteUser(int id) { var sucess = _userDataService.DeleteUser(id); @@ -76,7 +72,6 @@ namespace API.Controllers } [HttpPost] - [Authorize] public IActionResult UpdateUser(string username, string password, string email, bool isAdmin) { @@ -85,7 +80,6 @@ namespace API.Controllers } [HttpPut] - [Authorize] public IActionResult CreateUser(int id, [FromBody] UserDTO userDTO) { if(id != userDTO.Id) From 00cc2e3a2de13bce067b31b2ece74b25d95fb2ea Mon Sep 17 00:00:00 2001 From: Erwan MENAGER Date: Fri, 16 Feb 2024 17:27:36 +0100 Subject: [PATCH 07/18] =?UTF-8?q?Continuation=20des=20m=C3=A9thodes=20CRUD?= =?UTF-8?q?=20mais=20=C3=A9galement=20l'impl=C3=A9mentation=20du=20logger.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../API/Controllers/InquiriesController.cs | 41 ++++++++++++++++++- API_SQLuedo/API/Controllers/UserController.cs | 38 +++++++++++------ API_SQLuedo/API/Program.cs | 2 +- API_SQLuedo/Services/IDataService.cs | 3 +- API_SQLuedo/Services/UserDataService.cs | 16 ++++++-- 5 files changed, 82 insertions(+), 18 deletions(-) diff --git a/API_SQLuedo/API/Controllers/InquiriesController.cs b/API_SQLuedo/API/Controllers/InquiriesController.cs index 688c379..e42d14e 100644 --- a/API_SQLuedo/API/Controllers/InquiriesController.cs +++ b/API_SQLuedo/API/Controllers/InquiriesController.cs @@ -12,6 +12,8 @@ namespace API.Controllers { private IDataService _inquiryDataService; + private readonly ILogger _logger; + public InquiriesController(IDataService inquiryDataService) { _inquiryDataService = inquiryDataService; @@ -19,8 +21,45 @@ namespace API.Controllers [HttpGet("inquiries/{page}/{number}")] public IActionResult GetInquiries(int page, int number) - { + { + var nbInquiry = _inquiryDataService.GetInquiries(page, number).Count(); + if (nbInquiry == 0) + { + _logger.LogError("[ERREUR] Aucune enquête trouvé."); + return StatusCode(204); + } + _logger.LogInformation("[INFORMATION] {nb} Enquête(s) trouvée(s)", nbInquiry); return Ok(_inquiryDataService.GetInquiries(page, number)); } + + [HttpGet("inquiry/id/{id}")] + public IActionResult GetInquiryById(int id) + { + try + { + _logger.LogInformation("[INFORMATION] Enquête avec l'id {id} a été trouvé.", id); + return Ok(_inquiryDataService.GetInquiryById(id)); + } + catch (ArgumentException) + { + _logger.LogError("[ERREUR] Aucune enquête trouvée avec l'id {id}.", id); + return NotFound(); + } + } + + [HttpGet("inquiry/title/{title}")] + public IActionResult GetInquiryByTitle(string title) + { + try + { + _logger.LogInformation("[INFORMATION] Enquête avec le titre {title} a été trouvé.", title); + return Ok(_inquiryDataService.GetInquiryByTitle(title)); + } + catch (ArgumentException) + { + _logger.LogError("[ERREUR] Aucune enquête trouvée avec le titre {title}.", title); + return NotFound(); + } + } } } \ No newline at end of file diff --git a/API_SQLuedo/API/Controllers/UserController.cs b/API_SQLuedo/API/Controllers/UserController.cs index 7b61bf7..1896147 100644 --- a/API_SQLuedo/API/Controllers/UserController.cs +++ b/API_SQLuedo/API/Controllers/UserController.cs @@ -13,11 +13,14 @@ namespace API.Controllers [ApiController] public class UserController : Controller { - private IDataService _userDataService; + private IDataService _userDataService; + + private readonly ILogger _logger; - public UserController(IDataService userDataService) + public UserController(IDataService userDataService, ILogger logger) { _userDataService = userDataService; + _logger = logger; } [HttpGet("users/{page}/{number}")] @@ -26,8 +29,10 @@ namespace API.Controllers var nbUser = _userDataService.GetUsers(page, number).Count(); if(nbUser == 0) { + _logger.LogError("[ERREUR] Aucun utilisateur trouvé."); return StatusCode(204); } + _logger.LogInformation("[INFORMATION] {nb} Utilisateur(s) trouvé(s)", nbUser); return Ok(_userDataService.GetUsers(page, number)); } @@ -36,12 +41,13 @@ namespace API.Controllers { try { + _logger.LogInformation("[INFORMATION] Utilisateur avec l'id {id} a été trouvé.", id); return Ok(_userDataService.GetUserById(id)); - } catch (ArgumentException ex) - { + } catch (ArgumentException) + { + _logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id); return NotFound(); } - } [HttpGet("user/username/{username}")] @@ -49,9 +55,11 @@ namespace API.Controllers { try { + _logger.LogInformation("[INFORMATION] Utilisateur avec l'username {username} a été trouvé.", username); return Ok(_userDataService.GetUserByUsername(username)); - }catch (ArgumentException ex) + }catch (ArgumentException) { + _logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'username {username}.", username); return NotFound(); } @@ -60,40 +68,46 @@ namespace API.Controllers [HttpDelete] public IActionResult DeleteUser(int id) { - var sucess = _userDataService.DeleteUser(id); - if(sucess) + var success = _userDataService.DeleteUser(id); + if(success) { + _logger.LogInformation("[INFORMATION] L'utilisateur avec l'id {id} a été supprimé.", id); return Ok(_userDataService.DeleteUser(id)); } else { + _logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id); return NotFound(); } } [HttpPost] - public IActionResult UpdateUser(string username, string password, string email, bool isAdmin) + public IActionResult CreateUser(string username, string password, string email, bool isAdmin) { - // return Ok(_userDataService.CreateUser(username, password, email, isAdmin)); + _logger.LogInformation("[INFORMATION] Un utilisateur a été créé : username - {username}, password - {password}, email - {email}, isAdmin - {isAdmin}", username, password, email, isAdmin); return CreatedAtAction(nameof(GetUsers), _userDataService.CreateUser(username, password, email, isAdmin)); } [HttpPut] - public IActionResult CreateUser(int id, [FromBody] UserDTO userDTO) + public IActionResult UpdateUser(int id, [FromBody] UserDTO userDTO) { if(id != userDTO.Id) - { + { + _logger.LogError("[ERREUR] Problème ID - La mise à jour de l'utilisateur avec l'id {id} a échouée.", id); return BadRequest(); } if(!ModelState.IsValid) { + _logger.LogError("[ERREUR] Problème controlleur - La mise à jour de l'utilisateur avec l'id {id} a échouée.", id); return BadRequest(); } if(userDTO != null) { + _logger.LogInformation("[INFORMATION] La mise à jour de l'utilsiateur avec l'id {id} a été effectuée", id); return Ok(_userDataService.UpdateUser(id, userDTO)); } + _logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id); return NotFound(); } } diff --git a/API_SQLuedo/API/Program.cs b/API_SQLuedo/API/Program.cs index 80f106f..d4dbe01 100644 --- a/API_SQLuedo/API/Program.cs +++ b/API_SQLuedo/API/Program.cs @@ -13,7 +13,7 @@ builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); -builder.Services.AddScoped(); +builder.Services.AddScoped(); builder.Services.AddDbContext(); builder.Services.AddDbContext(options => options.UseInMemoryDatabase("appDb")); builder.Services.AddIdentityApiEndpoints().AddEntityFrameworkStores(); diff --git a/API_SQLuedo/Services/IDataService.cs b/API_SQLuedo/Services/IDataService.cs index a0c1a57..a3faad9 100644 --- a/API_SQLuedo/Services/IDataService.cs +++ b/API_SQLuedo/Services/IDataService.cs @@ -12,6 +12,7 @@ namespace Services public UserDTO UpdateUser(int id, UserDTO user); public UserDTO CreateUser(string username, string password, string email, bool isAdmin); public IEnumerable GetInquiries(int page, int number); - + public InquiryDTO GetInquiryById(int id); + public InquiryDTO GetInquiryByTitle(string title); } } diff --git a/API_SQLuedo/Services/UserDataService.cs b/API_SQLuedo/Services/UserDataService.cs index ce82782..a327454 100644 --- a/API_SQLuedo/Services/UserDataService.cs +++ b/API_SQLuedo/Services/UserDataService.cs @@ -11,10 +11,10 @@ using Microsoft.EntityFrameworkCore; namespace Services { - public class InquiryDataService : IDataService + public class UserDataService : IDataService { private UserDbContext DbContext { get; set; } - public InquiryDataService(UserDbContext context) + public UserDataService(UserDbContext context) { DbContext = context; context.Database.EnsureCreated(); @@ -93,6 +93,16 @@ namespace Services public IEnumerable GetInquiries(int page, int number) { throw new NotImplementedException(); - } + } + + public InquiryDTO GetInquiryById(int id) + { + throw new NotImplementedException(); + } + + public InquiryDTO GetInquiryByTitle(string title) + { + throw new NotImplementedException(); + } } } From d47098ab37e54a8138f6ceb1596630c734e6b9f5 Mon Sep 17 00:00:00 2001 From: "Johnny.Ratton" Date: Sat, 17 Feb 2024 08:49:54 +0100 Subject: [PATCH 08/18] =?UTF-8?q?D=C3=A9buggage=20du=20CRUD=20pour=20pouvo?= =?UTF-8?q?ir=20faire=20des=20tests=20dessus?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- API_SQLuedo/API/Controllers/UserController.cs | 10 +++++++--- API_SQLuedo/Services/UserDataService.cs | 15 +++++++-------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/API_SQLuedo/API/Controllers/UserController.cs b/API_SQLuedo/API/Controllers/UserController.cs index 1896147..8518f62 100644 --- a/API_SQLuedo/API/Controllers/UserController.cs +++ b/API_SQLuedo/API/Controllers/UserController.cs @@ -82,11 +82,15 @@ namespace API.Controllers } [HttpPost] - public IActionResult CreateUser(string username, string password, string email, bool isAdmin) + public IActionResult CreateUser([FromBody]UserDTO dto) { + if (dto.Username == null || dto.Password == null || dto.Email == null) + { + return BadRequest(); + } // return Ok(_userDataService.CreateUser(username, password, email, isAdmin)); - _logger.LogInformation("[INFORMATION] Un utilisateur a été créé : username - {username}, password - {password}, email - {email}, isAdmin - {isAdmin}", username, password, email, isAdmin); - return CreatedAtAction(nameof(GetUsers), _userDataService.CreateUser(username, password, email, isAdmin)); + _logger.LogInformation("[INFORMATION] Un utilisateur a été créé : username - {username}, password - {password}, email - {email}, isAdmin - {isAdmin}", dto.Username, dto.Password, dto.Email, dto.IsAdmin); + return Created(nameof(GetUsers), _userDataService.CreateUser(dto.Username, dto.Password, dto.Email, dto.IsAdmin)); } [HttpPut] diff --git a/API_SQLuedo/Services/UserDataService.cs b/API_SQLuedo/Services/UserDataService.cs index a327454..ddaa3e6 100644 --- a/API_SQLuedo/Services/UserDataService.cs +++ b/API_SQLuedo/Services/UserDataService.cs @@ -54,14 +54,14 @@ namespace Services return false; } DbContext.Users.Remove(userEntity); - DbContext.SaveChanges(); + DbContext.SaveChangesAsync(); return true; } public UserDTO UpdateUser(int id, UserDTO user) { - var updatingUser = GetUserById(id); - if(updatingUser == null) + var updatingUser = DbContext.Users.FirstOrDefault(u => u.Id == id); + if (updatingUser == null) { throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(id)); } @@ -69,11 +69,10 @@ namespace Services updatingUser.Password = user.Password; updatingUser.Email = user.Email; updatingUser.IsAdmin = user.IsAdmin; - - var updatedUser = updatingUser.FromDTOToModel().FromModelToEntity(); // Permet d'indiquer en Db que l'entité a été modifiée. - DbContext.Entry(updatedUser).State = EntityState.Modified; - return updatedUser.FromEntityToModel().FromModelToDTO(); + DbContext.Entry(updatingUser).State = EntityState.Modified; + DbContext.SaveChangesAsync(); + return updatingUser.FromEntityToModel().FromModelToDTO(); } public UserDTO CreateUser(string username, string password, string email, bool isAdmin) @@ -86,7 +85,7 @@ namespace Services IsAdmin = isAdmin }; DbContext.Users.Add(newUserEntity.FromDTOToModel().FromModelToEntity()); - DbContext.SaveChanges(); + DbContext.SaveChangesAsync(); return newUserEntity; } From d18e2d4e521c99599d2fe8cf4a82e74334a1aca5 Mon Sep 17 00:00:00 2001 From: "Johnny.Ratton" Date: Sat, 17 Feb 2024 11:14:23 +0100 Subject: [PATCH 09/18] =?UTF-8?q?Cr=C3=A9ation=20de=20l'application=20de?= =?UTF-8?q?=20tests=20console=20du=20UserController=20qui=20est=20interact?= =?UTF-8?q?ive=20et=20propose=20des=20tests=20automatiques?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- API_SQLuedo/API/API.csproj | 12 +- API_SQLuedo/API_SQLuedo.sln | 20 +- API_SQLuedo/DbContextLib/DbContextLib.csproj | 11 +- API_SQLuedo/EntityFramework/Entities.csproj | 6 +- API_SQLuedo/Model/DTO/UserDTO.cs | 13 + API_SQLuedo/Model/Model.csproj | 6 +- API_SQLuedo/Services/Services.csproj | 6 +- API_SQLuedo/TestAPI/TestAPI.csproj | 13 +- API_SQLuedo/TestConsoleAPI/Program.cs | 319 ++++++++++++++++++ .../TestConsoleAPI/TestConsoleAPI.csproj | 21 ++ API_SQLuedo/TestEF/TestEF.csproj | 13 +- 11 files changed, 401 insertions(+), 39 deletions(-) create mode 100644 API_SQLuedo/TestConsoleAPI/Program.cs create mode 100644 API_SQLuedo/TestConsoleAPI/TestConsoleAPI.csproj diff --git a/API_SQLuedo/API/API.csproj b/API_SQLuedo/API/API.csproj index cd3cbe6..f3c90dd 100644 --- a/API_SQLuedo/API/API.csproj +++ b/API_SQLuedo/API/API.csproj @@ -8,19 +8,19 @@ - - - + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + diff --git a/API_SQLuedo/API_SQLuedo.sln b/API_SQLuedo/API_SQLuedo.sln index 888826d..58f87a2 100644 --- a/API_SQLuedo/API_SQLuedo.sln +++ b/API_SQLuedo/API_SQLuedo.sln @@ -3,19 +3,21 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.8.34408.163 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API", "API\API.csproj", "{65F4AE69-E1CA-4B87-BDF0-946A37351BD1}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "API", "API\API.csproj", "{65F4AE69-E1CA-4B87-BDF0-946A37351BD1}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Entities", "EntityFramework\Entities.csproj", "{6D079CDA-C000-4833-98A0-D07D153EA264}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Entities", "EntityFramework\Entities.csproj", "{6D079CDA-C000-4833-98A0-D07D153EA264}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Model", "Model\Model.csproj", "{ADCC427D-A3CD-431C-A90B-F9369C4584E8}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Model", "Model\Model.csproj", "{ADCC427D-A3CD-431C-A90B-F9369C4584E8}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestAPI", "TestAPI\TestAPI.csproj", "{17025B90-8B2A-49E9-97D3-1A84A208DF50}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestAPI", "TestAPI\TestAPI.csproj", "{17025B90-8B2A-49E9-97D3-1A84A208DF50}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestEF", "TestEF\TestEF.csproj", "{54FAD8AF-7601-4C54-8406-D81476A8D7D7}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestEF", "TestEF\TestEF.csproj", "{54FAD8AF-7601-4C54-8406-D81476A8D7D7}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DbContextLib", "DbContextLib\DbContextLib.csproj", "{BDCB3BFD-B744-4BC0-BCFC-78E08600203A}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DbContextLib", "DbContextLib\DbContextLib.csproj", "{BDCB3BFD-B744-4BC0-BCFC-78E08600203A}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Services", "Services\Services.csproj", "{9BD3DCBA-AFD8-47FA-B07C-613B53E63968}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Services", "Services\Services.csproj", "{9BD3DCBA-AFD8-47FA-B07C-613B53E63968}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestConsoleAPI", "TestConsoleAPI\TestConsoleAPI.csproj", "{46376AEF-4093-4AE9-AD2F-F51B541F9C6A}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -51,6 +53,10 @@ Global {9BD3DCBA-AFD8-47FA-B07C-613B53E63968}.Debug|Any CPU.Build.0 = Debug|Any CPU {9BD3DCBA-AFD8-47FA-B07C-613B53E63968}.Release|Any CPU.ActiveCfg = Release|Any CPU {9BD3DCBA-AFD8-47FA-B07C-613B53E63968}.Release|Any CPU.Build.0 = Release|Any CPU + {46376AEF-4093-4AE9-AD2F-F51B541F9C6A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {46376AEF-4093-4AE9-AD2F-F51B541F9C6A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {46376AEF-4093-4AE9-AD2F-F51B541F9C6A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {46376AEF-4093-4AE9-AD2F-F51B541F9C6A}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/API_SQLuedo/DbContextLib/DbContextLib.csproj b/API_SQLuedo/DbContextLib/DbContextLib.csproj index 4611898..f2f138b 100644 --- a/API_SQLuedo/DbContextLib/DbContextLib.csproj +++ b/API_SQLuedo/DbContextLib/DbContextLib.csproj @@ -7,14 +7,15 @@ - - - - + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/API_SQLuedo/EntityFramework/Entities.csproj b/API_SQLuedo/EntityFramework/Entities.csproj index feae017..0768618 100644 --- a/API_SQLuedo/EntityFramework/Entities.csproj +++ b/API_SQLuedo/EntityFramework/Entities.csproj @@ -7,12 +7,12 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/API_SQLuedo/Model/DTO/UserDTO.cs b/API_SQLuedo/Model/DTO/UserDTO.cs index 786fad7..06aa236 100644 --- a/API_SQLuedo/Model/DTO/UserDTO.cs +++ b/API_SQLuedo/Model/DTO/UserDTO.cs @@ -23,5 +23,18 @@ namespace Model.DTO Email = email; IsAdmin = isAdmin; } + + public UserDTO(string username, string password, string email, bool isAdmin) + { + Username = username; + Password = password; + Email = email; + IsAdmin = isAdmin; + } + + public override string ToString() + { + return $"{Id}\t{Username}\t{Email}\t{IsAdmin}"; + } } } diff --git a/API_SQLuedo/Model/Model.csproj b/API_SQLuedo/Model/Model.csproj index b46af5d..6e81eea 100644 --- a/API_SQLuedo/Model/Model.csproj +++ b/API_SQLuedo/Model/Model.csproj @@ -7,12 +7,12 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/API_SQLuedo/Services/Services.csproj b/API_SQLuedo/Services/Services.csproj index 4cd7b1b..4eafac0 100644 --- a/API_SQLuedo/Services/Services.csproj +++ b/API_SQLuedo/Services/Services.csproj @@ -7,12 +7,12 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/API_SQLuedo/TestAPI/TestAPI.csproj b/API_SQLuedo/TestAPI/TestAPI.csproj index bda60d7..9d1ad3b 100644 --- a/API_SQLuedo/TestAPI/TestAPI.csproj +++ b/API_SQLuedo/TestAPI/TestAPI.csproj @@ -10,19 +10,20 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + - - + + runtime; build; native; contentfiles; analyzers; buildtransitive all diff --git a/API_SQLuedo/TestConsoleAPI/Program.cs b/API_SQLuedo/TestConsoleAPI/Program.cs new file mode 100644 index 0000000..651de21 --- /dev/null +++ b/API_SQLuedo/TestConsoleAPI/Program.cs @@ -0,0 +1,319 @@ +// See https://aka.ms/new-console-template for more information + +using API.Controllers; +using DbContextLib; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Model.DTO; +using Services; + +var connection = new SqliteConnection("DataSource=:memory:"); +connection.Open(); +var options = new DbContextOptionsBuilder() + .UseSqlite(connection) + .Options; +using ILoggerFactory factory = new LoggerFactory(); +ILogger logger = factory.CreateLogger(); + +using (var context = new UserDbContext(options)) +{ + var controller = new UserController(new UserDataService(context), logger); + + void PrintUsers() + { + Console.WriteLine(); + var users = controller.GetUsers(1, 10) as OkObjectResult; + foreach(var item in users.Value as IEnumerable) + { + Console.WriteLine(item); + } + } + + void SearchUserByUsername() + { + Console.WriteLine("\nVeuillez saisir le pseudonyme de l'utilisateur recherché : "); + var username = Console.ReadLine(); + var user = controller.GetUserByUsername(username) as OkObjectResult; + if(user == null) + { + Console.WriteLine("Erreur, la requête n'a rien donné."); + return; + } + Console.WriteLine(user.Value as UserDTO); + } + + void SearchUserById() + { + Console.WriteLine("\nVeuillez saisir l'identifiant de l'utilisateur recherché : "); + var id = Console.ReadLine(); + var user = controller.GetUserById(int.Parse(id)) as OkObjectResult; + if (user == null) + { + Console.WriteLine("Erreur, la requête n'a rien donné."); + return; + } + Console.WriteLine(user.Value as UserDTO); + } + + void AddUser() + { + Console.WriteLine("Veuillez saisir le pseudonyme :"); + var username = Console.ReadLine(); + Console.WriteLine("Veuillez saisir une adresse email :"); + var email = Console.ReadLine(); + Console.WriteLine("Veuillez saisir un mot de passe :"); + var mdp = Console.ReadLine(); + var res = controller.CreateUser(new UserDTO(username, mdp, email, false)); + if(res.GetType() == typeof(CreatedResult)) { + Console.WriteLine("\nUtilisateur créé avec succès"); + } else + { + Console.WriteLine("\nErreur lors de la création de l'utilisateur !"); + } + } + + void UpdateUser() + { + Console.WriteLine("Quel est l'identifiant de l'utilisateur à mettre à jour ?"); + var id = int.Parse(Console.ReadLine()); + var res = (controller.GetUserById(id)); + if (res.GetType() == typeof(OkObjectResult)) { + var user = (res as OkObjectResult).Value as UserDTO; + if (user == null) { + Console.WriteLine("Erreur, un problème est survenu"); + return; + } + else + { + Console.WriteLine("Utilisateur trouvé !\n"); + Console.WriteLine("Veuillez saisir le pseudonyme :"); + var username = Console.ReadLine(); + Console.WriteLine("Veuillez saisir l'email :"); + var email = Console.ReadLine(); + var retour = controller.UpdateUser(id, new UserDTO(id, username, user.Password, email, user.IsAdmin)); + if(retour.GetType() == typeof(OkObjectResult)) + { + Console.WriteLine("Mise à jour effectué avec succès !"); + } else + { + Console.WriteLine("Une erreur est survenue lors de la mise à jour."); + } + } + } + else { + Console.WriteLine("Une erreur est survenue lors de la mise à jour !"); + } + } + + void DeleteUser() + { + Console.WriteLine("Quel est l'identifiant de lutilisateur à supprimer ?"); + var id = int.Parse(Console.ReadLine()); + var res = controller.DeleteUser(id); + if(res.GetType() == typeof(OkObjectResult)) + { + Console.WriteLine("La suppression a été effectuée avec succès !"); + } + else + { + Console.WriteLine("Erreur lors de la suppression !"); + } + } + + + void Menu() + { + Console.WriteLine("|------------------------------------------------|"); + Console.WriteLine("| Menu |"); + Console.WriteLine("|------------------------------------------------|"); + Console.WriteLine("| t - Effectuer des tests automatiques |"); + Console.WriteLine("| 1 - Afficher les utilisateurs |"); + Console.WriteLine("| 2 - Rechercher un utilisateur avec son pseudo |"); + Console.WriteLine("| 3 - Rechercher un utilisateur avec son ID |"); + Console.WriteLine("| 4 - Ajouter un utilisateur |"); + Console.WriteLine("| 5 - Mettre à jour un utilisateur |"); + Console.WriteLine("| 6 - Supprimer un utilisateur |"); + Console.WriteLine("| q - Quitter |"); + Console.WriteLine("|------------------------------------------------|"); + } + + Menu(); + Console.WriteLine("\nSaisie :"); + var saisie = Console.ReadLine(); + + while (saisie != "q") { + switch (saisie) + { + case "1": + PrintUsers(); + break; + case "2": + SearchUserByUsername(); + break; + case "3": + SearchUserById(); + break; + case "4": + AddUser(); + break; + case "5": + UpdateUser(); + break; + case "6": + DeleteUser(); + break; + case "t": + AutoTests(); + break; + default: + break; + } + Console.WriteLine("\nAppuyez sur n'importe quelle touche pour continuer..."); + Console.ReadKey(); + Console.Clear(); + Menu(); + Console.WriteLine("\nSaisie :"); + saisie = Console.ReadLine(); + } + + void AutoTests() + { + // Affichage des utilisateurs + Console.WriteLine("\n##########################################################\n"); + Console.WriteLine("Affichages des utilisateurs stubbés dans le contexte :\n"); + var res = controller.GetUsers(1, 10) as OkObjectResult; + if(res == null) + { + Console.WriteLine("\nErreur lors de l'acquisition de la liste des utilisateurs"); + } + else + { + var users = res.Value as IEnumerable; + if(users == null) { + Console.WriteLine("\nErreur, les ustilisateurs n'ont pas été trouvés !"); + } + else + { + PrintUsers(); + } + } + + // Recherche d'utilisateur par ID + Console.WriteLine("\n##########################################################\n"); + Console.WriteLine("Affichage de l'utilisateur ayant pour identifiant 1 :\n"); + var res1 = controller.GetUserById(1) as OkObjectResult; + if (res1 == null) + { + Console.WriteLine("\nErreur lors de l'acquisition de l'utilisateur !"); + } + else + { + var user = res1.Value as UserDTO; + if (user == null) + { + Console.WriteLine("\nErreur, l'utilisateur n'existe pas !"); + } + else + { + Console.WriteLine(user); + } + } + + // Recherche d'utilisateur par pseudonyme + Console.WriteLine("\n##########################################################\n"); + Console.WriteLine("Affichage de l'utilisateur ayant pour username johnny :\n"); + var res2 = controller.GetUserByUsername("johnny") as OkObjectResult; + if (res2 == null) + { + Console.WriteLine("\nErreur lors de l'acquisition de l'utilisateur !"); + } + else + { + var user1 = res2.Value as UserDTO; + if (user1 == null) + { + Console.WriteLine("\nErreur, l'utilisateur n'existe pas !"); + } + else + { + Console.WriteLine(user1); + } + } + + // Ajout d'un utilisateur + Console.WriteLine("\n##########################################################\n"); + Console.WriteLine("Création de l'utilisateur :\n"); + var user2 = new UserDTO("JohnDoe", "motdepasse", "johndoe@gmail.com", false); + Console.WriteLine(user2); + var res3 = controller.CreateUser(user2) as CreatedResult; + if (res3 == null) + { + Console.WriteLine("\nErreur lors de la création de l'utilisateur !"); + } + else + { + Console.WriteLine("\nUtilisateur créé avec succès !"); + } + + // Affichage des utilisateurs + Console.WriteLine("\n##########################################################\n"); + PrintUsers(); + + // Mise à jour d'un utilisateur + Console.WriteLine("\n##########################################################\n"); + Console.WriteLine("Mise à jour de l'adresse email de l'utilisateur :\n"); + user2 = ((controller.GetUserByUsername("JohnDoe") as OkObjectResult).Value as UserDTO); + if (user2 == null) + { + Console.WriteLine("\nErreur lors de la récupération de l'utilisateur !"); + } + else + { + Console.WriteLine(user2); + Console.WriteLine("\nNouvelle adresse : John.DOE@etu.uca.fr"); + var user3 = new UserDTO(user2.Id, user2.Username, user2.Password, "John.DOE@etu.uca.fr", user2.IsAdmin); + var res4 = controller.UpdateUser(user2.Id, user3) as OkObjectResult; + if (res4 == null) + { + Console.WriteLine("\nErreur lors de la mise à jour de l'utilisateur !"); + } + else + { + Console.WriteLine("\nUtilisateur mis à jour avec succès !"); + } + } + // Affichage des utilisateurs + + Console.WriteLine("\n##########################################################\n"); + PrintUsers(); + + // Suppression d'un utilisateur + Console.WriteLine("\n##########################################################\n"); + Console.WriteLine("Suppression de l'utilisateur JohnDoe:\n"); + user2 = ((controller.GetUserByUsername("JohnDoe") as OkObjectResult).Value as UserDTO); + if (user2 == null) + { + Console.WriteLine("\nErreur lors de la récupération de l'utilisateur !"); + } + else + { + Console.WriteLine(user2); + var res5 = controller.DeleteUser(user2.Id) as OkObjectResult; + if (res5 == null) + { + Console.WriteLine("\nErreur lors de la suppression de l'utilisateur !"); + } + else + { + Console.WriteLine("\nUtilisateur supprimé avec succès !"); + } + } + // Affichage des utilisateurs + + Console.WriteLine("\n##########################################################\n"); + PrintUsers(); + } +} \ No newline at end of file diff --git a/API_SQLuedo/TestConsoleAPI/TestConsoleAPI.csproj b/API_SQLuedo/TestConsoleAPI/TestConsoleAPI.csproj new file mode 100644 index 0000000..c013237 --- /dev/null +++ b/API_SQLuedo/TestConsoleAPI/TestConsoleAPI.csproj @@ -0,0 +1,21 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + + + + + + + + diff --git a/API_SQLuedo/TestEF/TestEF.csproj b/API_SQLuedo/TestEF/TestEF.csproj index bda60d7..9d1ad3b 100644 --- a/API_SQLuedo/TestEF/TestEF.csproj +++ b/API_SQLuedo/TestEF/TestEF.csproj @@ -10,19 +10,20 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + - - + + runtime; build; native; contentfiles; analyzers; buildtransitive all From 4c8c5d20ac76d23d4eae5f61e2a042eb7aaa5c0c Mon Sep 17 00:00:00 2001 From: "Johnny.Ratton" Date: Sat, 17 Feb 2024 11:37:16 +0100 Subject: [PATCH 10/18] Ajout du versionnement de l'API --- API_SQLuedo/API/API.csproj | 1 + API_SQLuedo/API/Controllers/UserController.cs | 3 ++- API_SQLuedo/API/Program.cs | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/API_SQLuedo/API/API.csproj b/API_SQLuedo/API/API.csproj index f3c90dd..822644c 100644 --- a/API_SQLuedo/API/API.csproj +++ b/API_SQLuedo/API/API.csproj @@ -9,6 +9,7 @@ + all diff --git a/API_SQLuedo/API/Controllers/UserController.cs b/API_SQLuedo/API/Controllers/UserController.cs index 8518f62..6d2e9d6 100644 --- a/API_SQLuedo/API/Controllers/UserController.cs +++ b/API_SQLuedo/API/Controllers/UserController.cs @@ -8,8 +8,9 @@ using Services; namespace API.Controllers { - [Route("api/[controller]")] + [Route("api/{version:apiVersion}/[controller]")] [Authorize] + [ApiVersion("1.0")] [ApiController] public class UserController : Controller { diff --git a/API_SQLuedo/API/Program.cs b/API_SQLuedo/API/Program.cs index d4dbe01..63d3d14 100644 --- a/API_SQLuedo/API/Program.cs +++ b/API_SQLuedo/API/Program.cs @@ -1,6 +1,7 @@ using API; using DbContextLib; using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc.Versioning; using Microsoft.EntityFrameworkCore; using Microsoft.OpenApi.Models; using Services; @@ -18,6 +19,7 @@ builder.Services.AddDbContext(); builder.Services.AddDbContext(options => options.UseInMemoryDatabase("appDb")); builder.Services.AddIdentityApiEndpoints().AddEntityFrameworkStores(); builder.Services.AddAuthorization(); +builder.Services.AddApiVersioning(o => o.ApiVersionReader = new HeaderApiVersionReader("api-version")); //builder.Services.AddIdentityApiEndpoints() // .AddEntityFrameworkStores(); builder.Services.AddSwaggerGen(option => From ad336d48f3842be787f50793748bb8e1416e0daf Mon Sep 17 00:00:00 2001 From: clchieu Date: Tue, 20 Feb 2024 23:34:29 +0100 Subject: [PATCH 11/18] =?UTF-8?q?:construction=5Fworker:=20:construction:?= =?UTF-8?q?=20D=C3=A9but=20de=20la=20ci/cd?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- drone.yml | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 drone.yml diff --git a/drone.yml b/drone.yml new file mode 100644 index 0000000..e104556 --- /dev/null +++ b/drone.yml @@ -0,0 +1,23 @@ +kind: pipeline +type: docker +name: SQLuedoCICD + +trigger: + event: + - push + +steps: + - name: build + image: mcr.microsoft.com/dotnet/sdk:8.0 + commands: + - cd API_SQLuedo/ + - dotnet restore API_SQLuedo.sln + - dotnet build API_SQLuedo.sln -c Release --no-restore + + - name: tests + image: mcr.microsoft.com/dotnet/sdk:8.0 + commands: + - cd API_SQLuedo/ + - dotnet test API_SQLuedo.sln -c Release --no-build --no-restore + depends_on: + - [build] \ No newline at end of file From 6f9ee116fbc9d9cbc94fe6e6c58080e77a2550c0 Mon Sep 17 00:00:00 2001 From: clchieu Date: Wed, 21 Feb 2024 22:16:19 +0100 Subject: [PATCH 12/18] :construction: Ajout de la code inspection --- drone.yml | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/drone.yml b/drone.yml index e104556..d3a1a7f 100644 --- a/drone.yml +++ b/drone.yml @@ -13,11 +13,32 @@ steps: - cd API_SQLuedo/ - dotnet restore API_SQLuedo.sln - dotnet build API_SQLuedo.sln -c Release --no-restore - + - name: tests image: mcr.microsoft.com/dotnet/sdk:8.0 commands: - cd API_SQLuedo/ - dotnet test API_SQLuedo.sln -c Release --no-build --no-restore depends_on: - - [build] \ No newline at end of file + - [ build ] + + - name: code-inspection + image: hub.codefirst.iut.uca.fr/marc.chevaldonne/codefirst-dronesonarplugin-dotnet8 + secrets: [ SECRET_SONAR_LOGIN ] + environment: + sonar_host: https://codefirst.iut.uca.fr/sonar/ + sonar_token: + from_secret: LOGIN_SECURE_TOKEN + project_key: API_SQLuedo + coverage_exclusions: "Test*/**" + commands: + - cd Sources/ + - dotnet restore API_SQLuedo.sln + - dotnet sonarscanner begin /k:$${project_key} /d:sonar.host.url=$${sonar_host} /d:sonar.coverageReportPaths="coveragereport/SonarQube.xml" /d:sonar.coverage.exclusions=$${coverage_exclusions} /d:sonar.login=$${sonar_token} + - dotnet build API_SQLuedo.sln -c Release --no-restore + - dotnet test API_SQLuedo.sln --logger trx --no-restore /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura --collect "XPlat Code Coverage" + - reportgenerator -reports:"**/coverage.cobertura.xml" -reporttypes:SonarQube -targetdir:"coveragereport" + - dotnet publish API_SQLuedo.sln -c Release --no-restore -o CI_PROJECT_DIR/build/release + - dotnet sonarscanner end /d:sonar.login=$${sonar_token} + depends_on: + - [ build ] \ No newline at end of file From cd17c5978907cbea48dc45219b60d419db010db7 Mon Sep 17 00:00:00 2001 From: clchieu Date: Wed, 21 Feb 2024 22:20:50 +0100 Subject: [PATCH 13/18] :construction: Modification du nom de la ci, ajout de restore dans le test et ajout vers le bon dossier --- drone.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/drone.yml b/drone.yml index d3a1a7f..3d73d76 100644 --- a/drone.yml +++ b/drone.yml @@ -1,6 +1,6 @@ kind: pipeline type: docker -name: SQLuedoCICD +name: API_SQLuedo trigger: event: @@ -18,6 +18,7 @@ steps: image: mcr.microsoft.com/dotnet/sdk:8.0 commands: - cd API_SQLuedo/ + - dotnet restore API_SQLuedo.sln - dotnet test API_SQLuedo.sln -c Release --no-build --no-restore depends_on: - [ build ] @@ -32,7 +33,7 @@ steps: project_key: API_SQLuedo coverage_exclusions: "Test*/**" commands: - - cd Sources/ + - cd API_SQLuedo/ - dotnet restore API_SQLuedo.sln - dotnet sonarscanner begin /k:$${project_key} /d:sonar.host.url=$${sonar_host} /d:sonar.coverageReportPaths="coveragereport/SonarQube.xml" /d:sonar.coverage.exclusions=$${coverage_exclusions} /d:sonar.login=$${sonar_token} - dotnet build API_SQLuedo.sln -c Release --no-restore From 1f8592ef557ac58be58e7c0a66ff4e925868bc95 Mon Sep 17 00:00:00 2001 From: clchieu Date: Wed, 21 Feb 2024 22:27:14 +0100 Subject: [PATCH 14/18] :construction: test de la ci/cd --- drone.yml => .drone.yml | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename drone.yml => .drone.yml (100%) diff --git a/drone.yml b/.drone.yml similarity index 100% rename from drone.yml rename to .drone.yml From a0e80957ccd6c6e6aa23391e1483e626a45e602c Mon Sep 17 00:00:00 2001 From: clchieu Date: Wed, 21 Feb 2024 22:28:20 +0100 Subject: [PATCH 15/18] =?UTF-8?q?:construction:=20modification=20des=20d?= =?UTF-8?q?=C3=A9pendaces=20de=20test=20et=20de=20ci?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .drone.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.drone.yml b/.drone.yml index 3d73d76..ce63564 100644 --- a/.drone.yml +++ b/.drone.yml @@ -21,7 +21,7 @@ steps: - dotnet restore API_SQLuedo.sln - dotnet test API_SQLuedo.sln -c Release --no-build --no-restore depends_on: - - [ build ] + - [build] - name: code-inspection image: hub.codefirst.iut.uca.fr/marc.chevaldonne/codefirst-dronesonarplugin-dotnet8 @@ -42,4 +42,4 @@ steps: - dotnet publish API_SQLuedo.sln -c Release --no-restore -o CI_PROJECT_DIR/build/release - dotnet sonarscanner end /d:sonar.login=$${sonar_token} depends_on: - - [ build ] \ No newline at end of file + - [build] \ No newline at end of file From abef5133df8bb921daf9543833b009ac82dbf51f Mon Sep 17 00:00:00 2001 From: clchieu Date: Wed, 21 Feb 2024 22:30:29 +0100 Subject: [PATCH 16/18] =?UTF-8?q?:construction:=20Suppression=20de=20retou?= =?UTF-8?q?r=20=C3=A0=20la=20ligne=20et=20de=20tirets=20probl=C3=A9matique?= =?UTF-8?q?s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .drone.yml | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/.drone.yml b/.drone.yml index ce63564..d400fdd 100644 --- a/.drone.yml +++ b/.drone.yml @@ -20,8 +20,7 @@ steps: - cd API_SQLuedo/ - dotnet restore API_SQLuedo.sln - dotnet test API_SQLuedo.sln -c Release --no-build --no-restore - depends_on: - - [build] + depends_on: [ build ] - name: code-inspection image: hub.codefirst.iut.uca.fr/marc.chevaldonne/codefirst-dronesonarplugin-dotnet8 @@ -41,5 +40,4 @@ steps: - reportgenerator -reports:"**/coverage.cobertura.xml" -reporttypes:SonarQube -targetdir:"coveragereport" - dotnet publish API_SQLuedo.sln -c Release --no-restore -o CI_PROJECT_DIR/build/release - dotnet sonarscanner end /d:sonar.login=$${sonar_token} - depends_on: - - [build] \ No newline at end of file + depends_on: [ build ] \ No newline at end of file From 30b154d58657cafd9e260fb875ff20fa38cfea31 Mon Sep 17 00:00:00 2001 From: clchieu Date: Wed, 21 Feb 2024 22:36:47 +0100 Subject: [PATCH 17/18] :construction: Tentative de modification du sonar token --- .drone.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.drone.yml b/.drone.yml index d400fdd..483215f 100644 --- a/.drone.yml +++ b/.drone.yml @@ -28,7 +28,7 @@ steps: environment: sonar_host: https://codefirst.iut.uca.fr/sonar/ sonar_token: - from_secret: LOGIN_SECURE_TOKEN + from_secret: SECRET_SONAR_LOGIN project_key: API_SQLuedo coverage_exclusions: "Test*/**" commands: From c2468b68f4c58e51f59c0e9c0a2c01e4745f5ffc Mon Sep 17 00:00:00 2001 From: "Johnny.Ratton" Date: Fri, 23 Feb 2024 18:56:34 +0100 Subject: [PATCH 18/18] =?UTF-8?q?D=C3=A9but=20de=20la=20r=C3=A9daction=20d?= =?UTF-8?q?u=20README=20pour=20expliquer=20comment=20tout=20configurer=20p?= =?UTF-8?q?our=20que=20l'API=20fonctionne?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 84 +++++++++++++++++++++++++++++++++++++++++++ Ressources/image.png | Bin 0 -> 1689 bytes 2 files changed, 84 insertions(+) create mode 100644 Ressources/image.png diff --git a/README.md b/README.md index c3534c5..5b41071 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,86 @@ # API_SQLuedo +## Configuration de l'API + +### Au niveau de la solution du projet : + +- > Création des migrations + +```sh + dotnet ef migrations add MigrationName --project .\DbContextLib --context UserDbContext --startup-project .\API +``` + +- > Mise à jour de la base de données : + +```sh + dotnet ef database update --project .\DbContextLib --startup-project .\API +``` + +- > Exécuter le projet de l'API avec votre IDE + +![alt text](Ressources/image.png) + +
+ +## Caractéristiques de l'API + +### Source de données +--- +L'API est actuellement reliée à un projet __EntityFramework__ qui lui fournit les données dont elle a besoin. +La partie EntityFramework est, elle, reliée à une base de donnée __PostgreSQL__ mais peut très bien être reliée à un autre fournisseur de BDD en injectant un DbContextOptions configuré dans le au moment de l'instanciation du UserDbContext. + +--- +### Injecter un fournisseur de BDD alternatif +```C# + var options = new DbContextOptionsBuilder() + .UseNpgsql() + .Options; + + var dbContext = new UserDbContext(options); +``` +--- +### Configuration de la base de données + +Pour ce qui est de la base de données, il faut évidemment installer PostgreSQL.
+La classe UserDbContext utilise par défaut PostgreSQL à partir d'un utilisateur __admin__ qu'il faut créer au préalable. L'utilisateur __admin__ devra posséder le droit de créer une base de données et devra disposer de tous les droits d'édition sur celle-ci. + +```SQL + CREATE USER admin WITH PASSWORD "motdepasse"; + GRANT pg_read_all_data TO admin; + GRANT pg_write_all_data TO admin; + ALTER USER admin CREATEDB; +``` +--- +### Dans le DbContext + +Il faut également adapter la configuration de la connexion à la base de données dans le UserDbContext afin de l'adapter en fonction de la configuration que vous décidez de faire. Par défaut, si vous avez une base PostgreSQL sur la même machine que celle qui fait tourner l'API et que vous avez utilisé les commandes SQL fournies à l'identique, cela devrait fonctionner sans problème. Sinon, vous pouvez modifier le DbContext dans la méthode OnConfiguring ci-dessous : +>UserDbContext.cs +```C# + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + if (!optionsBuilder.IsConfigured) + { // Modifier la ligne ci-dessous en fonction de votre configuration + optionsBuilder.UseNpgsql("Host=localhost;Database=SQLuedo;Username=admin;Password=motdepasse"); + } + base.OnConfiguring(optionsBuilder); + } +``` + +--- + +### Utilisation de l'interface Swagger +Pour tester manuellement l'API, à l'exécution du projet de celle-ci, une interface Swagger s'ouvre dans votre navigateur. Etant donné que l'API est configurée pour demander une autentification à l'utilisateur, vous devrez alors créer un compte sur Swagger (qui ne sera valable que pour l'exécution en cours). + +Vous pourrez alors pour cela sélectionner la rubrique Register et entrer une __adresse email__ et un __mot de passe__ quelconque dans l'objet Json puis appuyer sur __Exécuter__. + +Ensuite, il vous faudra vous connecter via la rubrique Login pour laquelle vous n'aurez qu'à entrer l'email et le mot de passe précédents. Vous pouvez également activer les cookies si vous le souhaitez pour une persistance de la connexion. + +Voilà, vous pouvez maintenant utilisez librement l'API ! + +--- + +### Versionnement + +Notre API est versionnée ce qui signifie qu'à chaque requête, la version souhaitée de l'API doit être fournie. Pour l'instant, il n'y a qu'une __version 1.0__. + +--- \ No newline at end of file diff --git a/Ressources/image.png b/Ressources/image.png new file mode 100644 index 0000000000000000000000000000000000000000..02f648570caf9ca042b6359a6b65086474eee533 GIT binary patch literal 1689 zcmZ{ldpH~B9>-tTX{lNp(PDxQnRaazQ5@oux>F)9b-$Ga!9+qurR&(1R%o8l&8?FV{);wy*(OIoyE*{|Pj^)YiV2S1jsQF=Qr(MIlJS8ww@U;7 zphh2-oICo{H!?F4hY8N`Pr;>mU(Se*i_VCac>s_NW0P@dzNxsB41%FeDA_Q}(B|wZ z!z(hqdg{MqVP^H0Y-#qtz#nlLhF_ihYLE(mQm;G85t9`mT0pw#;&l7BOoqZ^OTxa3 zi9vh=<z!|MDjw*aa)z?jCeET4*dfg!6Y<_T@KQ=gw zv8AFL3=i8^bB8s%)5%MGzZqiC&P73~cPH%F>&i^ylRl3QcU_^x`k)NyMe;x&m`Lqp z_vWf12jrdqP6)q|o$z@4z6$8UCna%V)up}%WO;u-qn3^ikw{KIIV2>6V^`u!xO+q% zD1NQ+Cs|r0)DgE&c0zTi>_ecx@6Ju3=g#Wx<_z)m-f;?afF>KMc~zd%xWnJ%3HxDI z8LQJq4R@8Ft1CFr{UfW!TVYH;O-o>)2rlae1wdfo)7z8R=AN+Vryz`mWQl3z?8XNXWVPkT!6DS#B-P=Hz}wpc zpfl{^oqufogjToJvIy0zq)xuU@>Tc{7v1xe$1!5iJ-bVu+I9ewmQ*lm_N{!AgC&RlSDY7P5bP&Hjkxi?bb z6*y>}*NlkQ{CD?H3@-rCp_f6XOX~wyn6a3!U!Q#E1#*`vG zyYUY44(F<6qFQxcvht97V!8>2gGbl0%(^bs7q;Dnig=;f!N;P&bI-a7kNfCF`(#o> zRo{yX9h9BLDm%IRh8Bem_KVe;WBI2E`Gth_` z4Uo2&rt7=UO%bPZQxgKxrxFMuUy;TJ+Z!0lb-ogVl@6Ua^9O<$-q(6_RzZz939@$% z|3#P}zQ4^yT^RCBS&W4};v+J}+zsFU`A%!2U^J{j8up=0_Pig~pp;o}T+!OyhEoFoAKK3X252b5*^N~vY zfzg7-{TRAivHq|^S`d4s^%OkI!@5h0a&q(*Y2YBoz{s_g!3V`~in{(EtwQ?I literal 0 HcmV?d00001