fixing
continuous-integration/drone/push Build is passing Details

Cleaning
David D'ALMEIDA 2 years ago
parent 93b1ec94da
commit 0c69cd0add

@ -3,6 +3,8 @@ using Microsoft.AspNetCore.Mvc;
using Model; using Model;
using API_LoL_Project.Controllers.Response; using API_LoL_Project.Controllers.Response;
using API_LoL_Project.Middleware; 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 // 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/<RuneController> // GET: api/rune
[HttpGet] [HttpGet("/all")]
public async Task<ActionResult<IEnumerable<RuneDTO>>> GetAllRunes([FromQuery] Request.PageRequest request) public async Task<ActionResult<IEnumerable<RuneDTO>>> GetAllRunes([FromQuery] Request.PageRequest request)
{ {
try try
@ -44,14 +46,14 @@ namespace API_LoL_Project.Controllers.version2
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(GetAllRunes), request); ; _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)); var runes = await dataManager.GetItems(request.index, request.count, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending));
IEnumerable<RuneDTO> res = runes.Select(c => c.toDTO()); IEnumerable<RuneDTO> res = runes.Select(c => c.ToDTO());
if (res.Count() <= 0 || res == null) if (res.Count() <= 0 || res == null)
{ {
_logger.LogError("No runes found the total count is {totalcount} ", totalcount); _logger.LogError("No runes found the total count is {totalcount} ", totalcount);
return BadRequest("No runes found : totalcount is : " + totalcount); return BadRequest("No runes found : totalcount is : " + totalcount);
} }
var respList = res.Select(r => new LolResponce<RuneDTO> var respList = res.Select(r => new LolResponse<RuneDTO>
( (
r, r,
new List<EndPointLink> new List<EndPointLink>
@ -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"), 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(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/<RuneController> // GET: api/<RuneController>
/* [HttpGet] [HttpGet]
public async Task<ActionResult<IEnumerable<RuneDTO>>> Get([FromQuery] Request.PageRequest request) public async Task<ActionResult<IEnumerable<RuneDTO>>> Get([FromQuery] Request.PageRequest request)
{ {
try try
{ {
var totalcount = await runesManager.GetNbItems(); var totalcount = await dataManager.GetNbItems();
if (request.count + request.index > totalcount) if (request.count + request.index > totalcount)
{ {
_logger.LogWarning("to many rows ask the max is {totalcount}", 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); _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)); var runes = await dataManager.GetItems(request.index, totalcount, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending));
IEnumerable<RuneDTO> res = runes.Select(c => c.toDTO()); IEnumerable<RuneDTO> res = runes.Select(c => c.ToDTO());
if (res.Count() >= 0 || res == null) if (res.Count() >= 0 || res == null)
{ {
_logger.LogWarning("No runes found with Id"); _logger.LogWarning("No runes found with Id");
@ -112,10 +113,10 @@ namespace API_LoL_Project.Controllers.version2
} }
*/
/*
[HttpGet("{name}")] [HttpGet("{name}")]
public async Task<ActionResult<LolResponce<RuneDTO>>> GetRuneByName(string name) public async Task<ActionResult<LolResponse<RuneDTO>>> GetRuneByName(string name)
{ {
try try
{ {
@ -123,7 +124,7 @@ namespace API_LoL_Project.Controllers.version2
var rune = await dataManager var rune = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems()); .GetItemsByName(name, 0, await dataManager.GetNbItems());
_logger.LogInformation("Executing {Action} with name : {runeName}", nameof(GetRuneByName), name); _logger.LogInformation("Executing {Action} with name : {runeName}", nameof(GetRuneByName), name);
RuneDTO res = rune.First().toDTO(); RuneDTO res = rune.First().ToDTO();
if (res == null) if (res == null)
{ {
@ -137,53 +138,18 @@ namespace API_LoL_Project.Controllers.version2
EndPointLink.To($"/api/[controller]/{res.Name}/", "self") EndPointLink.To($"/api/[controller]/{res.Name}/", "self")
}; };
var response = new LolResponce<RuneDTO>(res, links); var response = new LolResponse<RuneDTO>(res, links);
return Ok(response); return Ok(response);
} }
catch (Exception e) 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); return BadRequest(e.Message);
} }
}*/
/* // GET api/<RuneController>/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/<RuneController>
// PUT api/<RuneController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
} }
// DELETE api/<RuneController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
} }
} }

@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Model; using Model;
using ApiMappeur; 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 // 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]")] [Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("2.0")] [ApiVersion("2.0")]
[ServiceFilter(typeof(AuthMiddlewareFliter))]
[ApiController] [ApiController]
public class RunePageController : ControllerBase public class RunePageController : ControllerBase
{ {
@ -23,7 +25,7 @@ namespace API_LoL_Project.Controllers.version2
this.dataManager = dataManager.RunePagesMgr; this.dataManager = dataManager.RunePagesMgr;
_logger = logger; _logger = logger;
} }
// GET: api/<RunePageController> // GET: api/runePage
[HttpGet] [HttpGet]
public async Task<ActionResult<PageResponse<RunePageDTO>>> Get([FromQuery] Request.PageRequest request) public async Task<ActionResult<PageResponse<RunePageDTO>>> Get([FromQuery] Request.PageRequest request)
{ {
@ -122,16 +124,15 @@ namespace API_LoL_Project.Controllers.version2
[HttpPost] [HttpPost]
public async Task<IActionResult> Post([FromBody] RunePageDTO runePage) public async Task<IActionResult> 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 try
{ {
if (await dataManager.GetNbItemsByName(runePage.Name) == 0) if (await dataManager.GetNbItemsByName(runePage.Name) == 0)
{ {
return CreatedAtAction(nameof(Get), return CreatedAtAction(nameof(Get),(await dataManager.AddItem(runePage.ToModel())).ToDto());
(await dataManager.AddItem(runePage.ToModel())).ToDto());
} }
_logger.LogWarning($"Name : {runePage.Name} is already exist"); _logger.LogWarning($"Name : {runePage.Name} already exist");
return BadRequest($"Name : {runePage.Name} is already exist"); return BadRequest($"Name : {runePage.Name} already exist");
} }
catch (Exception error) catch (Exception error)
{ {

@ -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<string>(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;
}
}
}

@ -7,7 +7,8 @@ using Model;
using StubLib; using StubLib;
using API_LoL_Project; using API_LoL_Project;
using API_LoL_Project.JsonConverter; using API_LoL_Project.JsonConverter;
using API_LoL_Project.Middleware.Auth;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -21,7 +22,39 @@ builder.Services.AddControllers().AddJsonOptions(options =>
}); });
builder.Services.AddEndpointsApiExplorer(); 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<string>()
}
};
cont.AddSecurityRequirement(requirement);
}
);
builder.Services.AddApiVersioning(opt => builder.Services.AddApiVersioning(opt =>
{ {
@ -38,6 +71,8 @@ builder.Services.AddVersionedApiExplorer(setup =>
}); });
builder.Services.AddScoped<AuthMiddlewareFliter>();
builder.Services.AddSingleton<IDataManager, DbData>(); builder.Services.AddSingleton<IDataManager, DbData>();
//builder.Services.AddSingleton<IDataManager, StubData>(); //builder.Services.AddSingleton<IDataManager, StubData>();
@ -64,6 +99,7 @@ if (app.Environment.IsDevelopment())
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseAuthorization(); app.UseAuthorization();
app.MapControllers(); app.MapControllers();

@ -1,4 +1,8 @@
{ {
"Authentification": {
"ApiKey" : "ViveC#"
},
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Information",

@ -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";
}
}
Loading…
Cancel
Save