From 0c69cd0addabe1ab35102ccaf15797038e7ccde3 Mon Sep 17 00:00:00 2001 From: dadalmeida1 Date: Mon, 27 Mar 2023 08:16:59 +0200 Subject: [PATCH] fixing --- .../Controllers/version2/RuneController.cs | 70 +++++------------- .../version2/RunePageController.cs | 13 ++-- .../Entities.LolDatabase.db-shm | Bin 32768 -> 32768 bytes .../Entities.LolDatabase.db-wal | Bin 168952 -> 189552 bytes .../Middleware/Auth/AuthMiddlewareFliter.cs | 34 +++++++++ .../Sources/API_LoL_Project/Program.cs | 40 +++++++++- .../Sources/API_LoL_Project/appsettings.json | 4 + .../API_LoL_Project/utils/AuthUtils.cs | 10 +++ 8 files changed, 111 insertions(+), 60 deletions(-) create mode 100644 EntityFramework_LoL/Sources/API_LoL_Project/Middleware/Auth/AuthMiddlewareFliter.cs create mode 100644 EntityFramework_LoL/Sources/API_LoL_Project/utils/AuthUtils.cs diff --git a/EntityFramework_LoL/Sources/API_LoL_Project/Controllers/version2/RuneController.cs b/EntityFramework_LoL/Sources/API_LoL_Project/Controllers/version2/RuneController.cs index 3b01397..d5a89bf 100644 --- a/EntityFramework_LoL/Sources/API_LoL_Project/Controllers/version2/RuneController.cs +++ b/EntityFramework_LoL/Sources/API_LoL_Project/Controllers/version2/RuneController.cs @@ -3,6 +3,8 @@ using Microsoft.AspNetCore.Mvc; using Model; using API_LoL_Project.Controllers.Response; using API_LoL_Project.Middleware; +using ApiMappeur; +using API_LoL_Project.Controllers.Response; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 @@ -29,8 +31,8 @@ namespace API_LoL_Project.Controllers.version2 - /*// GET: api/ - [HttpGet] + // GET: api/rune + [HttpGet("/all")] public async Task>> GetAllRunes([FromQuery] Request.PageRequest request) { try @@ -44,14 +46,14 @@ namespace API_LoL_Project.Controllers.version2 _logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(GetAllRunes), request); ; var runes = await dataManager.GetItems(request.index, request.count, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending)); - IEnumerable res = runes.Select(c => c.toDTO()); + IEnumerable res = runes.Select(c => c.ToDTO()); if (res.Count() <= 0 || res == null) { _logger.LogError("No runes found the total count is {totalcount} ", totalcount); return BadRequest("No runes found : totalcount is : " + totalcount); } - var respList = res.Select(r => new LolResponce + var respList = res.Select(r => new LolResponse ( r, new List @@ -61,7 +63,6 @@ namespace API_LoL_Project.Controllers.version2 EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetAllRunes)}", "self"), EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetAllRunes)}", "self"), EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetAllRunes)}", "self","POST"), - EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Put)}", "self","PUT"), } )); @@ -76,16 +77,16 @@ namespace API_LoL_Project.Controllers.version2 } } - */ + // GET: api/ - /* [HttpGet] + [HttpGet] public async Task>> Get([FromQuery] Request.PageRequest request) { try { - var totalcount = await runesManager.GetNbItems(); + var totalcount = await dataManager.GetNbItems(); if (request.count + request.index > totalcount) { _logger.LogWarning("to many rows ask the max is {totalcount}", totalcount); @@ -94,8 +95,8 @@ namespace API_LoL_Project.Controllers.version2 _logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request); - var runes = await runesManager.GetItems(request.PageNumber, totalcount, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending)); - IEnumerable res = runes.Select(c => c.toDTO()); + var runes = await dataManager.GetItems(request.index, totalcount, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending)); + IEnumerable res = runes.Select(c => c.ToDTO()); if (res.Count() >= 0 || res == null) { _logger.LogWarning("No runes found with Id"); @@ -112,10 +113,10 @@ namespace API_LoL_Project.Controllers.version2 } - */ - /* + + [HttpGet("{name}")] - public async Task>> GetRuneByName(string name) + public async Task>> GetRuneByName(string name) { try { @@ -123,7 +124,7 @@ namespace API_LoL_Project.Controllers.version2 var rune = await dataManager .GetItemsByName(name, 0, await dataManager.GetNbItems()); _logger.LogInformation("Executing {Action} with name : {runeName}", nameof(GetRuneByName), name); - RuneDTO res = rune.First().toDTO(); + RuneDTO res = rune.First().ToDTO(); if (res == null) { @@ -137,53 +138,18 @@ namespace API_LoL_Project.Controllers.version2 EndPointLink.To($"/api/[controller]/{res.Name}/", "self") }; - var response = new LolResponce(res, links); + var response = new LolResponse(res, links); return Ok(response); } catch (Exception e) { - _logger.LogError("Somthing goes wrong caching the Champions controller : " + e.Message); + _logger.LogError("Somthing goes wrong catching bt the Runnes controller : " + e.Message); return BadRequest(e.Message); } - }*/ - - /* // GET api//5 - [HttpGet("{id}")] - public string Get(int id) - { - try - { - var rune = await dataManager - .GetItemsByName(name, 0, await dataManager.GetNbItems()); - RuneDto result = champion.First().toDTO(); - return Ok(result); - } - catch (Exeption e) - { - - new HttpException(400, 'Cannot get rune :' + e.message); - } - - - }*/ - - // POST api/ - - - // PUT api//5 - [HttpPut("{id}")] - public void Put(int id, [FromBody] string value) - { - - } + } - // DELETE api//5 - [HttpDelete("{id}")] - public void Delete(int id) - { - } } } diff --git a/EntityFramework_LoL/Sources/API_LoL_Project/Controllers/version2/RunePageController.cs b/EntityFramework_LoL/Sources/API_LoL_Project/Controllers/version2/RunePageController.cs index 999438b..395092c 100644 --- a/EntityFramework_LoL/Sources/API_LoL_Project/Controllers/version2/RunePageController.cs +++ b/EntityFramework_LoL/Sources/API_LoL_Project/Controllers/version2/RunePageController.cs @@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Hosting; using Model; using ApiMappeur; +using API_LoL_Project.Middleware.Auth; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 @@ -12,6 +13,7 @@ namespace API_LoL_Project.Controllers.version2 { [Route("api/v{version:apiVersion}/[controller]")] [ApiVersion("2.0")] + [ServiceFilter(typeof(AuthMiddlewareFliter))] [ApiController] public class RunePageController : ControllerBase { @@ -23,7 +25,7 @@ namespace API_LoL_Project.Controllers.version2 this.dataManager = dataManager.RunePagesMgr; _logger = logger; } - // GET: api/ + // GET: api/runePage [HttpGet] public async Task>> Get([FromQuery] Request.PageRequest request) { @@ -122,16 +124,15 @@ namespace API_LoL_Project.Controllers.version2 [HttpPost] public async Task Post([FromBody] RunePageDTO runePage) { - _logger.LogInformation("method {Action} - RUNEPAGE call with {item}", nameof(Post), runePage); + _logger.LogInformation("method {Action} - RunPageController with {item}", nameof(Post), runePage); try { if (await dataManager.GetNbItemsByName(runePage.Name) == 0) { - return CreatedAtAction(nameof(Get), - (await dataManager.AddItem(runePage.ToModel())).ToDto()); + return CreatedAtAction(nameof(Get),(await dataManager.AddItem(runePage.ToModel())).ToDto()); } - _logger.LogWarning($"Name : {runePage.Name} is already exist"); - return BadRequest($"Name : {runePage.Name} is already exist"); + _logger.LogWarning($"Name : {runePage.Name} already exist"); + return BadRequest($"Name : {runePage.Name} already exist"); } catch (Exception error) { diff --git a/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db-shm b/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db-shm index 0d14dc243e18eaf80d45661a448bd9cf3e0c3795..89e1d6ebf032289c890da20c485d1162c3feca16 100644 GIT binary patch delta 222 zcmZo@U}|V!s+V}A%K!t63=9H#K#n{R3m>1Oep7o*(EdL!;jt z!^{Sm`yUBF#hDoNCN{1XWC3znfmj5HMS)mmvmxVjhs{?UHMkhHfb8>(o6q>_F*0gH i*rx)Rm>KneY*oh1pF&=#G3o%>KbcrX8Ppkc!NLITy6v{|GbFTp2>P)YR=BP7hib2 zCRIJqC@=t-`5y^Dg@M*iY+SwBg>izzXxHda6USQmO##fIK!a5be#0+Gq YF>d}8@=6WJ`o+X7%Amg4kx`uy0QPD@$p8QV diff --git a/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db-wal b/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db-wal index b70852355ec33e8eaa73b8651d4f885f0000a0d5..fe89db55619224b519ae89186894439a6c5f8c06 100644 GIT binary patch delta 328 zcmeydoa@60?uHh|ElfWqPqz?e5)k2k-m!G~wK>Ol85kIt_@6NFf8&3$IZ@ySznuUR zlV(t9UTT12dTLN&UP^v02P2bYaY<2TUOG@QD-bj6|MMbVdnW4zn_975+ne`FbAe5H z%)tM6dx0|3O@3h^W=%#^Lzt%b1v5#BbWGy;{iD+VF~r_04E*o-uK?{m!7nAj#3HH5 z0kH>F>-2faOiDr)iYqIh-+1~2V%Jp${;S(BBr~1n_m^bRlti-(VhWQ0i=-qcgbjDU p4A80aF!!s^IW8QuM*Akj%-5h$cnx&TeST3cW=Te(AuthUtils.ApiKeySectionName); + if (!apiKey.Equals(clientApiKey)) + { + context.Result = new UnauthorizedObjectResult("ApiKey used is invalid"); + return; + } + + // If the API key is valid, allow the request to proceed. + await Task.CompletedTask; + } + } +} diff --git a/EntityFramework_LoL/Sources/API_LoL_Project/Program.cs b/EntityFramework_LoL/Sources/API_LoL_Project/Program.cs index ac2026c..a331e4a 100644 --- a/EntityFramework_LoL/Sources/API_LoL_Project/Program.cs +++ b/EntityFramework_LoL/Sources/API_LoL_Project/Program.cs @@ -7,7 +7,8 @@ using Model; using StubLib; using API_LoL_Project; using API_LoL_Project.JsonConverter; - +using API_LoL_Project.Middleware.Auth; +using Microsoft.OpenApi.Models; var builder = WebApplication.CreateBuilder(args); @@ -21,7 +22,39 @@ builder.Services.AddControllers().AddJsonOptions(options => }); builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); +builder.Services.AddSwaggerGen( cont => +{ + cont.AddSecurityDefinition("ApiKey", new Microsoft.OpenApi.Models.OpenApiSecurityScheme + { + Description = "The Key to acces to the API", + Type = SecuritySchemeType.ApiKey, + Name = "x-api-key", + In = ParameterLocation.Header, + Scheme = "ApiKeyScheme" + }); + + var scheme = new OpenApiSecurityScheme + { + Reference = new OpenApiReference + { + Type = ReferenceType.SecurityScheme, + Id = "ApiKey" + }, + In = ParameterLocation.Header + }; + + var requirement = new OpenApiSecurityRequirement + { + { + scheme, new List() + } + }; + cont.AddSecurityRequirement(requirement); + +} + + + ); builder.Services.AddApiVersioning(opt => { @@ -38,6 +71,8 @@ builder.Services.AddVersionedApiExplorer(setup => }); +builder.Services.AddScoped(); + builder.Services.AddSingleton(); //builder.Services.AddSingleton(); @@ -64,6 +99,7 @@ if (app.Environment.IsDevelopment()) app.UseHttpsRedirection(); + app.UseAuthorization(); app.MapControllers(); diff --git a/EntityFramework_LoL/Sources/API_LoL_Project/appsettings.json b/EntityFramework_LoL/Sources/API_LoL_Project/appsettings.json index 064a744..0c07a4f 100644 --- a/EntityFramework_LoL/Sources/API_LoL_Project/appsettings.json +++ b/EntityFramework_LoL/Sources/API_LoL_Project/appsettings.json @@ -1,4 +1,8 @@ { + + "Authentification": { + "ApiKey" : "ViveC#" + }, "Logging": { "LogLevel": { "Default": "Information", diff --git a/EntityFramework_LoL/Sources/API_LoL_Project/utils/AuthUtils.cs b/EntityFramework_LoL/Sources/API_LoL_Project/utils/AuthUtils.cs new file mode 100644 index 0000000..94966bd --- /dev/null +++ b/EntityFramework_LoL/Sources/API_LoL_Project/utils/AuthUtils.cs @@ -0,0 +1,10 @@ +namespace API_LoL_Project.utils +{ + public class AuthUtils + { + public const string ApiKeySectionName = "Authentification:ApiKey"; + public const string ApiKeyHeaderName = "x-api-key"; + + + } +}