refractoring

This commit is contained in:
QkoSad
2024-12-05 12:09:30 +02:00
parent 926436860c
commit 80040638a6
37 changed files with 814 additions and 682 deletions
+109 -110
View File
@@ -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);
}
}
}
+25 -26
View File
@@ -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
View File
@@ -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);
}
}
}
+79 -80
View File
@@ -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
View File
@@ -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
View File
@@ -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);
}
}
}
+86 -97
View File
@@ -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
View File
@@ -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);
}
}
}