Adds PasswordHasher + DbSetup

This commit is contained in:
Janus C. H. Knudsen 2025-01-21 23:26:05 +01:00
parent 4ec4beef21
commit db09261768
7 changed files with 269 additions and 45 deletions

View file

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Core.Entities.Users
{
public class User
{
public int Id { get; set; }
public string Email { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public bool EmailConfirmed { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime? LastLoginDate { get; set; }
}
public class Tenant
{
public int Id { get; set; }
public string ConnectionString { get; set; }
public DateTime CreatedDate { get; set; }
public int CreatedBy { get; set; }
public bool IsActive { get; set; }
}
public class UserTenant
{
public int UserId { get; set; }
public int TenantId { get; set; }
public DateTime CreatedDate { get; set; }
}
}

View file

@ -0,0 +1,47 @@
namespace Core.Entities.Users
{
public static class PasswordHasher
{
private const int _saltSize = 16; // 128 bit
private const int _keySize = 32; // 256 bit
private const int _iterations = 100000;
public static string HashPassword(string password)
{
using (var algorithm = new System.Security.Cryptography.Rfc2898DeriveBytes(
password,
_saltSize,
_iterations,
System.Security.Cryptography.HashAlgorithmName.SHA256))
{
var key = Convert.ToBase64String(algorithm.GetBytes(_keySize));
var salt = Convert.ToBase64String(algorithm.Salt);
return $"{_iterations}.{salt}.{key}";
}
}
public static bool VerifyPassword(string hash, string password)
{
var parts = hash.Split('.', 3);
if (parts.Length != 3)
{
return false;
}
var iterations = Convert.ToInt32(parts[0]);
var salt = Convert.FromBase64String(parts[1]);
var key = Convert.FromBase64String(parts[2]);
using (var algorithm = new System.Security.Cryptography.Rfc2898DeriveBytes(
password,
salt,
iterations,
System.Security.Cryptography.HashAlgorithmName.SHA256))
{
var keyToCheck = algorithm.GetBytes(_keySize);
return keyToCheck.SequenceEqual(key);
}
}
}
}