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 0d14dc2..89e1d6e 100644 Binary files a/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db-shm and b/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db-shm differ 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 b708523..fe89db5 100644 Binary files a/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db-wal and b/EntityFramework_LoL/Sources/API_LoL_Project/Entities.LolDatabase.db-wal differ diff --git a/EntityFramework_LoL/Sources/API_LoL_Project/Middleware/Auth/AuthMiddlewareFliter.cs b/EntityFramework_LoL/Sources/API_LoL_Project/Middleware/Auth/AuthMiddlewareFliter.cs new file mode 100644 index 0000000..99e6d7d --- /dev/null +++ b/EntityFramework_LoL/Sources/API_LoL_Project/Middleware/Auth/AuthMiddlewareFliter.cs @@ -0,0 +1,34 @@ +using API_LoL_Project.utils; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace API_LoL_Project.Middleware.Auth +{ + public class AuthMiddlewareFliter : IAsyncAuthorizationFilter + { + private readonly IConfiguration _configuration; + + public AuthMiddlewareFliter(IConfiguration configuration) + { + this._configuration = configuration; + } + public async Task OnAuthorizationAsync(AuthorizationFilterContext context) + { + if (!context.HttpContext.Request.Headers.TryGetValue(AuthUtils.ApiKeyHeaderName, out var clientApiKey)) + { + context.Result = new UnauthorizedObjectResult("ApiKey is missing please ask author's permission"); + return; + } + + var apiKey = _configuration.GetValue(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"; + + + } +}