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
+30 -8
View File
@@ -3,7 +3,7 @@ using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.DTOs.Auth;
using SharpbinV3.Server.Settings;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
@@ -12,6 +12,15 @@ using Bcrypt = BCrypt.Net.BCrypt;
namespace SharpbinV3.Server.Services
{
public class JwtUser
{
public Guid UUID { get; set; }
public string Username { get; set; } = string.Empty;
public string DisplayName { get; set; } = string.Empty;
public bool TotpEnabled { get; set; }
public int[] Roles { get; set; } = [];
public DateTime Expires { get; set; }
}
public sealed class AuthService(AppDbContext db, IOptions<JWTSettings> jwtOptions, IOptions<AuthSettings> authOptions)
{
private readonly AppDbContext _db = db;
@@ -30,20 +39,24 @@ namespace SharpbinV3.Server.Services
};
if (_authSettings.First_User_Admin && !await _db.Users.AnyAsync())
user.Roles = [0,1,255];
user.Roles = [0, 1, 255];
_db.Users.Add(user);
await _db.SaveChangesAsync();
return user;
}
public async Task<JWTResult> GenerateJWTToken(User user)
public async Task<CreateJWT> GenerateJWTToken(User user)
{
var jwtHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(_jwtSettings.Secret);
var totpEnabled = await _db.UserTotps.AnyAsync(t => t.UserUUID == user.UUID);
var claims = new List<Claim>
{
new("UUID", user.UUID.ToString()),
new("Username", user.Username),
new("DisplayName", user.DisplayName ?? ""),
new("TOTP_Enabled", totpEnabled.ToString()),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
@@ -100,7 +113,7 @@ namespace SharpbinV3.Server.Services
await _db.SaveChangesAsync();
return new JWTResult()
return new CreateJWT()
{
Token = jwtToken,
Success = true,
@@ -108,7 +121,7 @@ namespace SharpbinV3.Server.Services
};
}
public async Task<JWTResult> RefreshJWTToken(string token, string refreshToken)
public async Task<CreateJWT> RefreshJWTToken(string token, string refreshToken)
{
var jwtHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(_jwtSettings.Secret);
@@ -135,20 +148,20 @@ namespace SharpbinV3.Server.Services
|| storedRefreshToken.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
|| storedRefreshToken.JwtId != jwtId)
{
return new JWTResult() { Success = false, Errors = ["Invalid refresh token, possibly already used or expired."] };
return new CreateJWT() { Success = false, Errors = ["Invalid refresh token, possibly already used or expired."] };
}
storedRefreshToken.Used = true;
await _db.SaveChangesAsync();
var userUUID = principal.Claims.First(c => c.Type == "UUID").Value;
var user = await _db.Users.FirstOrDefaultAsync(u => u.UUID == Guid.Parse(userUUID));
if (user == null || storedRefreshToken.UserUUID != Guid.Parse(userUUID))
return new JWTResult() { Success = false, Errors = ["Invalid token."] };
return new CreateJWT() { Success = false, Errors = ["Invalid token."] };
return await GenerateJWTToken(user);
}
catch
{
return new JWTResult() { Success = false, Errors = ["Server Error"] };
return new CreateJWT() { Success = false, Errors = ["Server Error"] };
}
}
@@ -172,5 +185,14 @@ namespace SharpbinV3.Server.Services
_db.Users.Update(existingUser);
await _db.SaveChangesAsync();
}
public async Task<User?> GetUserFromHttpContext(HttpContext context)
{
var uuidClaim = context.User.Claims.FirstOrDefault(c => c.Type == "UUID")?.Value;
if (uuidClaim == null)
return null;
var userUUID = Guid.Parse(uuidClaim);
return await _db.Users.FirstOrDefaultAsync(u => u.UUID == userUUID);
}
}
}
@@ -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);
}
}
}