refractoring
This commit is contained in:
+80
-81
@@ -1,102 +1,101 @@
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
|
||||
namespace Server
|
||||
namespace Server;
|
||||
|
||||
class Program
|
||||
{
|
||||
class Program
|
||||
static void HandleMissingPath(HttpListenerResponse response)
|
||||
{
|
||||
static void HandleMissingPath(HttpListenerResponse response)
|
||||
{
|
||||
response.StatusCode = 404;
|
||||
string errorMessage = "Not Found";
|
||||
byte[] buffer = Encoding.UTF8.GetBytes(errorMessage);
|
||||
response.ContentType = "text/plain";
|
||||
response.ContentLength64 = buffer.Length;
|
||||
response.OutputStream.Write(buffer, 0, buffer.Length);
|
||||
response.OutputStream.Write(buffer, 0, buffer.Length);
|
||||
}
|
||||
response.StatusCode = 404;
|
||||
string errorMessage = "Not Found";
|
||||
byte[] buffer = Encoding.UTF8.GetBytes(errorMessage);
|
||||
response.ContentType = "text/plain";
|
||||
response.ContentLength64 = buffer.Length;
|
||||
response.OutputStream.Write(buffer, 0, buffer.Length);
|
||||
response.OutputStream.Write(buffer, 0, buffer.Length);
|
||||
}
|
||||
|
||||
static void Main()
|
||||
{
|
||||
// create server
|
||||
HttpListener listener = new HttpListener();
|
||||
// routes need to be added first
|
||||
listener.Prefixes.Add("http://localhost:5000/api/getall/");
|
||||
listener.Prefixes.Add("http://localhost:5000/api/gettopten/");
|
||||
listener.Prefixes.Add("http://localhost:5000/api/getuser/");
|
||||
listener.Prefixes.Add("http://localhost:5000/api/reset/");
|
||||
listener.Prefixes.Add("http://localhost:5000/api/createp/");
|
||||
listener.Prefixes.Add("http://localhost:5000/api/register/");
|
||||
listener.Prefixes.Add("http://localhost:5000/api/login/");
|
||||
listener.Prefixes.Add("http://localhost:5000/api/createlog/");
|
||||
static void Main()
|
||||
{
|
||||
// create server
|
||||
HttpListener listener = new();
|
||||
// routes need to be added first
|
||||
listener.Prefixes.Add("http://localhost:5000/api/getall/");
|
||||
listener.Prefixes.Add("http://localhost:5000/api/gettopten/");
|
||||
listener.Prefixes.Add("http://localhost:5000/api/getuser/");
|
||||
listener.Prefixes.Add("http://localhost:5000/api/reset/");
|
||||
listener.Prefixes.Add("http://localhost:5000/api/createp/");
|
||||
listener.Prefixes.Add("http://localhost:5000/api/register/");
|
||||
listener.Prefixes.Add("http://localhost:5000/api/login/");
|
||||
listener.Prefixes.Add("http://localhost:5000/api/createlog/");
|
||||
|
||||
// listen
|
||||
listener.Start();
|
||||
Console.WriteLine("Server is listening on http://localhost:5000/");
|
||||
while (true)
|
||||
// listen
|
||||
listener.Start();
|
||||
Console.WriteLine("Server is listening on http://localhost:5000/");
|
||||
while (true)
|
||||
{
|
||||
HttpListenerContext context = listener.GetContext();
|
||||
HttpListenerRequest request = context.Request;
|
||||
HttpListenerResponse response = context.Response;
|
||||
// url after localhost:5000/
|
||||
string uri;
|
||||
if (request != null && request.Url != null)
|
||||
uri = request.Url.AbsolutePath;
|
||||
else
|
||||
return;
|
||||
switch (request.HttpMethod)
|
||||
{
|
||||
HttpListenerContext context = listener.GetContext();
|
||||
HttpListenerRequest request = context.Request;
|
||||
HttpListenerResponse response = context.Response;
|
||||
// url after localhost:5000/
|
||||
string uri;
|
||||
if (request != null && request.Url != null)
|
||||
uri = request.Url.AbsolutePath;
|
||||
else
|
||||
return;
|
||||
switch (request.HttpMethod)
|
||||
{
|
||||
case "GET":
|
||||
case "GET":
|
||||
switch (uri)
|
||||
{
|
||||
case "/api/reset":
|
||||
Reset.HandleRequest(response);
|
||||
break;
|
||||
case "/api/getall":
|
||||
/* Thread clientThread = new Thread(() => Getall.HandleRequest(request, response)); */
|
||||
/* clientThread.Start(); */
|
||||
Getall.HandleRequest(request, response);
|
||||
break;
|
||||
case "/api/gettopten":
|
||||
Gettopten.HandleRequest(request, response);
|
||||
break;
|
||||
case "/api/getuser":
|
||||
Getuser.HandleRequest(request, response);
|
||||
break;
|
||||
case "/api/createp":
|
||||
CreateProcedure.HandleRequest(response);
|
||||
break;
|
||||
default:
|
||||
HandleMissingPath(response);
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case "POST":
|
||||
if (request.HasEntityBody)
|
||||
switch (uri)
|
||||
{
|
||||
case "/api/reset":
|
||||
Reset.HandleRequest(request, response);
|
||||
case "/api/register":
|
||||
Register.HandleRequest(request, response);
|
||||
break;
|
||||
case "/api/getall":
|
||||
/* Thread clientThread = new Thread(() => Getall.HandleRequest(request, response)); */
|
||||
/* clientThread.Start(); */
|
||||
Getall.HandleRequest(request, response);
|
||||
case "/api/login":
|
||||
Login.HandleRequest(request, response);
|
||||
break;
|
||||
case "/api/gettopten":
|
||||
Gettopten.HandleRequest(request, response);
|
||||
break;
|
||||
case "/api/getuser":
|
||||
Getuser.HandleRequest(request, response);
|
||||
break;
|
||||
case "/api/createp":
|
||||
CreateProcedure.HandleRequest(request, response);
|
||||
case "/api/createlog":
|
||||
CreateLog.HandleRequest(request, response, context);
|
||||
break;
|
||||
default:
|
||||
HandleMissingPath(response);
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case "POST":
|
||||
if (request.HasEntityBody)
|
||||
switch (uri)
|
||||
{
|
||||
case "/api/register":
|
||||
Register.HandleRequest(request, response);
|
||||
break;
|
||||
case "/api/login":
|
||||
Login.HandleRequest(request, response);
|
||||
break;
|
||||
case "/api/createlog":
|
||||
CreateLog.HandleRequest(request, response, context);
|
||||
break;
|
||||
default:
|
||||
HandleMissingPath(response);
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
HandleMissingPath(response);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
else
|
||||
{
|
||||
HandleMissingPath(response);
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
HandleMissingPath(response);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -13,7 +13,7 @@ using System.Reflection;
|
||||
[assembly: System.Reflection.AssemblyCompanyAttribute("TimelogBackend")]
|
||||
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
|
||||
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
|
||||
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+cb7b3ad94c91aad561fa90871a3e078e741f566c")]
|
||||
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+926436860cd34dec9ccf3feac66e4c63bae7ba8f")]
|
||||
[assembly: System.Reflection.AssemblyProductAttribute("TimelogBackend")]
|
||||
[assembly: System.Reflection.AssemblyTitleAttribute("TimelogBackend")]
|
||||
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
|
||||
|
||||
@@ -1 +1 @@
|
||||
21ebdfea2f4ecbc0e48a6b53f27fa496a20e08b7ed0ace43e5500d5093c8a245
|
||||
4d078ebec60178a78b052888e79c6e658ccc73953d1f8ba236008a06ecc632b9
|
||||
|
||||
@@ -117,3 +117,46 @@
|
||||
/home/arch/projects/wip/timelog-interview-login/backendCs/bin/Debug/net8.0/Microsoft.IdentityModel.Logging.dll
|
||||
/home/arch/projects/wip/timelog-interview-login/backendCs/bin/Debug/net8.0/Microsoft.IdentityModel.Tokens.dll
|
||||
/home/arch/projects/wip/timelog-interview-login/backendCs/bin/Debug/net8.0/System.IdentityModel.Tokens.Jwt.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/obj/Debug/net8.0/TimelogBackend.csproj.AssemblyReference.cache
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/obj/Debug/net8.0/TimelogBackend.GeneratedMSBuildEditorConfig.editorconfig
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/obj/Debug/net8.0/TimelogBackend.AssemblyInfoInputs.cache
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/obj/Debug/net8.0/TimelogBackend.AssemblyInfo.cs
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/obj/Debug/net8.0/TimelogBackend.csproj.CoreCompileInputs.cache
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/obj/Debug/net8.0/TimelogBackend.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/obj/Debug/net8.0/refint/TimelogBackend.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/obj/Debug/net8.0/TimelogBackend.pdb
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/TimelogBackend
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/TimelogBackend.deps.json
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/TimelogBackend.runtimeconfig.json
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/TimelogBackend.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/TimelogBackend.pdb
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/BouncyCastle.Cryptography.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/Google.Protobuf.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/K4os.Compression.LZ4.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/K4os.Compression.LZ4.Streams.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/K4os.Hash.xxHash.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/Microsoft.IdentityModel.Abstractions.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/Microsoft.IdentityModel.JsonWebTokens.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/Microsoft.IdentityModel.Logging.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/Microsoft.IdentityModel.Tokens.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/MySql.Data.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/Newtonsoft.Json.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/System.Configuration.ConfigurationManager.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/System.Diagnostics.EventLog.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/System.IdentityModel.Tokens.Jwt.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/System.IO.Pipelines.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/System.Security.Cryptography.ProtectedData.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/System.Security.Permissions.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/System.Windows.Extensions.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/ZstdSharp.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/runtimes/win-x64/native/comerr64.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/runtimes/win-x64/native/gssapi64.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/runtimes/win-x64/native/k5sprt64.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/runtimes/win-x64/native/krb5_64.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/runtimes/win-x64/native/krbcc64.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/runtimes/win/lib/net8.0/System.Diagnostics.EventLog.Messages.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/runtimes/win/lib/net8.0/System.Diagnostics.EventLog.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/bin/Debug/net8.0/runtimes/win/lib/net8.0/System.Windows.Extensions.dll
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/obj/Debug/net8.0/TimelogBackend.csproj.CopyComplete
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/obj/Debug/net8.0/TimelogBackend.genruntimeconfig.cache
|
||||
/home/arch/projects/unfinished/timelog-interview-login/backendCs/obj/Debug/net8.0/ref/TimelogBackend.dll
|
||||
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
cabec8eef32bfb7a5e67f2b4ed57839edd7c13e8479c77f87a2d35ec66b02abb
|
||||
6ce12d87876379d820297a17b33b1f57ff3987d74bed581fb7ebcc8c73660966
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,17 +1,17 @@
|
||||
{
|
||||
"format": 1,
|
||||
"restore": {
|
||||
"/home/arch/projects/wip/timelog-interview-login/backendCs/TimelogBackend.csproj": {}
|
||||
"/home/arch/projects/unfinished/timelog-interview-login/backendCs/TimelogBackend.csproj": {}
|
||||
},
|
||||
"projects": {
|
||||
"/home/arch/projects/wip/timelog-interview-login/backendCs/TimelogBackend.csproj": {
|
||||
"/home/arch/projects/unfinished/timelog-interview-login/backendCs/TimelogBackend.csproj": {
|
||||
"version": "1.0.0",
|
||||
"restore": {
|
||||
"projectUniqueName": "/home/arch/projects/wip/timelog-interview-login/backendCs/TimelogBackend.csproj",
|
||||
"projectUniqueName": "/home/arch/projects/unfinished/timelog-interview-login/backendCs/TimelogBackend.csproj",
|
||||
"projectName": "TimelogBackend",
|
||||
"projectPath": "/home/arch/projects/wip/timelog-interview-login/backendCs/TimelogBackend.csproj",
|
||||
"projectPath": "/home/arch/projects/unfinished/timelog-interview-login/backendCs/TimelogBackend.csproj",
|
||||
"packagesPath": "/home/arch/.nuget/packages/",
|
||||
"outputPath": "/home/arch/projects/wip/timelog-interview-login/backendCs/obj/",
|
||||
"outputPath": "/home/arch/projects/unfinished/timelog-interview-login/backendCs/obj/",
|
||||
"projectStyle": "PackageReference",
|
||||
"configFilePaths": [
|
||||
"/home/arch/.nuget/NuGet/NuGet.Config"
|
||||
|
||||
@@ -1857,11 +1857,11 @@
|
||||
"project": {
|
||||
"version": "1.0.0",
|
||||
"restore": {
|
||||
"projectUniqueName": "/home/arch/projects/wip/timelog-interview-login/backendCs/TimelogBackend.csproj",
|
||||
"projectUniqueName": "/home/arch/projects/unfinished/timelog-interview-login/backendCs/TimelogBackend.csproj",
|
||||
"projectName": "TimelogBackend",
|
||||
"projectPath": "/home/arch/projects/wip/timelog-interview-login/backendCs/TimelogBackend.csproj",
|
||||
"projectPath": "/home/arch/projects/unfinished/timelog-interview-login/backendCs/TimelogBackend.csproj",
|
||||
"packagesPath": "/home/arch/.nuget/packages/",
|
||||
"outputPath": "/home/arch/projects/wip/timelog-interview-login/backendCs/obj/",
|
||||
"outputPath": "/home/arch/projects/unfinished/timelog-interview-login/backendCs/obj/",
|
||||
"projectStyle": "PackageReference",
|
||||
"configFilePaths": [
|
||||
"/home/arch/.nuget/NuGet/NuGet.Config"
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"version": 2,
|
||||
"dgSpecHash": "lhoNhBuhv5pZb43QtTahPtHclYQU5heHEQPyTVS7gTLS0zI+oKRmmyzvVbe56/iHd4Yw20shJvPbIdrCOp+Qug==",
|
||||
"dgSpecHash": "Kw1QiagALZErTv+cX8IjNVaHlG1vVsZ8jbQdO6NwgQJYGShK1fNvP3A258Ci81RECrzVlyi53zgZ5YHVjUaNOw==",
|
||||
"success": true,
|
||||
"projectFilePath": "/home/arch/projects/wip/timelog-interview-login/backendCs/TimelogBackend.csproj",
|
||||
"projectFilePath": "/home/arch/projects/unfinished/timelog-interview-login/backendCs/TimelogBackend.csproj",
|
||||
"expectedPackageFiles": [
|
||||
"/home/arch/.nuget/packages/bouncycastle.cryptography/2.3.1/bouncycastle.cryptography.2.3.1.nupkg.sha512",
|
||||
"/home/arch/.nuget/packages/google.protobuf/3.26.1/google.protobuf.3.26.1.nupkg.sha512",
|
||||
|
||||
+109
-110
@@ -6,125 +6,124 @@ using Microsoft.IdentityModel.Tokens;
|
||||
using MySql.Data.MySqlClient;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Server
|
||||
namespace Server;
|
||||
|
||||
public class CreateLog : Route
|
||||
{
|
||||
public class CreateLog : Route
|
||||
private static string secretKey =
|
||||
"stronk-key-much-sercret-much-more-stronk-stronk-key-much-sercret-much-more-stronk";
|
||||
|
||||
private static bool ValidateToken(string token)
|
||||
{
|
||||
private static string secretKey =
|
||||
"stronk-key-much-sercret-much-more-stronk-stronk-key-much-sercret-much-more-stronk";
|
||||
|
||||
private static bool ValidateToken(string token)
|
||||
try
|
||||
{
|
||||
try
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
var validationParameters = new TokenValidationParameters
|
||||
{
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
var validationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidIssuer = "TimeLogServer",
|
||||
ValidAudience = "TimeLogWebsite",
|
||||
IssuerSigningKey = key,
|
||||
};
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidIssuer = "TimeLogServer",
|
||||
ValidAudience = "TimeLogWebsite",
|
||||
IssuerSigningKey = key,
|
||||
};
|
||||
|
||||
var principal = tokenHandler.ValidateToken(
|
||||
token,
|
||||
validationParameters,
|
||||
out SecurityToken validatedToken
|
||||
);
|
||||
return validatedToken != null;
|
||||
}
|
||||
catch
|
||||
var principal = tokenHandler.ValidateToken(
|
||||
token,
|
||||
validationParameters,
|
||||
out SecurityToken validatedToken
|
||||
);
|
||||
return validatedToken != null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void HandleRequest(
|
||||
HttpListenerRequest request,
|
||||
HttpListenerResponse response,
|
||||
HttpListenerContext context
|
||||
)
|
||||
{
|
||||
try
|
||||
{
|
||||
// check header
|
||||
var headers = request.Headers;
|
||||
string? token = headers["token"];
|
||||
if (!string.IsNullOrEmpty(token) && !ValidateToken(token))
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Invalid token");
|
||||
}
|
||||
// prepare SQL query
|
||||
MySqlCommand cmd = new MySqlCommand();
|
||||
// extact data from body
|
||||
string body;
|
||||
using (
|
||||
StreamReader bodyReader = new StreamReader(
|
||||
request.InputStream,
|
||||
request.ContentEncoding
|
||||
)
|
||||
)
|
||||
{
|
||||
body = bodyReader.ReadToEnd();
|
||||
}
|
||||
JObject jsonObject = JObject.Parse(body);
|
||||
string project = jsonObject["project"]?.ToString() ?? "";
|
||||
string time = jsonObject["time"]?.ToString() ?? "";
|
||||
string date = jsonObject["date"]?.ToString() ?? "";
|
||||
|
||||
// TODO check if the hours on given date don't combine to more
|
||||
// than 8
|
||||
|
||||
// validate time
|
||||
if (!int.TryParse(time, out int myInt) || myInt < 0 || myInt > 8)
|
||||
throw new Exception("Incorect ammount of hours");
|
||||
// validate date
|
||||
Regex regex = new Regex(@"^\d{4}-\d{2}-\d{2}$");
|
||||
if (string.IsNullOrEmpty(date) || !regex.IsMatch(date))
|
||||
{
|
||||
throw new Exception("Incorrect date format");
|
||||
}
|
||||
// validate user
|
||||
// extract user from jwt
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var jwtToken = handler.ReadJwtToken(token);
|
||||
string? usernameClaim =
|
||||
jwtToken.Claims.FirstOrDefault(c => c.Type == "user")?.Value ?? "";
|
||||
if (string.IsNullOrEmpty(usernameClaim))
|
||||
{
|
||||
throw new Exception("wrong user id");
|
||||
}
|
||||
|
||||
// validate project
|
||||
// TODO better project validation
|
||||
if (string.IsNullOrEmpty(project))
|
||||
{
|
||||
throw new Exception("wrong project");
|
||||
}
|
||||
using (MySqlConnection conn = new MySqlConnection(connectionString))
|
||||
{
|
||||
conn.Open();
|
||||
cmd.Connection = conn;
|
||||
cmd.CommandText =
|
||||
@"INSERT INTO Timelog(user,project,date,time)
|
||||
VALUES(@user,@project,@date,@time);";
|
||||
cmd.Parameters.AddWithValue("@user", usernameClaim);
|
||||
cmd.Parameters.AddWithValue("@project", project);
|
||||
cmd.Parameters.AddWithValue("@time", time);
|
||||
cmd.Parameters.AddWithValue("@date", date);
|
||||
// execute query and read results
|
||||
cmd.ExecuteNonQuery();
|
||||
|
||||
SendSuccess(response);
|
||||
}
|
||||
}
|
||||
|
||||
public static void HandleRequest(
|
||||
HttpListenerRequest request,
|
||||
HttpListenerResponse response,
|
||||
HttpListenerContext context
|
||||
)
|
||||
catch (Exception ex)
|
||||
{
|
||||
try
|
||||
{
|
||||
// check header
|
||||
var headers = request.Headers;
|
||||
string? token = headers["token"];
|
||||
if (!string.IsNullOrEmpty(token) && !ValidateToken(token))
|
||||
{
|
||||
throw new Exception("Invalid token");
|
||||
}
|
||||
// prepare SQL query
|
||||
MySqlCommand cmd = new MySqlCommand();
|
||||
// extact data from body
|
||||
string body;
|
||||
using (
|
||||
StreamReader bodyReader = new StreamReader(
|
||||
request.InputStream,
|
||||
request.ContentEncoding
|
||||
)
|
||||
)
|
||||
{
|
||||
body = bodyReader.ReadToEnd();
|
||||
}
|
||||
JObject jsonObject = JObject.Parse(body);
|
||||
string project = jsonObject["project"]?.ToString() ?? "";
|
||||
string time = jsonObject["time"]?.ToString() ?? "";
|
||||
string date = jsonObject["date"]?.ToString() ?? "";
|
||||
|
||||
// TODO check if the hours on given date don't combine to more
|
||||
// than 8
|
||||
|
||||
// validate time
|
||||
if (!int.TryParse(time, out int myInt) || myInt < 0 || myInt > 8)
|
||||
throw new Exception("Incorect ammount of hours");
|
||||
// validate date
|
||||
Regex regex = new Regex(@"^\d{4}-\d{2}-\d{2}$");
|
||||
if (string.IsNullOrEmpty(date) || !regex.IsMatch(date))
|
||||
{
|
||||
throw new Exception("Incorrect date format");
|
||||
}
|
||||
// validate user
|
||||
// extract user from jwt
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var jwtToken = handler.ReadJwtToken(token);
|
||||
string? usernameClaim =
|
||||
jwtToken.Claims.FirstOrDefault(c => c.Type == "user")?.Value ?? "";
|
||||
if (string.IsNullOrEmpty(usernameClaim))
|
||||
{
|
||||
throw new Exception("wrong user id");
|
||||
}
|
||||
|
||||
// validate project
|
||||
// TODO better project validation
|
||||
if (string.IsNullOrEmpty(project))
|
||||
{
|
||||
throw new Exception("wrong project");
|
||||
}
|
||||
using (MySqlConnection conn = new MySqlConnection(connectionString))
|
||||
{
|
||||
conn.Open();
|
||||
cmd.Connection = conn;
|
||||
cmd.CommandText =
|
||||
@"INSERT INTO Timelog(user,project,date,time)
|
||||
VALUES(@user,@project,@date,@time);";
|
||||
cmd.Parameters.AddWithValue("@user", usernameClaim);
|
||||
cmd.Parameters.AddWithValue("@project", project);
|
||||
cmd.Parameters.AddWithValue("@time", time);
|
||||
cmd.Parameters.AddWithValue("@date", date);
|
||||
// execute query and read results
|
||||
cmd.ExecuteNonQuery();
|
||||
|
||||
SendSuccess(response);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SendError(response, ex);
|
||||
}
|
||||
SendError(response, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
using System.Net;
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
namespace Server
|
||||
{
|
||||
public class CreateProcedure : Route
|
||||
{
|
||||
public static void HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
|
||||
{
|
||||
try
|
||||
{
|
||||
MySqlCommand cmd = new MySqlCommand();
|
||||
namespace Server;
|
||||
|
||||
using (MySqlConnection conn = new MySqlConnection(connectionString))
|
||||
{
|
||||
conn.Open();
|
||||
cmd.Connection = conn;
|
||||
cmd.CommandText =
|
||||
@"
|
||||
public class CreateProcedure : Route
|
||||
{
|
||||
public static void HandleRequest(HttpListenerResponse response)
|
||||
{
|
||||
try
|
||||
{
|
||||
MySqlCommand cmd = new();
|
||||
|
||||
using (MySqlConnection conn = new(connectionString))
|
||||
{
|
||||
conn.Open();
|
||||
cmd.Connection = conn;
|
||||
cmd.CommandText =
|
||||
@"
|
||||
CREATE PROCEDURE fill_timelog ()
|
||||
BEGIN
|
||||
DECLARE j INT DEFAULT 1;
|
||||
@@ -53,9 +53,9 @@ BEGIN
|
||||
SET users = users + 1;
|
||||
END WHILE;
|
||||
END;";
|
||||
cmd.ExecuteNonQuery();
|
||||
cmd.CommandText =
|
||||
@"CREATE PROCEDURE InitDB()
|
||||
cmd.ExecuteNonQuery();
|
||||
cmd.CommandText =
|
||||
@"CREATE PROCEDURE InitDB()
|
||||
BEGIN
|
||||
DECLARE i INT DEFAULT 1;
|
||||
TRUNCATE TABLE Timelog;
|
||||
@@ -116,15 +116,14 @@ BEGIN
|
||||
DROP TABLE temp_fname;
|
||||
DROP TABLE temp_lname;
|
||||
END;";
|
||||
cmd.ExecuteNonQuery();
|
||||
// prepare response
|
||||
SendSuccess(response);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SendError(response, ex);
|
||||
cmd.ExecuteNonQuery();
|
||||
// prepare response
|
||||
SendSuccess(response);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SendError(response, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+98
-99
@@ -3,113 +3,112 @@ using System.Text.RegularExpressions;
|
||||
using MySql.Data.MySqlClient;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Server
|
||||
{
|
||||
// there should be a better way to deal with data comming from sql
|
||||
public class Log
|
||||
{
|
||||
public object? f_name { get; set; }
|
||||
public object? l_name { get; set; }
|
||||
public object? mail { get; set; }
|
||||
public object? name { get; set; }
|
||||
public object? time { get; set; }
|
||||
public object? date { get; set; }
|
||||
public object? user { get; set; }
|
||||
}
|
||||
namespace Server;
|
||||
|
||||
public class Getall : Route
|
||||
// there should be a better way to deal with data comming from sql
|
||||
public class Log
|
||||
{
|
||||
public object? f_name { get; set; }
|
||||
public object? l_name { get; set; }
|
||||
public object? mail { get; set; }
|
||||
public object? name { get; set; }
|
||||
public object? time { get; set; }
|
||||
public object? date { get; set; }
|
||||
public object? user { get; set; }
|
||||
}
|
||||
|
||||
public class Getall : Route
|
||||
{
|
||||
public static void HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
|
||||
{
|
||||
public static void HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
// prepare SQL query
|
||||
MySqlCommand cmd = new MySqlCommand();
|
||||
// get url params
|
||||
var queryString = request.QueryString;
|
||||
string? from = queryString["from"];
|
||||
string? to = queryString["to"];
|
||||
string? sortby = queryString["sortby"];
|
||||
string? offset = queryString["offset"];
|
||||
string? order = queryString["order"];
|
||||
order = order == "true" ? "ASC" : "DESC";
|
||||
string mainQuery =
|
||||
@"SELECT u.f_name,u.l_name,u.mail,p.name,t.time,t.date,t.user
|
||||
// prepare SQL query
|
||||
MySqlCommand cmd = new();
|
||||
// get url params
|
||||
var queryString = request.QueryString;
|
||||
string? from = queryString["from"];
|
||||
string? to = queryString["to"];
|
||||
string? sortby = queryString["sortby"];
|
||||
string? offset = queryString["offset"];
|
||||
string? order = queryString["order"];
|
||||
order = order == "true" ? "ASC" : "DESC";
|
||||
string mainQuery =
|
||||
@"SELECT u.f_name,u.l_name,u.mail,p.name,t.time,t.date,t.user
|
||||
FROM Timelog t
|
||||
INNER JOIN Project p ON p.id=t.project
|
||||
INNER JOIN User u ON u.id=t.user ";
|
||||
// this shenanigan is needed to remove the "" around group by
|
||||
string offsetQuery = " LIMIT 10 OFFSET " + offset + ";";
|
||||
// depending on the incoming parameters construct a Query
|
||||
if (!string.IsNullOrEmpty(to) && !string.IsNullOrEmpty(from))
|
||||
{
|
||||
Regex regex = new Regex(@"^\d{4}-\d{2}-\d{2}$");
|
||||
if (!regex.IsMatch(to) || !regex.IsMatch(from))
|
||||
{
|
||||
throw new Exception("Incorrect date format");
|
||||
}
|
||||
string whereQuery = " WHERE t.date BETWEEN @from AND @to ";
|
||||
mainQuery = mainQuery + whereQuery;
|
||||
}
|
||||
if (!string.IsNullOrEmpty(sortby))
|
||||
{
|
||||
List<string> validSorting = new List<string>
|
||||
{
|
||||
"f_name",
|
||||
"l_name",
|
||||
"mail",
|
||||
"time",
|
||||
"date",
|
||||
"user",
|
||||
"project",
|
||||
};
|
||||
if (!validSorting.Contains(sortby))
|
||||
{
|
||||
throw new Exception("Incorrect sorting value");
|
||||
}
|
||||
string orderQuery = " ORDER BY " + sortby + " " + order;
|
||||
mainQuery = mainQuery + orderQuery;
|
||||
}
|
||||
if (!int.TryParse(offset, out int myInt) || myInt < 0)
|
||||
throw new Exception("Incorect offset");
|
||||
// add the final line to the query
|
||||
cmd.CommandText = mainQuery + offsetQuery;
|
||||
// those don't produce error if they don't find their variables
|
||||
cmd.Parameters.AddWithValue("@from", from);
|
||||
cmd.Parameters.AddWithValue("@to", to);
|
||||
|
||||
using (MySqlConnection conn = new MySqlConnection(connectionString))
|
||||
{
|
||||
conn.Open();
|
||||
cmd.Connection = conn;
|
||||
// execute query and read results
|
||||
MySqlDataReader reader = cmd.ExecuteReader();
|
||||
|
||||
List<Log> entries = new List<Log>();
|
||||
while (reader.Read())
|
||||
{
|
||||
entries.Add(
|
||||
new Log
|
||||
{
|
||||
f_name = reader["f_name"],
|
||||
l_name = reader["l_name"],
|
||||
user = reader["user"],
|
||||
date = reader["date"],
|
||||
name = reader["name"],
|
||||
time = reader["time"],
|
||||
mail = reader["mail"],
|
||||
}
|
||||
);
|
||||
}
|
||||
// serialize JSON
|
||||
string jsonResponse = JsonConvert.SerializeObject(entries);
|
||||
SendSuccess(response, jsonResponse);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
// this shenanigan is needed to remove the "" around group by
|
||||
string offsetQuery = " LIMIT 10 OFFSET " + offset + ";";
|
||||
// depending on the incoming parameters construct a Query
|
||||
if (!string.IsNullOrEmpty(to) && !string.IsNullOrEmpty(from))
|
||||
{
|
||||
SendError(response, ex);
|
||||
Regex regex = new Regex(@"^\d{4}-\d{2}-\d{2}$");
|
||||
if (!regex.IsMatch(to) || !regex.IsMatch(from))
|
||||
{
|
||||
throw new Exception("Incorrect date format");
|
||||
}
|
||||
string whereQuery = " WHERE t.date BETWEEN @from AND @to ";
|
||||
mainQuery = mainQuery + whereQuery;
|
||||
}
|
||||
if (!string.IsNullOrEmpty(sortby))
|
||||
{
|
||||
List<string> validSorting =
|
||||
[
|
||||
"f_name",
|
||||
"l_name",
|
||||
"mail",
|
||||
"time",
|
||||
"date",
|
||||
"user",
|
||||
"project",
|
||||
];
|
||||
if (!validSorting.Contains(sortby))
|
||||
{
|
||||
throw new Exception("Incorrect sorting value");
|
||||
}
|
||||
string orderQuery = " ORDER BY " + sortby + " " + order;
|
||||
mainQuery = mainQuery + orderQuery;
|
||||
}
|
||||
if (!int.TryParse(offset, out int myInt) || myInt < 0)
|
||||
throw new Exception("Incorect offset");
|
||||
// add the final line to the query
|
||||
cmd.CommandText = mainQuery + offsetQuery;
|
||||
// those don't produce error if they don't find their variables
|
||||
cmd.Parameters.AddWithValue("@from", from);
|
||||
cmd.Parameters.AddWithValue("@to", to);
|
||||
|
||||
using (MySqlConnection conn = new(connectionString))
|
||||
{
|
||||
conn.Open();
|
||||
cmd.Connection = conn;
|
||||
// execute query and read results
|
||||
MySqlDataReader reader = cmd.ExecuteReader();
|
||||
|
||||
List<Log> entries = [];
|
||||
while (reader.Read())
|
||||
{
|
||||
entries.Add(
|
||||
new Log
|
||||
{
|
||||
f_name = reader["f_name"],
|
||||
l_name = reader["l_name"],
|
||||
user = reader["user"],
|
||||
date = reader["date"],
|
||||
name = reader["name"],
|
||||
time = reader["time"],
|
||||
mail = reader["mail"],
|
||||
}
|
||||
);
|
||||
}
|
||||
// serialize JSON
|
||||
string jsonResponse = JsonConvert.SerializeObject(entries);
|
||||
SendSuccess(response, jsonResponse);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SendError(response, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,101 +3,100 @@ using System.Text.RegularExpressions;
|
||||
using MySql.Data.MySqlClient;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Server
|
||||
namespace Server;
|
||||
|
||||
public class TopTen
|
||||
{
|
||||
public class TopTen
|
||||
{
|
||||
public object? user { get; set; }
|
||||
public object? date { get; set; }
|
||||
public object? project { get; set; }
|
||||
public object? f_name { get; set; }
|
||||
public object? l_name { get; set; }
|
||||
public object? name { get; set; }
|
||||
public object? total_time { get; set; }
|
||||
}
|
||||
public object? user { get; set; }
|
||||
public object? date { get; set; }
|
||||
public object? project { get; set; }
|
||||
public object? f_name { get; set; }
|
||||
public object? l_name { get; set; }
|
||||
public object? name { get; set; }
|
||||
public object? total_time { get; set; }
|
||||
}
|
||||
|
||||
public class Gettopten : Route
|
||||
public class Gettopten : Route
|
||||
{
|
||||
public static void HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
|
||||
{
|
||||
public static void HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
|
||||
try
|
||||
{
|
||||
try
|
||||
// prepare SQL query
|
||||
MySqlCommand cmd = new();
|
||||
var queryString = request.QueryString;
|
||||
string? from = queryString["from"];
|
||||
string? to = queryString["to"];
|
||||
string? filterBy = queryString["filterBy"];
|
||||
|
||||
if (!string.IsNullOrEmpty(to) && !string.IsNullOrEmpty(from))
|
||||
{
|
||||
// prepare SQL query
|
||||
MySqlCommand cmd = new MySqlCommand();
|
||||
var queryString = request.QueryString;
|
||||
string? from = queryString["from"];
|
||||
string? to = queryString["to"];
|
||||
string? filterBy = queryString["filterBy"];
|
||||
Regex regex = new Regex(@"^\d{4}-\d{2}-\d{2}$");
|
||||
if (!regex.IsMatch(to) || !regex.IsMatch(from))
|
||||
{
|
||||
throw new Exception("Incorrect date format");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("Empty date format");
|
||||
}
|
||||
if (string.IsNullOrEmpty(filterBy))
|
||||
{
|
||||
throw new Exception("Empty filterby");
|
||||
}
|
||||
if (filterBy != "user" && filterBy != "project")
|
||||
{
|
||||
throw new Exception("Incorrect filterby");
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(to) && !string.IsNullOrEmpty(from))
|
||||
{
|
||||
Regex regex = new Regex(@"^\d{4}-\d{2}-\d{2}$");
|
||||
if (!regex.IsMatch(to) || !regex.IsMatch(from))
|
||||
{
|
||||
throw new Exception("Incorrect date format");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("Empty date format");
|
||||
}
|
||||
if (string.IsNullOrEmpty(filterBy))
|
||||
{
|
||||
throw new Exception("Empty filterby");
|
||||
}
|
||||
if (filterBy != "user" && filterBy != "project")
|
||||
{
|
||||
throw new Exception("Incorrect filterby");
|
||||
}
|
||||
|
||||
// this shenanigan is needed to remove the "" around
|
||||
// group by
|
||||
string req =
|
||||
@"SELECT t.user,t.date,t.project,u.f_name,u.l_name,p.name,SUM(t.time) as total_time
|
||||
// this shenanigan is needed to remove the "" around
|
||||
// group by
|
||||
string req =
|
||||
@"SELECT t.user,t.date,t.project,u.f_name,u.l_name,p.name,SUM(t.time) as total_time
|
||||
FROM Timelog t
|
||||
INNER JOIN Project p ON p.id=t.project
|
||||
INNER JOIN User u ON u.id=t.user
|
||||
WHERE t.date BETWEEN @from AND @to
|
||||
GROUP BY "
|
||||
+ filterBy
|
||||
+ @" ORDER BY total_time DESC
|
||||
+ filterBy
|
||||
+ @" ORDER BY total_time DESC
|
||||
LIMIT 10;";
|
||||
cmd.CommandText = req;
|
||||
cmd.Parameters.AddWithValue("@from", from);
|
||||
cmd.Parameters.AddWithValue("@to", to);
|
||||
cmd.CommandText = req;
|
||||
cmd.Parameters.AddWithValue("@from", from);
|
||||
cmd.Parameters.AddWithValue("@to", to);
|
||||
|
||||
using (MySqlConnection conn = new MySqlConnection(connectionString))
|
||||
{
|
||||
cmd.Connection = conn;
|
||||
conn.Open();
|
||||
// Execute the query and read the results
|
||||
MySqlDataReader reader = cmd.ExecuteReader();
|
||||
List<TopTen> entries = new List<TopTen>();
|
||||
while (reader.Read())
|
||||
{
|
||||
entries.Add(
|
||||
new TopTen
|
||||
{
|
||||
user = reader["user"],
|
||||
date = reader["date"],
|
||||
project = reader["project"],
|
||||
f_name = reader["f_name"],
|
||||
l_name = reader["l_name"],
|
||||
name = reader["name"],
|
||||
total_time = reader["total_time"],
|
||||
}
|
||||
);
|
||||
}
|
||||
// Serialize the data to JSON
|
||||
string jsonResponse = JsonConvert.SerializeObject(entries);
|
||||
// prepare response
|
||||
SendSuccess(response, jsonResponse);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
using (MySqlConnection conn = new(connectionString))
|
||||
{
|
||||
SendError(response, ex);
|
||||
cmd.Connection = conn;
|
||||
conn.Open();
|
||||
// Execute the query and read the results
|
||||
MySqlDataReader reader = cmd.ExecuteReader();
|
||||
List<TopTen> entries = [];
|
||||
while (reader.Read())
|
||||
{
|
||||
entries.Add(
|
||||
new TopTen
|
||||
{
|
||||
user = reader["user"],
|
||||
date = reader["date"],
|
||||
project = reader["project"],
|
||||
f_name = reader["f_name"],
|
||||
l_name = reader["l_name"],
|
||||
name = reader["name"],
|
||||
total_time = reader["total_time"],
|
||||
}
|
||||
);
|
||||
}
|
||||
// Serialize the data to JSON
|
||||
string jsonResponse = JsonConvert.SerializeObject(entries);
|
||||
// prepare response
|
||||
SendSuccess(response, jsonResponse);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SendError(response, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+37
-36
@@ -3,54 +3,55 @@ using System.Net;
|
||||
using MySql.Data.MySqlClient;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Server
|
||||
namespace Server;
|
||||
|
||||
public class Getuser : Route
|
||||
{
|
||||
public class Getuser : Route
|
||||
public static void HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
|
||||
{
|
||||
public static void HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
|
||||
try
|
||||
{
|
||||
try
|
||||
var queryString = request.QueryString;
|
||||
string? userid = queryString["userid"];
|
||||
if (string.IsNullOrEmpty(userid))
|
||||
{
|
||||
var queryString = request.QueryString;
|
||||
string? userid = queryString["userid"];
|
||||
if (string.IsNullOrEmpty(userid))
|
||||
{
|
||||
throw new Exception("Missing userid");
|
||||
}
|
||||
// prepare SQL query
|
||||
MySqlCommand cmd = new MySqlCommand();
|
||||
cmd.CommandText =
|
||||
throw new Exception("Missing userid");
|
||||
}
|
||||
// prepare SQL query
|
||||
MySqlCommand cmd = new()
|
||||
{
|
||||
CommandText =
|
||||
@"SELECT p.name, SUM(t.time)
|
||||
FROM Timelog t
|
||||
INNER JOIN Project p ON p.id=t.project
|
||||
INNER JOIN User u ON u.id=t.user
|
||||
WHERE User = @userid
|
||||
GROUP BY name;";
|
||||
cmd.Parameters.AddWithValue("@userid", userid);
|
||||
GROUP BY name;",
|
||||
};
|
||||
cmd.Parameters.AddWithValue("@userid", userid);
|
||||
|
||||
using (MySqlConnection conn = new MySqlConnection(connectionString))
|
||||
{
|
||||
conn.Open();
|
||||
cmd.Connection = conn;
|
||||
// execute query and read results
|
||||
MySqlDataReader reader = cmd.ExecuteReader();
|
||||
dynamic expando = new ExpandoObject();
|
||||
while (reader.Read())
|
||||
{
|
||||
((IDictionary<string?, object>)expando)[reader["name"].ToString()] = reader[
|
||||
"SUM(t.time)"
|
||||
];
|
||||
}
|
||||
// serialize JSON
|
||||
string jsonResponse = JsonConvert.SerializeObject(expando);
|
||||
// prepare response
|
||||
SendSuccess(response, jsonResponse);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
using (MySqlConnection conn = new(connectionString))
|
||||
{
|
||||
SendError(response, ex);
|
||||
conn.Open();
|
||||
cmd.Connection = conn;
|
||||
// execute query and read results
|
||||
MySqlDataReader reader = cmd.ExecuteReader();
|
||||
dynamic expando = new ExpandoObject();
|
||||
while (reader.Read())
|
||||
{
|
||||
((IDictionary<string?, object>)expando)[reader["name"].ToString()] = reader[
|
||||
"SUM(t.time)"
|
||||
];
|
||||
}
|
||||
// serialize JSON
|
||||
string jsonResponse = JsonConvert.SerializeObject(expando);
|
||||
// prepare response
|
||||
SendSuccess(response, jsonResponse);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SendError(response, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+101
-105
@@ -8,126 +8,122 @@ using MySql.Data.MySqlClient;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Server
|
||||
namespace Server;
|
||||
|
||||
public class Login : Route
|
||||
{
|
||||
public class Login : Route
|
||||
private static string secretKey =
|
||||
"stronk-key-much-sercret-much-more-stronk-stronk-key-much-sercret-much-more-stronk";
|
||||
|
||||
public static string GenerateToken(string user)
|
||||
{
|
||||
private static string secretKey =
|
||||
"stronk-key-much-sercret-much-more-stronk-stronk-key-much-sercret-much-more-stronk";
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
|
||||
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||
|
||||
public static string GenerateToken(string user)
|
||||
{
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
|
||||
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: "TimeLogServer",
|
||||
audience: "TimeLogWebsite",
|
||||
claims: new[] { new Claim("user", user) },
|
||||
expires: DateTime.Now.AddHours(2),
|
||||
signingCredentials: creds
|
||||
);
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: "TimeLogServer",
|
||||
audience: "TimeLogWebsite",
|
||||
claims: new[] { new Claim("user", user) },
|
||||
expires: DateTime.Now.AddHours(2),
|
||||
signingCredentials: creds
|
||||
);
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
public static bool VerifyPassword(string enteredPassword, string storedHash)
|
||||
{
|
||||
byte[] hashBytes = Convert.FromBase64String(storedHash);
|
||||
|
||||
public static bool VerifyPassword(string enteredPassword, string storedHash)
|
||||
{
|
||||
byte[] hashBytes = Convert.FromBase64String(storedHash);
|
||||
// Extract the salt from the stored hash
|
||||
byte[] salt = new byte[16];
|
||||
Array.Copy(hashBytes, 0, salt, 0, 16);
|
||||
|
||||
// Extract the salt from the stored hash
|
||||
byte[] salt = new byte[16];
|
||||
Array.Copy(hashBytes, 0, salt, 0, 16);
|
||||
|
||||
// Hash the entered password with the stored salt
|
||||
using (
|
||||
var pbkdf2 = new Rfc2898DeriveBytes(
|
||||
enteredPassword,
|
||||
salt,
|
||||
10000,
|
||||
HashAlgorithmName.SHA256
|
||||
)
|
||||
// Hash the entered password with the stored salt
|
||||
using (
|
||||
var pbkdf2 = new Rfc2898DeriveBytes(
|
||||
enteredPassword,
|
||||
salt,
|
||||
10000,
|
||||
HashAlgorithmName.SHA256
|
||||
)
|
||||
{
|
||||
byte[] newHash = pbkdf2.GetBytes(32);
|
||||
|
||||
// Compare the computed hash with the stored hash
|
||||
for (int i = 0; i < 32; i++)
|
||||
{
|
||||
if (newHash[i] != hashBytes[i + 16])
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public static void HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
|
||||
)
|
||||
{
|
||||
try
|
||||
{
|
||||
// extract data from body
|
||||
string body;
|
||||
using (
|
||||
StreamReader bodyReader = new StreamReader(
|
||||
request.InputStream,
|
||||
request.ContentEncoding
|
||||
)
|
||||
)
|
||||
{
|
||||
body = bodyReader.ReadToEnd();
|
||||
}
|
||||
JObject jsonObject = JObject.Parse(body);
|
||||
string mail = jsonObject["mail"]?.ToString() ?? "";
|
||||
string password = jsonObject["password"]?.ToString() ?? "";
|
||||
byte[] newHash = pbkdf2.GetBytes(32);
|
||||
|
||||
// prepare SQL query
|
||||
MySqlCommand cmd = new MySqlCommand();
|
||||
cmd.CommandText =
|
||||
// Compare the computed hash with the stored hash
|
||||
for (int i = 0; i < 32; i++)
|
||||
{
|
||||
if (newHash[i] != hashBytes[i + 16])
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public static void HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
|
||||
{
|
||||
try
|
||||
{
|
||||
// extract data from body
|
||||
string body;
|
||||
using (StreamReader bodyReader = new(request.InputStream, request.ContentEncoding))
|
||||
{
|
||||
body = bodyReader.ReadToEnd();
|
||||
}
|
||||
JObject jsonObject = JObject.Parse(body);
|
||||
string mail = jsonObject["mail"]?.ToString() ?? "";
|
||||
string password = jsonObject["password"]?.ToString() ?? "";
|
||||
|
||||
// prepare SQL query
|
||||
MySqlCommand cmd = new()
|
||||
{
|
||||
CommandText =
|
||||
@"SELECT u.id, password FROM User u
|
||||
INNER JOIN Password p ON p.user=u.id
|
||||
WHERE mail=@mail;";
|
||||
cmd.Parameters.AddWithValue("@mail", mail);
|
||||
WHERE mail=@mail;",
|
||||
};
|
||||
cmd.Parameters.AddWithValue("@mail", mail);
|
||||
|
||||
using (MySqlConnection conn = new MySqlConnection(connectionString))
|
||||
{
|
||||
cmd.Connection = conn;
|
||||
conn.Open();
|
||||
// execute query and read results
|
||||
MySqlDataReader reader = cmd.ExecuteReader();
|
||||
string? userId = "";
|
||||
string? hashedPass = "";
|
||||
string? jsonResponse;
|
||||
while (reader.Read())
|
||||
{
|
||||
userId = Convert.ToString(reader["id"]);
|
||||
hashedPass = reader.GetString("password");
|
||||
}
|
||||
|
||||
// check username
|
||||
if (string.IsNullOrEmpty(userId))
|
||||
{
|
||||
throw new Exception("Invalid Username or Password");
|
||||
}
|
||||
//check password
|
||||
if (
|
||||
string.IsNullOrEmpty(password)
|
||||
|| string.IsNullOrEmpty(hashedPass)
|
||||
|| !VerifyPassword(password, hashedPass)
|
||||
)
|
||||
{
|
||||
throw new Exception("Invalid Username or Password");
|
||||
}
|
||||
|
||||
jsonResponse = JsonConvert.SerializeObject(GenerateToken(userId));
|
||||
|
||||
// prepare response
|
||||
SendSuccess(response, jsonResponse);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
using (MySqlConnection conn = new(connectionString))
|
||||
{
|
||||
SendError(response, ex);
|
||||
cmd.Connection = conn;
|
||||
conn.Open();
|
||||
// execute query and read results
|
||||
MySqlDataReader reader = cmd.ExecuteReader();
|
||||
string? userId = "";
|
||||
string? hashedPass = "";
|
||||
string? jsonResponse;
|
||||
while (reader.Read())
|
||||
{
|
||||
userId = Convert.ToString(reader["id"]);
|
||||
hashedPass = reader.GetString("password");
|
||||
}
|
||||
|
||||
// check username
|
||||
if (string.IsNullOrEmpty(userId))
|
||||
{
|
||||
throw new Exception("Invalid Username or Password");
|
||||
}
|
||||
//check password
|
||||
if (
|
||||
string.IsNullOrEmpty(password)
|
||||
|| string.IsNullOrEmpty(hashedPass)
|
||||
|| !VerifyPassword(password, hashedPass)
|
||||
)
|
||||
{
|
||||
throw new Exception("Invalid Username or Password");
|
||||
}
|
||||
|
||||
jsonResponse = JsonConvert.SerializeObject(GenerateToken(userId));
|
||||
|
||||
// prepare response
|
||||
SendSuccess(response, jsonResponse);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SendError(response, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,113 +3,102 @@ using System.Security.Cryptography;
|
||||
using MySql.Data.MySqlClient;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace Server
|
||||
namespace Server;
|
||||
|
||||
public class Register : Route
|
||||
{
|
||||
public class Register : Route
|
||||
private static string HashPassword(string password)
|
||||
{
|
||||
private static string HashPassword(string password)
|
||||
// Generate a salt
|
||||
byte[] salt = new byte[16];
|
||||
RandomNumberGenerator.Fill(salt);
|
||||
// Create a PBKDF2 instance to hash the password
|
||||
using var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000, HashAlgorithmName.SHA256);
|
||||
byte[] hash = pbkdf2.GetBytes(32);
|
||||
|
||||
// Combine the salt and the hash together
|
||||
byte[] hashBytes = new byte[48]; // 16 (salt) + 32 (hash)
|
||||
Array.Copy(salt, 0, hashBytes, 0, 16);
|
||||
Array.Copy(hash, 0, hashBytes, 16, 32);
|
||||
|
||||
// Return the final hash as a Base64 encoded string
|
||||
return Convert.ToBase64String(hashBytes);
|
||||
}
|
||||
|
||||
public static void HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
|
||||
{
|
||||
MySqlTransaction? transaction = null;
|
||||
try
|
||||
{
|
||||
// Generate a salt
|
||||
byte[] salt = new byte[16];
|
||||
RandomNumberGenerator.Fill(salt);
|
||||
// Create a PBKDF2 instance to hash the password
|
||||
using (
|
||||
var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000, HashAlgorithmName.SHA256)
|
||||
// extract parameters from req body
|
||||
string body;
|
||||
using (StreamReader bodyReader = new(request.InputStream, request.ContentEncoding))
|
||||
{
|
||||
body = bodyReader.ReadToEnd();
|
||||
}
|
||||
JObject jsonObject = JObject.Parse(body);
|
||||
string f_name = jsonObject["f_name"]?.ToString() ?? "";
|
||||
string l_name = jsonObject["l_name"]?.ToString() ?? "";
|
||||
string password = jsonObject["password"]?.ToString() ?? "";
|
||||
string mail = jsonObject["mail"]?.ToString() ?? "";
|
||||
|
||||
// validate parameters
|
||||
if (
|
||||
string.IsNullOrEmpty(f_name)
|
||||
|| f_name.Length > 30
|
||||
|| f_name.Length < 2
|
||||
|| string.IsNullOrEmpty(l_name)
|
||||
|| l_name.Length > 30
|
||||
|| l_name.Length < 2
|
||||
|| string.IsNullOrEmpty(mail)
|
||||
|| mail.Length > 50
|
||||
|| mail.Length < 6
|
||||
|| string.IsNullOrEmpty(password)
|
||||
|| password.Length > 30
|
||||
|| password.Length < 10
|
||||
)
|
||||
{
|
||||
byte[] hash = pbkdf2.GetBytes(32);
|
||||
throw new Exception("Wrong parameters");
|
||||
}
|
||||
// open connection
|
||||
// prepare SQL query
|
||||
MySqlCommand cmd = new()
|
||||
{
|
||||
// Insert into User
|
||||
CommandText = "INSERT INTO User(f_name,l_name,mail) VALUES(@f_name,@l_name,@mail)",
|
||||
};
|
||||
cmd.Parameters.AddWithValue("@f_name", f_name);
|
||||
cmd.Parameters.AddWithValue("@l_name", l_name);
|
||||
cmd.Parameters.AddWithValue("@mail", mail);
|
||||
|
||||
// Combine the salt and the hash together
|
||||
byte[] hashBytes = new byte[48]; // 16 (salt) + 32 (hash)
|
||||
Array.Copy(salt, 0, hashBytes, 0, 16);
|
||||
Array.Copy(hash, 0, hashBytes, 16, 32);
|
||||
using (MySqlConnection conn = new(connectionString))
|
||||
{
|
||||
conn.Open();
|
||||
transaction = conn.BeginTransaction();
|
||||
cmd.Connection = conn;
|
||||
cmd.ExecuteNonQuery();
|
||||
|
||||
// Return the final hash as a Base64 encoded string
|
||||
return Convert.ToBase64String(hashBytes);
|
||||
// Get user ID
|
||||
cmd.CommandText = "SELECT id FROM User WHERE mail=@mail;";
|
||||
MySqlDataReader reader = cmd.ExecuteReader();
|
||||
reader.Read();
|
||||
var id = reader["id"];
|
||||
reader.Close();
|
||||
|
||||
// Insert into password
|
||||
cmd.CommandText = "INSERT INTO Password(user,password) VALUES(@id,@password)";
|
||||
cmd.Parameters.AddWithValue("@password", HashPassword(password));
|
||||
cmd.Parameters.AddWithValue("@id", id);
|
||||
cmd.ExecuteNonQuery();
|
||||
transaction.Commit();
|
||||
|
||||
SendSuccess(response);
|
||||
}
|
||||
}
|
||||
|
||||
public static void HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
|
||||
catch (Exception ex)
|
||||
{
|
||||
MySqlTransaction? transaction = null;
|
||||
try
|
||||
{
|
||||
// extract parameters from req body
|
||||
string body;
|
||||
using (
|
||||
StreamReader bodyReader = new StreamReader(
|
||||
request.InputStream,
|
||||
request.ContentEncoding
|
||||
)
|
||||
)
|
||||
{
|
||||
body = bodyReader.ReadToEnd();
|
||||
}
|
||||
JObject jsonObject = JObject.Parse(body);
|
||||
string f_name = jsonObject["f_name"]?.ToString() ?? "";
|
||||
string l_name = jsonObject["l_name"]?.ToString() ?? "";
|
||||
string password = jsonObject["password"]?.ToString() ?? "";
|
||||
string mail = jsonObject["mail"]?.ToString() ?? "";
|
||||
|
||||
// validate parameters
|
||||
if (
|
||||
string.IsNullOrEmpty(f_name)
|
||||
|| f_name.Length > 30
|
||||
|| f_name.Length < 2
|
||||
|| string.IsNullOrEmpty(l_name)
|
||||
|| l_name.Length > 30
|
||||
|| l_name.Length < 2
|
||||
|| string.IsNullOrEmpty(mail)
|
||||
|| mail.Length > 50
|
||||
|| mail.Length < 6
|
||||
|| string.IsNullOrEmpty(password)
|
||||
|| password.Length > 30
|
||||
|| password.Length < 10
|
||||
)
|
||||
{
|
||||
throw new Exception("Wrong parameters");
|
||||
}
|
||||
// open connection
|
||||
// prepare SQL query
|
||||
MySqlCommand cmd = new MySqlCommand();
|
||||
|
||||
// Insert into User
|
||||
cmd.CommandText =
|
||||
"INSERT INTO User(f_name,l_name,mail) VALUES(@f_name,@l_name,@mail)";
|
||||
cmd.Parameters.AddWithValue("@f_name", f_name);
|
||||
cmd.Parameters.AddWithValue("@l_name", l_name);
|
||||
cmd.Parameters.AddWithValue("@mail", mail);
|
||||
|
||||
using (MySqlConnection conn = new MySqlConnection(connectionString))
|
||||
{
|
||||
conn.Open();
|
||||
transaction = conn.BeginTransaction();
|
||||
cmd.Connection = conn;
|
||||
cmd.ExecuteNonQuery();
|
||||
|
||||
// Get user ID
|
||||
cmd.CommandText = "SELECT id FROM User WHERE mail=@mail;";
|
||||
MySqlDataReader reader = cmd.ExecuteReader();
|
||||
reader.Read();
|
||||
var id = reader["id"];
|
||||
reader.Close();
|
||||
|
||||
// Insert into password
|
||||
cmd.CommandText = "INSERT INTO Password(user,password) VALUES(@id,@password)";
|
||||
cmd.Parameters.AddWithValue("@password", HashPassword(password));
|
||||
cmd.Parameters.AddWithValue("@id", id);
|
||||
cmd.ExecuteNonQuery();
|
||||
transaction.Commit();
|
||||
|
||||
SendSuccess(response);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (transaction != null)
|
||||
transaction.Rollback();
|
||||
SendError(response, ex);
|
||||
}
|
||||
transaction?.Rollback();
|
||||
SendError(response, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+19
-21
@@ -1,32 +1,30 @@
|
||||
using System.Net;
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
namespace Server
|
||||
namespace Server;
|
||||
|
||||
public class Reset : Route
|
||||
{
|
||||
public class Reset : Route
|
||||
public static void HandleRequest(HttpListenerResponse response)
|
||||
{
|
||||
public static void HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
|
||||
try
|
||||
{
|
||||
try
|
||||
// prepare SQL query
|
||||
MySqlCommand cmd = new() { CommandText = "CALL InitDB" };
|
||||
using (MySqlConnection conn = new MySqlConnection(connectionString))
|
||||
{
|
||||
// prepare SQL query
|
||||
MySqlCommand cmd = new MySqlCommand();
|
||||
cmd.CommandText = "CALL InitDB";
|
||||
using (MySqlConnection conn = new MySqlConnection(connectionString))
|
||||
{
|
||||
cmd.Connection = conn;
|
||||
// open connection
|
||||
conn.Open();
|
||||
// execute query
|
||||
cmd.ExecuteNonQuery();
|
||||
// set up and send response
|
||||
SendSuccess(response);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SendError(response, ex);
|
||||
cmd.Connection = conn;
|
||||
// open connection
|
||||
conn.Open();
|
||||
// execute query
|
||||
cmd.ExecuteNonQuery();
|
||||
// set up and send response
|
||||
SendSuccess(response);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SendError(response, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user