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
+1
View File
@@ -0,0 +1 @@
SharpbinV3
@@ -0,0 +1,29 @@
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
namespace SharpbinV3.Server.Authorization
{
public sealed class NotBannedHandler(bool requireAuth = false) : AuthorizationHandler<NotBannedRequirement>
{
private readonly bool _requireAuth = requireAuth;
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
NotBannedRequirement requirement)
{
var isAuthenticated = context.User.Identity?.IsAuthenticated ?? false;
if (_requireAuth && !isAuthenticated)
return Task.CompletedTask;
var isBanned = context.User.Claims.Any(c =>
(c.Type == ClaimTypes.Role || c.Type == "role") &&
c.Value == "403");
if (!isBanned)
context.Succeed(requirement);
return Task.CompletedTask;
}
}
}
@@ -0,0 +1,8 @@
using Microsoft.AspNetCore.Authorization;
namespace SharpbinV3.Server.Authorization
{
public class NotBannedRequirement : IAuthorizationRequirement
{
}
}
+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." });
}
}
}
@@ -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();
+55 -27
View File
@@ -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,
@@ -1,6 +1,6 @@
namespace SharpbinV3.Server.DTOs
namespace SharpbinV3.Server.DTOs.Auth
{
public class JWTResult
public class CreateJWT
{
public string? Token { get; set; }
public string? RefreshToken { get; set; }
@@ -0,0 +1,7 @@
namespace SharpbinV3.Server.DTOs.Auth
{
public class DisableTotpDto
{
public string Code { get; set; } = string.Empty;
}
}
@@ -0,0 +1,8 @@
namespace SharpbinV3.Server.DTOs.Auth
{
public sealed class EnableTotpDto
{
public string Secret { get; set; } = string.Empty;
public string Code { get; set; } = string.Empty;
}
}
@@ -1,8 +1,8 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.DTOs
namespace SharpbinV3.Server.DTOs.Auth
{
public class RefreshTokenRequest
public class RefreshTokenDto
{
[Required]
public required string Token { get; set; }
@@ -1,8 +1,8 @@
using System.Text.Json.Serialization;
namespace SharpbinV3.Server.DTOs
namespace SharpbinV3.Server.DTOs.Auth
{
public class TurnstileResponse
public class TurnstileResponseDto
{
[JsonPropertyName("success")]
public bool Success { get; set; }
@@ -1,6 +1,6 @@
namespace SharpbinV3.Server.DTOs
namespace SharpbinV3.Server.DTOs.Paste
{
public class PasteMetadataUpdateRequest
public class UpdatePasteDto
{
public string? Title { get; set; }
public string? Syntax { get; set; }
@@ -0,0 +1,8 @@
namespace SharpbinV3.Server.DTOs.User
{
public class DeleteUserDto
{
public string? Token { get; set; }
public string? TotpCode { get; set; }
}
}
@@ -1,8 +1,8 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.DTOs
namespace SharpbinV3.Server.DTOs.User
{
public class LoginRequest
public class LoginUserDto
{
[StringLength(50, MinimumLength = 3)]
public string? Username { get; set; }
@@ -10,5 +10,6 @@ namespace SharpbinV3.Server.DTOs
[StringLength(128, MinimumLength = 6)]
public string? Password { get; set; }
public string? Token { get; set; }
public string? TotpCode { get; set; }
}
}
@@ -3,7 +3,7 @@ using System.Text.RegularExpressions;
namespace SharpbinV3.Server.DTOs
{
public partial class RegisterRequest
public partial class RegisterUserDto
{
[Required]
[StringLength(50, MinimumLength = 3)]
@@ -3,12 +3,13 @@ using System.Text.RegularExpressions;
namespace SharpbinV3.Server.DTOs
{
public partial class UpdateUserRequest
public partial class UpdateUserDto
{
public string? DisplayName { get; set; }
public string? Email { get; set; }
public int? Visibility { get; set; } = 0;
public int[]? Roles { get; set; }
public string? TotpCode { get; set; }
public IEnumerable<ValidationResult> Validate()
{
+7
View File
@@ -8,6 +8,7 @@ namespace SharpbinV3.Server.Data
public DbSet<User> Users => Set<User>();
public DbSet<Paste> Pastes => Set<Paste>();
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
public DbSet<UserTotp> UserTotps => Set<UserTotp>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
@@ -24,6 +25,12 @@ namespace SharpbinV3.Server.Data
.WithMany(u => u.RefreshTokens)
.HasForeignKey(r => r.UserUUID)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<UserTotp>()
.HasOne(t => t.User)
.WithOne(u => u.Totp)
.HasForeignKey<UserTotp>(t => t.UserUUID)
.OnDelete(DeleteBehavior.Cascade);
}
}
+1
View File
@@ -21,5 +21,6 @@ namespace SharpbinV3.Server.Data.Entities
public int Visibility { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private
public List<Paste> Pastes { get; set; } = [];
public List<RefreshToken> RefreshTokens { get; set; } = [];
public UserTotp? Totp { get; set; }
}
}
@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.Data.Entities
{
public class UserTotp
{
[Key]
public Guid UserUUID { get; set; }
public byte[] EncryptedSecret { get; set; } = null!;
public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
public User User { get; set; } = null!;
}
}
@@ -0,0 +1,68 @@
using SharpbinV3.Server.Services;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
namespace SharpbinV3.Server.Extensions
{
public static class HttpContextExtensions
{
public readonly static string[] ipHeaders =
[
"X-Forwarded-For",
"X-Real-IP",
"CF-Connecting-IP",
"True-Client-IP",
"X-Cluster-Client-IP",
"X-ProxyUser-IP"
];
public static JwtUser? GetJwtUser(this HttpContext context)
{
if (context.User == null || !context.User.Identity?.IsAuthenticated == true)
return null;
var claims = context.User.Claims;
var uuidClaim = claims.FirstOrDefault(c => c.Type == "UUID")?.Value;
if (string.IsNullOrEmpty(uuidClaim) || !Guid.TryParse(uuidClaim, out var uuid))
return null;
var username = claims.FirstOrDefault(c => c.Type == "Username")?.Value ?? "";
var displayName = claims.FirstOrDefault(c => c.Type == "DisplayName")?.Value ?? "";
var totpEnabled = claims.FirstOrDefault(c => c.Type == "TOTP_Enabled")?.Value == "True";
var roles = claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => int.TryParse(c.Value, out var r) ? r : 0)
.ToArray();
var expClaim = claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Exp)?.Value;
var expires = expClaim != null && long.TryParse(expClaim, out var expUnix)
? DateTimeOffset.FromUnixTimeSeconds(expUnix).UtcDateTime
: DateTime.UtcNow.AddMinutes(15);
return new JwtUser
{
UUID = uuid,
Username = username,
DisplayName = displayName,
TotpEnabled = totpEnabled,
Roles = roles.Length > 0 ? roles : [0],
Expires = expires
};
}
public static string GetRequestIP(this HttpContext context)
{
foreach (var header in ipHeaders)
{
if (context.Request.Headers.TryGetValue(header, out Microsoft.Extensions.Primitives.StringValues value))
{
var ip = value.FirstOrDefault();
if (!string.IsNullOrEmpty(ip))
return ip.Split(',')[0].Trim();
}
}
return context.Connection.RemoteIpAddress?.ToString() ?? "Unknown";
}
}
}
@@ -1,5 +1,4 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
@@ -0,0 +1,221 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260107181640_UserTotps")]
partial class UserTotps
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.1");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Property<int>("PID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<Guid?>("AuthorUUID")
.HasColumnType("TEXT");
b.Property<byte[]>("Content")
.IsRequired()
.HasColumnType("BLOB");
b.Property<long?>("EditedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("ID")
.HasColumnType("TEXT");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("Size")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<long>("TrueSize")
.HasColumnType("INTEGER");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int>("Views")
.HasColumnType("INTEGER");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("PID");
b.HasIndex("AuthorUUID");
b.HasIndex("ExpiresAt");
b.HasIndex("ID")
.IsUnique();
b.HasIndex("PID")
.IsUnique();
b.HasIndex("UUID")
.IsUnique();
b.HasIndex("Views");
b.HasIndex("Visibility");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Token")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.HasKey("UserUUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.PrimitiveCollection<string>("Roles")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int?>("UID")
.HasColumnType("INTEGER");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UUID");
b.HasIndex("UID");
b.HasIndex("UUID")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<byte[]>("EncryptedSecret")
.IsRequired()
.HasColumnType("BLOB");
b.HasKey("UserUUID");
b.ToTable("UserTotps");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithOne("Totp")
.HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,40 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class UserTotps : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "UserTotps",
columns: table => new
{
UserUUID = table.Column<Guid>(type: "TEXT", nullable: false),
EncryptedSecret = table.Column<byte[]>(type: "BLOB", nullable: false),
CreatedAt = table.Column<long>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserTotps", x => x.UserUUID);
table.ForeignKey(
name: "FK_UserTotps_Users_UserUUID",
column: x => x.UserUUID,
principalTable: "Users",
principalColumn: "UUID",
onDelete: ReferentialAction.Cascade);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "UserTotps");
}
}
}
@@ -15,7 +15,7 @@ namespace SharpbinV3.Server.Migrations
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.0");
modelBuilder.HasAnnotation("ProductVersion", "10.0.1");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
@@ -155,6 +155,23 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<byte[]>("EncryptedSecret")
.IsRequired()
.HasColumnType("BLOB");
b.HasKey("UserUUID");
b.ToTable("UserTotps");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
@@ -176,11 +193,24 @@ namespace SharpbinV3.Server.Migrations
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithOne("Totp")
.HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
}
+32 -1
View File
@@ -1,7 +1,10 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using SharpbinV3.Server.Authorization;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Services;
using SharpbinV3.Server.Services.Verification;
@@ -33,8 +36,10 @@ namespace SharpbinV3.Server
builder.Services.AddScoped<AuthService>();
builder.Services.AddScoped<PasteService>();
builder.Services.AddScoped<VerificationService>();
builder.Services.AddScoped<TotpVerificationProvider>();
builder.Services.AddHttpClient<IVerificationProvider, TurnstileVerificationProvider>();
builder.Services.AddMemoryCache();
builder.Services.AddHealthChecks()
.AddDbContextCheck<AppDbContext>("Database");
@@ -65,6 +70,14 @@ namespace SharpbinV3.Server
ValidAlgorithms = [SecurityAlgorithms.HmacSha256]
};
});
builder.Services.AddAuthorizationBuilder()
.AddPolicy("NotBanned", policy =>
policy.Requirements.Add(new NotBannedRequirement()));
builder.Services.AddAuthorizationBuilder()
.AddPolicy("AuthAndNotBanned", policy =>
policy.Requirements.Add(new NotBannedRequirement()));
builder.Services.AddSingleton<IAuthorizationHandler>(new NotBannedHandler(false));
builder.Services.AddSingleton<IAuthorizationHandler>(new NotBannedHandler(true));
builder.Services.AddRateLimiter(options =>
@@ -91,6 +104,10 @@ namespace SharpbinV3.Server
builder.Services.Configure<JWTSettings>(builder.Configuration.GetSection("JWTSettings"));
builder.Services.Configure<AuthSettings>(builder.Configuration.GetSection("AuthSettings"));
builder.Services.AddDataProtection()
.PersistKeysToFileSystem(GetDataProtectionKeyDirectory(builder.Environment))
.SetApplicationName("SharpbinV3");
var app = builder.Build();
app.UseRateLimiter();
@@ -130,5 +147,19 @@ namespace SharpbinV3.Server
app.Run();
}
static DirectoryInfo GetDataProtectionKeyDirectory(IHostEnvironment env)
{
var overridepath = Environment.GetEnvironmentVariable("DATA_PROTECTION_KEY_PATH");
if (!string.IsNullOrEmpty(overridepath))
return new DirectoryInfo(overridepath);
var basePath = env.IsDevelopment()
? Environment.CurrentDirectory
: Environment.SpecialFolder.ApplicationData.ToString();
var path = Path.Combine(basePath, "SharpbinV3", "DataProtectionKeys");
return new DirectoryInfo(path);
}
}
}
+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);
}
}
}
+8 -7
View File
@@ -13,20 +13,21 @@
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.0">
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.1" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.0">
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.01" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="10.0.0" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="10.0.1" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
<PackageReference Include="Otp.NET" Version="1.4.1" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.15.0" />
</ItemGroup>
+24
View File
@@ -0,0 +1,24 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.2.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpbinV3.Server", "SharpbinV3.Server.csproj", "{79A5E17C-498C-F55E-C79E-1F32E48383EF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {98CE5484-B4BF-4C6B-9EEC-07F6E621F094}
EndGlobalSection
EndGlobal
-23
View File
@@ -2,34 +2,11 @@
{
public class Utilities
{
public readonly static string[] ipHeaders =
[
"X-Forwarded-For",
"X-Real-IP",
"CF-Connecting-IP",
"True-Client-IP",
"X-Cluster-Client-IP",
"X-ProxyUser-IP"
];
public static string GenerateRandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var random = new Random();
return new string([.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)])]);
}
public static string GetRequestIP(HttpContext request)
{
foreach (var header in ipHeaders)
{
if (request.Request.Headers.TryGetValue(header, out Microsoft.Extensions.Primitives.StringValues value))
{
var ip = value.FirstOrDefault();
if (!string.IsNullOrEmpty(ip))
return ip.Split(',')[0].Trim();
}
}
return request.Connection.RemoteIpAddress?.ToString() ?? "Unknown";
}
}
}