102 lines
2.6 KiB
C#
102 lines
2.6 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using Shadow.Data;
|
|
using Shadow.Entities;
|
|
using System.Text;
|
|
using System.Xml.Serialization;
|
|
|
|
namespace Shadow.Tools;
|
|
|
|
public class GeneralUseHelpers(ApplicationDbContext? db = null, IConfiguration? appsettings = null)
|
|
{
|
|
private readonly ApplicationDbContext? _db = db;
|
|
private readonly IConfiguration? _appsettings = appsettings;
|
|
|
|
|
|
//async public Task<User?> GetUserFromEmail(string email)
|
|
//{
|
|
// return await _db.Users.FirstOrDefaultAsync(e => e.Email == email);
|
|
//}
|
|
|
|
//public string HashWithSHA512(string s)
|
|
//{
|
|
// using (var sha512 = SHA512.Create())
|
|
// {
|
|
// byte[] bytes = Encoding.ASCII.GetBytes(s);
|
|
// byte[] hash = sha512.ComputeHash(bytes);
|
|
// string hashstring = BitConverter.ToString(hash).Replace("-", "").ToLower();
|
|
// return hashstring;
|
|
// }
|
|
//}
|
|
|
|
/// <summary>
|
|
/// Quick and dirty Dictionary<string, string> to JSON serializer
|
|
/// </summary>
|
|
/// <param name="dict">Dictionary with keypair of two strings</param>
|
|
/// <returns>Minified JSON</returns>
|
|
public static string DictAsJson(Dictionary<string, string> dict)
|
|
{
|
|
string resultJson = String.Empty;
|
|
|
|
foreach (string key in dict.Keys)
|
|
{
|
|
string cleanKey = key.Replace("\"", "\\\""); // "a"b" -> "a\"b"
|
|
string cleanValue = dict[key].Replace("\"", "\\\"");
|
|
resultJson += $"\"{cleanKey}\": \"{cleanValue}\", " // "key": "val",<space>
|
|
.Replace(@"\", @"\\"); // a\b -> a\\b
|
|
}
|
|
|
|
return "{" + resultJson[..^2] + "}";
|
|
}
|
|
|
|
public async Task<User?> GetUserFromForm(HttpRequest request)
|
|
{
|
|
User? user = null;
|
|
try
|
|
{
|
|
string username = request.Form["u"]!;
|
|
string saltedPassword = request.Form["t"]!;
|
|
string sesame = request.Form["s"]!;
|
|
|
|
User? foundUser = _db?.Users
|
|
.FirstOrDefault(u => u.NormalizedName == username.ToLower());
|
|
|
|
if (foundUser == null)
|
|
return user;
|
|
|
|
string resaltedPassword = MetadataExtractor.GetStringMD5($"{foundUser.Password}{sesame}");
|
|
if (resaltedPassword == saltedPassword)
|
|
user = foundUser;
|
|
}
|
|
catch
|
|
{
|
|
user = null;
|
|
}
|
|
|
|
return user;
|
|
}
|
|
|
|
public async Task<User?> GetUserFromParams(HttpRequest request)
|
|
{
|
|
User? user = null;
|
|
try
|
|
{
|
|
string username = request.Query["u"]!;
|
|
string saltedPassword = request.Query["t"]!;
|
|
string sesame = request.Query["s"]!;
|
|
|
|
User foundUser = _db!.Users
|
|
.FirstOrDefault(u => u.NormalizedName == username.ToLower())!;
|
|
|
|
string resaltedPassword = MetadataExtractor.GetStringMD5($"{foundUser.Password}{sesame}");
|
|
if (resaltedPassword == saltedPassword)
|
|
user = foundUser;
|
|
}
|
|
catch
|
|
{
|
|
user = null;
|
|
}
|
|
|
|
return user;
|
|
}
|
|
}
|