mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-05 18:48:41 +00:00
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:
@@ -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." });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,23 +2,25 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SharpbinV3.Server.Data.Entities;
|
||||
using SharpbinV3.Server.DTOs;
|
||||
using SharpbinV3.Server.DTOs.Paste;
|
||||
using SharpbinV3.Server.Extensions;
|
||||
using SharpbinV3.Server.Services;
|
||||
using SharpbinV3.Server.Settings;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace SharpbinV3.Server.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
public class PasteController(PasteService pasteService, UserService userService, IOptions<PasteSettings> options) : ControllerBase
|
||||
public class PasteController(PasteService pasteService, UserService userService, AuthService authService, IOptions<PasteSettings> options) : ControllerBase
|
||||
{
|
||||
private readonly PasteService _pasteService = pasteService;
|
||||
private readonly UserService _userService = userService;
|
||||
private readonly AuthService _authService = authService;
|
||||
private readonly PasteSettings _pasteSettings = options.Value;
|
||||
|
||||
[HttpPost]
|
||||
[Route("create")]
|
||||
[Authorize(Policy = "NotBanned")]
|
||||
public async Task<IActionResult> CreatePaste(string title = "", string syntax = "plaintext", int visibility = 0, long expiresAt = 0)
|
||||
{
|
||||
if (!await _pasteService.ValidateExpiresAt(expiresAt))
|
||||
@@ -33,9 +35,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
string content = await new StreamReader(Request.Body).ReadToEndAsync();
|
||||
if (System.Text.Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes)
|
||||
return BadRequest(new { message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." });
|
||||
var httpUser = HttpContext.User;
|
||||
var userUUID = httpUser?.FindFirst("UUID")?.Value;
|
||||
User? user = userUUID is not null ? await _userService.GetByUUID(Guid.Parse(userUUID)) : null;
|
||||
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt);
|
||||
return Ok(new
|
||||
{
|
||||
@@ -95,21 +95,17 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
[HttpPut]
|
||||
[Route("{id}/edit")]
|
||||
[Authorize]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
public async Task<IActionResult> EditPaste(string id)
|
||||
{
|
||||
string content = await new StreamReader(Request.Body).ReadToEndAsync();
|
||||
if (content == null || id == null) return NotFound();
|
||||
var paste = await _pasteService.Get(id);
|
||||
if (paste == null) return NotFound();
|
||||
var user = HttpContext.User;
|
||||
var uuidClaim = user?.FindFirst("UUID")?.Value;
|
||||
if (uuidClaim == null || user == null) return Forbid();
|
||||
var hasPrivilegedRole = user.Claims
|
||||
.Where(c => c.Type == ClaimTypes.Role)
|
||||
.Select(c => int.Parse(c.Value))
|
||||
.Any(r => r == 1 || r == 255);
|
||||
if (paste.AuthorUUID != Guid.Parse(uuidClaim) && !hasPrivilegedRole)
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user == null) return Forbid();
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
||||
return Forbid();
|
||||
bool result = await _pasteService.EditText(paste, content);
|
||||
if (!result) return NotFound();
|
||||
@@ -118,19 +114,15 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
[HttpPatch]
|
||||
[Route("{id}/modify")]
|
||||
[Authorize]
|
||||
public async Task<IActionResult> ModifyPasteMetadata(string id, [FromBody] PasteMetadataUpdateRequest request)
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
public async Task<IActionResult> ModifyPasteMetadata(string id, [FromBody] UpdatePasteDto request)
|
||||
{
|
||||
var paste = await _pasteService.Get(id);
|
||||
if (paste == null) return NotFound();
|
||||
var user = HttpContext.User;
|
||||
var uuidClaim = user?.FindFirst("UUID")?.Value;
|
||||
if (uuidClaim == null || user == null) return Forbid();
|
||||
var hasPrivilegedRole = user.Claims
|
||||
.Where(c => c.Type == ClaimTypes.Role)
|
||||
.Select(c => int.Parse(c.Value))
|
||||
.Any(r => r == 1 || r == 255);
|
||||
if (paste.AuthorUUID != Guid.Parse(uuidClaim) && !hasPrivilegedRole)
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user == null) return Forbid();
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
||||
return Forbid();
|
||||
if (request.Title != null)
|
||||
paste.Title = request.Title;
|
||||
@@ -171,19 +163,15 @@ namespace SharpbinV3.Server.Controllers
|
||||
}
|
||||
[HttpDelete]
|
||||
[Route("{id}/delete")]
|
||||
[Authorize]
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
public async Task<IActionResult> DeletePaste(string id)
|
||||
{
|
||||
var paste = await _pasteService.Get(id);
|
||||
if (paste == null) return NotFound();
|
||||
var user = HttpContext.User;
|
||||
var uuidClaim = user?.FindFirst("UUID")?.Value;
|
||||
if (uuidClaim == null || user == null) return Forbid();
|
||||
var hasPrivilegedRole = user.Claims
|
||||
.Where(c => c.Type == ClaimTypes.Role)
|
||||
.Select(c => int.Parse(c.Value))
|
||||
.Any(r => r == 1 || r == 255);
|
||||
if (paste.AuthorUUID != Guid.Parse(uuidClaim) && !hasPrivilegedRole)
|
||||
var user = HttpContext.GetJwtUser();
|
||||
if (user == null) return Forbid();
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
||||
return Forbid();
|
||||
bool result = await _pasteService.Delete(paste);
|
||||
if (!result) return NotFound();
|
||||
|
||||
@@ -4,17 +4,23 @@ using Microsoft.EntityFrameworkCore;
|
||||
using SharpbinV3.Server.Data;
|
||||
using SharpbinV3.Server.Data.Entities;
|
||||
using SharpbinV3.Server.DTOs;
|
||||
using SharpbinV3.Server.DTOs.User;
|
||||
using SharpbinV3.Server.Extensions;
|
||||
using SharpbinV3.Server.Services;
|
||||
using System.Security.Claims;
|
||||
using SharpbinV3.Server.Services.Verification;
|
||||
using SharpbinV3.Server.Services.Verification.Providers;
|
||||
|
||||
namespace SharpbinV3.Server.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class UserController(UserService userService, AppDbContext db) : ControllerBase
|
||||
public class UserController(UserService userService, AppDbContext db, AuthService authService, TotpVerificationProvider totp, VerificationService verificationService) : ControllerBase
|
||||
{
|
||||
private readonly UserService _userService = userService;
|
||||
private readonly AppDbContext _db = db;
|
||||
private readonly AuthService _authService = authService;
|
||||
private readonly TotpVerificationProvider _totp = totp;
|
||||
private readonly VerificationService _verificationService = verificationService;
|
||||
|
||||
[HttpGet("{username}")]
|
||||
public async Task<IActionResult> GetByUsername(string username, [FromQuery] int page = 1)
|
||||
@@ -44,33 +50,39 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
[HttpPatch("uuid/{uuid}")]
|
||||
[Authorize]
|
||||
public async Task<IActionResult> UpdateByUUID(Guid uuid, [FromBody] UpdateUserRequest updatedUser)
|
||||
public async Task<IActionResult> UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(ModelState);
|
||||
var jwtUser = HttpContext.User;
|
||||
var uuidClaim = jwtUser?.FindFirst("UUID")?.Value;
|
||||
if (uuidClaim == null || jwtUser == null) return Forbid();
|
||||
var userRoles = jwtUser.Claims
|
||||
.Where(c => c.Type == ClaimTypes.Role)
|
||||
.Select(c => int.Parse(c.Value));
|
||||
|
||||
var jwtUser = HttpContext.GetJwtUser();
|
||||
if (jwtUser == null) return Forbid();
|
||||
var user = await _userService.GetByUUID(uuid);
|
||||
if (user == null)
|
||||
return NotFound();
|
||||
if (!userRoles.Any(r => r == 1 || r == 255) && user.UUID != Guid.Parse(uuidClaim))
|
||||
if (!jwtUser.Roles.Any(r => r == 1 || r == 255) && user.UUID != jwtUser.UUID)
|
||||
return Forbid();
|
||||
if (user.Roles.Contains(255) && !userRoles.Contains(255))
|
||||
if (user.Roles.Contains(255) && !jwtUser.Roles.Contains(255))
|
||||
return Forbid();
|
||||
|
||||
user.DisplayName = updatedUser.DisplayName ?? user.DisplayName;
|
||||
if (userRoles.Any(r => r == 255) || user.UUID == Guid.Parse(uuidClaim)) // only admins or self
|
||||
if (jwtUser.Roles.Any(r => r == 255) || user.UUID == jwtUser.UUID) // only admins or self
|
||||
{
|
||||
user.Email = updatedUser.Email ?? user.Email;
|
||||
user.Visibility = updatedUser.Visibility ?? user.Visibility;
|
||||
}
|
||||
if (userRoles.Any(r => r == 255))
|
||||
if (jwtUser.Roles.Contains(255))
|
||||
{
|
||||
if (updatedUser.Roles.Contains(255) && jwtUser.TotpEnabled)
|
||||
{
|
||||
if (string.IsNullOrEmpty(updatedUser.TotpCode) || !await _totp.VerifyAsync(new VerificationContext
|
||||
{
|
||||
UserUUID = jwtUser.UUID,
|
||||
Code = updatedUser.TotpCode
|
||||
}))
|
||||
{
|
||||
return Unauthorized(new { message = "Invalid TOTP code." });
|
||||
}
|
||||
}
|
||||
user.Roles = updatedUser.Roles ?? user.Roles;
|
||||
}
|
||||
|
||||
@@ -79,22 +91,39 @@ namespace SharpbinV3.Server.Controllers
|
||||
}
|
||||
|
||||
[HttpDelete("uuid/{uuid}")]
|
||||
[Authorize]
|
||||
public async Task<IActionResult> DeleteByUUID(Guid uuid)
|
||||
[Authorize(Policy = "AuthAndNotBanned")]
|
||||
public async Task<IActionResult> DeleteByUUID(Guid uuid, [FromBody] DeleteUserDto dto)
|
||||
{
|
||||
var jwtUser = HttpContext.User;
|
||||
var uuidClaim = jwtUser?.FindFirst("UUID")?.Value;
|
||||
if (uuidClaim == null || jwtUser == null) return Forbid();
|
||||
var userRoles = jwtUser.Claims
|
||||
.Where(c => c.Type == ClaimTypes.Role)
|
||||
.Select(c => int.Parse(c.Value));
|
||||
|
||||
var jwtUser = HttpContext.GetJwtUser();
|
||||
if (jwtUser == null) return Forbid();
|
||||
var user = await _userService.GetByUUID(uuid);
|
||||
if (user == null)
|
||||
return NotFound();
|
||||
if (!userRoles.Any(r => r == 255) && user.UUID != Guid.Parse(uuidClaim))
|
||||
if (user == null) return Forbid();
|
||||
if (!jwtUser.Roles.Any(r => r == 255) && user.UUID != jwtUser.UUID)
|
||||
return Forbid();
|
||||
|
||||
if (jwtUser.TotpEnabled)
|
||||
{
|
||||
if (string.IsNullOrEmpty(dto.TotpCode) || !await _totp.VerifyAsync(new VerificationContext
|
||||
{
|
||||
UserUUID = jwtUser.UUID,
|
||||
Code = dto.TotpCode
|
||||
}))
|
||||
{
|
||||
return Unauthorized(new { message = "Invalid TOTP code." });
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (string.IsNullOrEmpty(dto.Token) || !await _verificationService.VerifyAsync(new VerificationContext
|
||||
{
|
||||
Token = dto.Token,
|
||||
Ip = HttpContext.GetRequestIP()
|
||||
}))
|
||||
{
|
||||
return Unauthorized(new { message = "Invalid verification token." });
|
||||
}
|
||||
}
|
||||
|
||||
_db.Users.Remove(user);
|
||||
await _db.SaveChangesAsync();
|
||||
return Ok(new { message = "User deleted successfully." });
|
||||
@@ -139,7 +168,6 @@ namespace SharpbinV3.Server.Controllers
|
||||
})
|
||||
.ToListAsync();
|
||||
|
||||
|
||||
var pagination = new
|
||||
{
|
||||
Page = page,
|
||||
|
||||
Reference in New Issue
Block a user