Skip to content

Commit

Permalink
45 authentication of backend data updating exception handling (Szops#50)
Browse files Browse the repository at this point in the history
* Added API Key

* Minor changes
  • Loading branch information
Matyjash authored Apr 3, 2022
1 parent 9e9b8e3 commit 3bd423c
Show file tree
Hide file tree
Showing 6 changed files with 104 additions and 54 deletions.
43 changes: 43 additions & 0 deletions api/SzopAPI/SzopAPI/Attributes/ApiKeyAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;

namespace SzopAPI.Attributes
{
[AttributeUsage(validOn: AttributeTargets.Class)]
public class ApiKeyAttribute : Attribute, IAsyncActionFilter
{
private const string APIKEYNAME = "ApiKey";
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (!context.HttpContext.Request.Headers.TryGetValue(APIKEYNAME, out var extractedApiKey))
{
context.Result = new ContentResult()
{
StatusCode = 401,
Content = "Api Key was not provided"
};
return;
}

var appSettings = context.HttpContext.RequestServices.GetRequiredService<IConfiguration>();

var apiKey = appSettings.GetValue<string>(APIKEYNAME);

if (!apiKey.Equals(extractedApiKey))
{
context.Result = new ContentResult()
{
StatusCode = 401,
Content = "Api Key is not valid"
};
return;
}

await next();
}
}
}
15 changes: 8 additions & 7 deletions api/SzopAPI/SzopAPI/Controllers/GetPointsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@
using SzopAPI.Data;
using SzopAPI.Data.Interface;
using SzopAPI.Data.Model;
using SzopAPI.Attributes;
using System.ComponentModel.DataAnnotations;

namespace SzopAPI.Controllers
{

[Route("api/get-points")]
[ApiKey]
[ApiController]
public class GetPointsController : ControllerBase
{
Expand All @@ -15,14 +19,11 @@ public class GetPointsController : ControllerBase

// POST api/<PointController>
[HttpPost]
public ActionResult<string> GetPoints(string url)
public ActionResult<string> GetPoints([Required] string url, [FromHeader(Name = "ApiKey")][Required] string apiKey)
{
bool success = LoadPoints.DownloadFile(url);
if (success)
{
return "OK";
}
else return "KO";
string message = LoadPoints.DownloadFile(url);

return message;
}


Expand Down
91 changes: 47 additions & 44 deletions api/SzopAPI/SzopAPI/Data/LoadPoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ public class LoadPoints
/// </summary>
/// <param name="url">URL to file</param>
/// <returns>true if download was successful, false if wasn't</returns>
public static bool DownloadFile(string url)
public static string DownloadFile(string url)
{
//download file from given url
string fileName = url;
bool success = false;
string returnMessage = "";
using (var webClient = new WebClient())
{
try
Expand All @@ -33,7 +33,8 @@ public static bool DownloadFile(string url)
}
catch (Exception e)
{
return success;
System.Diagnostics.Debug.WriteLine("Failed to download file: {0}", e);
return "Exception caught! Failed to download file.";
}
}

Expand All @@ -53,75 +54,76 @@ public static bool DownloadFile(string url)
bool same = CompareFiles(file, "Data/External/Temp/" + fileName);
if (same)
{
System.Diagnostics.Debug.WriteLine("They are the same! Deleting downloaded file!");
DeleteFile("Data/External/Temp/" + fileName);
success = true;
return success;
return "The same file already exists. No difference detected. No changes have been made";
}
else //if they are not the same replace old file with the downloaded one
{
System.Diagnostics.Debug.WriteLine("They are not the same. Updating files...");
DeleteFile(file);
File.Move("Data/External/Temp/" + fileName, file);
UpdateVersion();
success = true;
return success;
return "Although The same file already exists it is not the same. Updated xlsx file.";
}
}
}
System.Diagnostics.Debug.WriteLine("New file detected. Moving to main folder...");

//if the file doesnt exist in PointsSheets directory: move downloaded file to PointsSheets directory
File.Move("Data/External/Temp/" + fileName, "Data/External/PointsSheets/" + fileName);
UpdateVersion();

success = true;
return success;
return "No file with the same name detected. Downloaded file has been moved to PointsSheets";
}

public static List<Point> LoadPointFromXLSX(string fileName)
{
List<Point> points = new List<Point>();

using (var stream = File.Open("Data/External/PointsSheets/" + fileName, FileMode.Open, FileAccess.Read))
try
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
using (var stream = File.Open("Data/External/PointsSheets/" + fileName, FileMode.Open, FileAccess.Read))
{
int i = 0;
do
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
while (reader.Read())
int i = 0;
do
{
if (i > 0 && reader.GetValue(0) != null)
while (reader.Read())
{
Point point = new Point();

point.PointId = Convert.ToInt32(reader.GetDouble(0));
point.Street = reader.GetString(1);
point.Sector = reader.GetString(2);
point.Estate = reader.GetString(3);
//daty
point.OpeningDateTimes = new List<DateTime>();
string allDates = reader.GetString(4);
string pattern = @"\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])\ (0[0-9]|1[0-9]|2[0-4])\:([0-5][0-9])";
Regex re = new Regex(pattern);

foreach (Match match in re.Matches(allDates))
if (i > 0 && reader.GetValue(0) != null)
{
DateTime date = DateTime.Parse(match.Value);
point.OpeningDateTimes.Add(date);
}
//
point.Latitude = Convert.ToDouble(reader.GetString(5).Replace('.', ','));
point.Longitude = Convert.ToDouble(reader.GetString(6).Replace('.', ','));
point.Description = reader.GetString(7);
points.Add(point);
Point point = new Point();

point.PointId = Convert.ToInt32(reader.GetDouble(0));
point.Street = reader.GetString(1);
point.Sector = reader.GetString(2);
point.Estate = reader.GetString(3);
//daty
point.OpeningDateTimes = new List<DateTime>();
string allDates = reader.GetString(4);
string pattern = @"\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])\ (0[0-9]|1[0-9]|2[0-4])\:([0-5][0-9])";
Regex re = new Regex(pattern);

foreach (Match match in re.Matches(allDates))
{
DateTime date = DateTime.Parse(match.Value);
point.OpeningDateTimes.Add(date);
}
//
point.Latitude = Convert.ToDouble(reader.GetString(5).Replace('.', ','));
point.Longitude = Convert.ToDouble(reader.GetString(6).Replace('.', ','));
point.Description = reader.GetString(7);
points.Add(point);

}
i++;
}
i++;
}
} while (reader.NextResult());
} while (reader.NextResult());
}
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("Failed to load points from the XLSX file: {0}", e);
}

return points;

Expand Down Expand Up @@ -188,8 +190,9 @@ public static void DeleteFile(string filePath)
{
File.Delete(filePath);
}
catch (Exception ex)
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("Failed to delete file: {0}", e);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion api/SzopAPI/SzopAPI/Data/version.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
27.03.2022 16:24:38
03.04.2022 20:29:09
4 changes: 3 additions & 1 deletion api/SzopAPI/SzopAPI/Program.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//using SzopAPI.Attributes;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
Expand All @@ -11,7 +13,7 @@

System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);


//app.UseMiddleware<ApiKeyAttribute>();
app.UseSwagger();
app.UseSwaggerUI();

Expand Down
3 changes: 2 additions & 1 deletion api/SzopAPI/SzopAPI/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"ApiKey" : "szop"
}

0 comments on commit 3bd423c

Please sign in to comment.