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
+111 -7
View File
@@ -1,10 +1,17 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.DTOs.Auth;
using SharpbinV3.Server.DTOs.User;
using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Services;
using SharpbinV3.Server.Services.Verification;
using SharpbinV3.Server.Services.Verification.Providers;
using SharpbinV3.Server.Settings;
using Bcrypt = BCrypt.Net.BCrypt;
@@ -12,20 +19,29 @@ namespace SharpbinV3.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class AuthController(UserService userService, AuthService authService, IOptions<AuthSettings> options, VerificationService verification) : ControllerBase
public class AuthController(UserService userService, AuthService authService, IOptions<AuthSettings> options,
VerificationService verification, TotpVerificationProvider totp, AppDbContext db) : ControllerBase
{
private readonly AuthService _authService = authService;
private readonly UserService _userService = userService;
private readonly VerificationService _verification = verification;
private readonly TotpVerificationProvider _totp = totp;
private readonly AppDbContext _db = db;
[HttpPost]
[EnableRateLimiting("Sliding")]
[Route("register")]
public async Task<IActionResult> Register([FromBody] RegisterRequest request)
public async Task<IActionResult> Register([FromBody] RegisterUserDto request)
{
if (!options.Value.Registration_Enabled)
return BadRequest(new { message = "Registration is disabled." });
if (!await _verification.VerifyAsync(request.Token, Utilities.GetRequestIP(HttpContext)))
if (!ModelState.IsValid)
return BadRequest(ModelState);
if (!await _verification.VerifyAsync(new VerificationContext
{
Token = request.Token,
Ip = HttpContext.GetRequestIP()
}))
return BadRequest(new { message = "Verification failed." });
var existingUser = await _userService.GetByUsername(request.Username);
@@ -60,12 +76,16 @@ namespace SharpbinV3.Server.Controllers
[HttpPost]
[Route("login")]
[EnableRateLimiting("Sliding")]
public async Task<IActionResult> Login([FromBody] LoginRequest request)
public async Task<IActionResult> Login([FromBody] LoginUserDto request)
{
if (string.IsNullOrEmpty(request.Username) && string.IsNullOrEmpty(request.Email))
return BadRequest(new { message = "Username or email is required." });
if (!await _verification.VerifyAsync(request.Token, Utilities.GetRequestIP(HttpContext)))
if (!await _verification.VerifyAsync(new VerificationContext
{
Token = request.Token,
Ip = HttpContext.GetRequestIP()
}))
return BadRequest(new { message = "Verification failed." });
User? user = null;
@@ -77,6 +97,20 @@ namespace SharpbinV3.Server.Controllers
if (user == null) return BadRequest(new { message = "Invalid username/email or password." });
if (!Bcrypt.Verify(request.Password, user.PasswordHash))
return BadRequest(new { message = "Invalid username/email or password." });
var totpEnabled = await _db.UserTotps.AnyAsync(t => t.UserUUID == user.UUID);
if (totpEnabled)
{
if (string.IsNullOrWhiteSpace(request.TotpCode))
return BadRequest(new { message = "TOTP code is required." });
var totpValid = await _totp.VerifyAsync(new VerificationContext
{
UserUUID = user.UUID,
Code = request.TotpCode
});
if (!totpValid)
return BadRequest(new { message = "Invalid TOTP code." });
}
var token = _authService.GenerateJWTToken(user);
await _authService.UpdateLoginTime(user);
return Ok(new { token.Result });
@@ -84,7 +118,7 @@ namespace SharpbinV3.Server.Controllers
[HttpPost]
[Route("refresh")]
[EnableRateLimiting("Sliding")]
public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenRequest request)
public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenDto request)
{
try
{
@@ -108,5 +142,75 @@ namespace SharpbinV3.Server.Controllers
registration_enabled = authSettings.Registration_Enabled
});
}
[HttpGet]
[Authorize]
[Route("totp/enroll")]
public async Task<IActionResult> StartTotpEnrollment()
{
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user is null) return BadRequest(new { message = "User not found." });
var secret = _totp.GenerateSecret();
var secretBase32 = _totp.ToBase32(secret);
var account = string.IsNullOrWhiteSpace(user.Email) ? user.Username : user.Email!;
var uri = _totp.BuildOtpAuthUri("SharpbinV3", account, secretBase32);
return Ok(new { secret = secretBase32, otpauth = uri });
}
[HttpPost]
[Authorize]
[Route("totp/enable")]
public async Task<IActionResult> EnableTotp([FromBody] EnableTotpDto request)
{
var uuidClaim = User.Claims.FirstOrDefault(c => c.Type == "UUID")?.Value;
if (string.IsNullOrEmpty(uuidClaim)) return Unauthorized();
var uuid = Guid.Parse(uuidClaim);
if (string.IsNullOrWhiteSpace(request.Secret) || string.IsNullOrWhiteSpace(request.Code))
return BadRequest(new { message = "Secret and code are required." });
if (!_totp.VerifyWithSecretBase32(request.Secret, request.Code))
return BadRequest(new { message = "Invalid TOTP code." });
var secretBytes = _totp.FromBase32(request.Secret);
var protectedBytes = _totp.Protect(secretBytes);
var existing = await _db.UserTotps.FirstOrDefaultAsync(t => t.UserUUID == uuid);
if (existing is null)
{
var entry = new UserTotp { UserUUID = uuid, EncryptedSecret = protectedBytes };
_db.UserTotps.Add(entry);
}
else
{
existing.EncryptedSecret = protectedBytes;
_db.UserTotps.Update(existing);
}
await _db.SaveChangesAsync();
return Ok(new { message = "TOTP enabled." });
}
[HttpPost]
[Authorize]
[Route("totp/disable")]
public async Task<IActionResult> DisableTotp([FromBody] DisableTotpDto dto)
{
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null) return BadRequest(new { message = "User not found." });
if (string.IsNullOrWhiteSpace(dto.Code))
return BadRequest(new { message = "TOTP code is required." });
var existing = await _db.UserTotps.FirstOrDefaultAsync(t => t.UserUUID == user.UUID);
if (existing is null)
return BadRequest(new { message = "TOTP is not enabled." });
if (!_totp.VerifyAsync(new VerificationContext
{
UserUUID = user.UUID,
Code = dto.Code
}).Result)
return BadRequest(new { message = "Invalid TOTP code." });
_db.UserTotps.Remove(existing);
await _db.SaveChangesAsync();
return Ok(new { message = "TOTP disabled." });
}
}
}