feat: totp 2fa; httpcontext extension for jwtuser; asp.net data protection; prevent banned users from certain actions; account deletion requires 2fa if enabled; making users admins requires 2fa if enabled; httpcontext extension to get ip; enhance user store

refactor: organize dtos by domain; verification providers use verification context; move ip parsing into http context extensions
chore: clean code
This commit is contained in:
2026-01-07 16:36:41 -05:00
parent 361cf76f46
commit 20ceb91db8
46 changed files with 1568 additions and 162 deletions
@@ -4,6 +4,6 @@
{
int Priority { get; }
bool IsConfigured { get; }
Task<bool> VerifyAsync(string token, string? ip);
Task<bool> VerifyAsync(VerificationContext context);
}
}
@@ -0,0 +1,73 @@
using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using OtpNet;
using SharpbinV3.Server.Data;
namespace SharpbinV3.Server.Services.Verification.Providers
{
public sealed class TotpVerificationProvider : IVerificationProvider
{
private readonly AppDbContext _db;
private readonly IDataProtector _protector;
private readonly IMemoryCache _cache;
public TotpVerificationProvider(AppDbContext db, IDataProtectionProvider dataProtectionProvider, IMemoryCache cache)
{
_db = db;
_protector = dataProtectionProvider.CreateProtector("TotpSecret-v1");
_cache = cache;
}
public int Priority => 0;
public bool IsConfigured => false;
public async Task<bool> VerifyAsync(VerificationContext ctx)
{
if (ctx.UserUUID is null) return false;
if (string.IsNullOrWhiteSpace(ctx.Code)) return false;
var userTotp = await _db.UserTotps.FirstOrDefaultAsync(t => t.UserUUID == ctx.UserUUID.Value);
if (userTotp is null) return false;
var secret = _protector.Unprotect(userTotp.EncryptedSecret);
if (!VerifyCode(secret, ctx.Code, out var step))
return false;
var key = $"totp:{ctx.UserUUID}:{step}";
if (_cache.TryGetValue(key, out _))
return false;
_cache.Set(key, true, TimeSpan.FromSeconds(60));
return true;
}
public byte[] GenerateSecret(int size = 20) => KeyGeneration.GenerateRandomKey(size);
public string ToBase32(byte[] data) => Base32Encoding.ToString(data);
public byte[] FromBase32(string base32) => string.IsNullOrWhiteSpace(base32) ? [] : Base32Encoding.ToBytes(base32);
public string BuildOtpAuthUri(string issuer, string accountName, string secretBase32, int digits = 6, int period = 30, string algorithm = "SHA1")
{
var label = Uri.EscapeDataString($"{issuer}:{accountName}");
var query = $"secret={secretBase32}&issuer={Uri.EscapeDataString(issuer)}&algorithm={algorithm}&digits={digits}&period={period}";
return $"otpauth://totp/{label}?{query}";
}
public byte[] Protect(byte[] secret) => _protector.Protect(secret);
public byte[] Unprotect(byte[] protectedSecret) => _protector.Unprotect(protectedSecret);
public bool VerifyWithSecretBase32(string secretBase32, string code, int digits = 6, int period = 30, int window = 1)
{
var secret = FromBase32(secretBase32);
return VerifyCode(secret, code, out _, digits, period, window);
}
private bool VerifyCode(byte[] secret, string code, out long matchedStep, int digits = 6, int period = 30, int window = 1)
{
var totp = new Totp(secret, step: period, mode: OtpHashMode.Sha1, totpSize: digits);
return totp.VerifyTotp(code, out matchedStep, new VerificationWindow(previous: window, future: window));
}
private string ComputeCode(byte[] key, long timestep, int digits) => new Totp(key, totpSize: digits).ComputeTotp(DateTime.UtcNow);
}
}
@@ -1,5 +1,5 @@
using Microsoft.Extensions.Options;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.DTOs.Auth;
using SharpbinV3.Server.Settings;
using System.Text.Json;
@@ -13,26 +13,28 @@ namespace SharpbinV3.Server.Services.Verification.Providers
public int Priority => 1;
public bool IsConfigured => !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SecretKey) && !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SiteKey);
public async Task<bool> VerifyAsync(string token, string? ip)
public async Task<bool> VerifyAsync(VerificationContext ctx)
{
if (_authSettings.CF_Turnstile_SecretKey is null)
throw new InvalidOperationException("Turnstile secret key is not configured.");
if (string.IsNullOrEmpty(ctx.Token))
return false;
var parameters = new Dictionary<string, string>
{
{ "secret", _authSettings.CF_Turnstile_SecretKey },
{ "response", token }
{ "response", ctx.Token }
};
if (!string.IsNullOrEmpty(ip))
parameters.Add("remoteip", ip);
if (!string.IsNullOrEmpty(ctx.Ip))
parameters.Add("remoteip", ctx.Ip);
var postContent = new FormUrlEncodedContent(parameters);
var response = await httpClient.PostAsync(SiteverifyUrl, postContent);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
var result = JsonSerializer.Deserialize<TurnstileResponse>(json);
var result = JsonSerializer.Deserialize<TurnstileResponseDto>(json);
return result?.Success ?? false;
}
}
@@ -0,0 +1,12 @@
namespace SharpbinV3.Server.Services.Verification
{
public sealed class VerificationContext
{
public string? Token { get; init; }
public string? Ip { get; init; }
public Guid? UserUUID { get; init; }
public string? Code { get; init; }
}
}
@@ -14,18 +14,17 @@ namespace SharpbinV3.Server.Services.Verification
.FirstOrDefault();
}
public async Task<bool> VerifyAsync(string? token, string? ip)
public async Task<bool> VerifyAsync(VerificationContext context, IVerificationProvider? provider = null)
{
var provider = GetActiveProvider();
var activeProvider = provider ?? GetActiveProvider();
if (provider is null)
if (activeProvider is null)
return true;
if (string.IsNullOrWhiteSpace(token))
if (string.IsNullOrWhiteSpace(context.Token))
return false;
return await provider.VerifyAsync(token, ip);
return await activeProvider.VerifyAsync(context);
}
}
}