feat: implement Turnstile verification for enhanced security during login and registration

refactor: remove unnecessary interfaces for services; change user key from UID to UUID
This commit is contained in:
2025-12-31 12:11:09 -05:00
parent 08c4be4f7e
commit 848b8598e5
27 changed files with 579 additions and 84 deletions
@@ -1,24 +1,31 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.Services;
using SharpbinV3.Server.Services.Verification;
using SharpbinV3.Server.Settings;
using Bcrypt = BCrypt.Net.BCrypt;
namespace SharpbinV3.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class AuthController(IUserService userService, IAuthService authService) : ControllerBase
public class AuthController(UserService userService, AuthService authService, IOptions<AuthSettings> options, VerificationService verification) : ControllerBase
{
private readonly IAuthService _authService = authService;
private readonly IUserService _userService = userService;
private readonly AuthService _authService = authService;
private readonly UserService _userService = userService;
private readonly VerificationService _verification = verification;
[HttpPost]
[EnableRateLimiting("Sliding")]
[Route("register")]
public async Task<IActionResult> Register([FromBody] RegisterRequest request)
{
if (!await _verification.VerifyAsync(request.Token, Utilities.GetRequestIP(HttpContext)))
return BadRequest(new { message = "Verification failed." });
var existingUser = await _userService.GetByUsername(request.Username);
if (existingUser != null)
return Conflict(new { message = "Username already exists." });
@@ -51,6 +58,7 @@ namespace SharpbinV3.Server.Controllers
}
);
}
[HttpPost]
[Route("login")]
[EnableRateLimiting("Sliding")]
@@ -59,6 +67,9 @@ namespace SharpbinV3.Server.Controllers
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)))
return BadRequest(new { message = "Verification failed." });
User? user = null;
if (!string.IsNullOrEmpty(request.Username))
user = await _userService.GetByUsername(request.Username);
@@ -88,6 +99,17 @@ namespace SharpbinV3.Server.Controllers
}
}
[HttpGet]
[Route("info")]
public async Task<IActionResult> GetSiteInfo()
{
var authSettings = options.Value;
return Ok(new
{
cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey) ? null : authSettings.CF_Turnstile_SiteKey
});
}
private static bool IsValidPassword(string password)
{
@@ -11,10 +11,10 @@ namespace SharpbinV3.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PasteController(IPasteService pasteService, IUserService userService, IOptions<PasteSettings> options) : ControllerBase
public class PasteController(PasteService pasteService, UserService userService, IOptions<PasteSettings> options) : ControllerBase
{
private readonly IPasteService _pasteService = pasteService;
private readonly IUserService _userService = userService;
private readonly PasteService _pasteService = pasteService;
private readonly UserService _userService = userService;
private readonly PasteSettings _pasteSettings = options.Value;
[HttpPost]
@@ -11,9 +11,9 @@ namespace SharpbinV3.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UserController(IUserService userService, AppDbContext db) : ControllerBase
public class UserController(UserService userService, AppDbContext db) : ControllerBase
{
private readonly IUserService _userService = userService;
private readonly UserService _userService = userService;
private readonly AppDbContext _db = db;
[HttpGet("{username}")]
+1
View File
@@ -9,5 +9,6 @@ namespace SharpbinV3.Server.DTOs
public string? Email { get; set; }
[StringLength(128, MinimumLength = 6)]
public string? Password { get; set; }
public string? Token { get; set; }
}
}
@@ -15,5 +15,6 @@ namespace SharpbinV3.Server.DTOs
public string? Email { get; set; }
public string? DisplayName { get; set; }
public string? Token { get; set; }
}
}
@@ -0,0 +1,12 @@
using System.Text.Json.Serialization;
namespace SharpbinV3.Server.DTOs
{
public class TurnstileResponse
{
[JsonPropertyName("success")]
public bool Success { get; set; }
[JsonPropertyName("error-codes")]
public string[]? ErrorCodes { get; set; }
}
}
+18
View File
@@ -8,5 +8,23 @@ namespace SharpbinV3.Server.Data
public DbSet<User> Users => Set<User>();
public DbSet<Paste> Pastes => Set<Paste>();
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Paste>()
.HasOne(p => p.User)
.WithMany(u => u.Pastes)
.HasForeignKey(p => p.AuthorUUID)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<RefreshToken>()
.HasOne(r => r.User)
.WithMany(u => u.RefreshTokens)
.HasForeignKey(r => r.UserUUID)
.OnDelete(DeleteBehavior.Cascade);
}
}
}
+4 -1
View File
@@ -6,16 +6,19 @@ namespace SharpbinV3.Server.Data.Entities
[Index(nameof(UUID), IsUnique = true)]
public sealed class User
{
[Key]
public int UID { get; set; }
[Key]
public required Guid UUID { get; set; } = Guid.CreateVersion7(); // uuid v7 includes timestamp
public required string Username { get; set; }
public required string PasswordHash { get; set; }
public string? Email { get; set; }
public string? DisplayName { get; set; }
public long? LastLogin { get; set; }
public int[] Roles { get; set; } = [0]; // 0 = regular user, 1 = moderator, 255 = admin
public int Visibility { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private
public List<Paste> Pastes { get; set; } = [];
public List<RefreshToken> RefreshTokens { get; set; } = [];
}
}
@@ -0,0 +1,190 @@
// <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("20251231161600_UserUUIDKey")]
partial class UserUUIDKey
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.0");
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("UUID")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
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.User", b =>
{
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,138 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class UserUUIDKey : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Pastes_Users_UserUID",
table: "Pastes");
migrationBuilder.DropForeignKey(
name: "FK_RefreshTokens_Users_UserUID",
table: "RefreshTokens");
migrationBuilder.DropPrimaryKey(
name: "PK_Users",
table: "Users");
migrationBuilder.DropIndex(
name: "IX_RefreshTokens_UserUID",
table: "RefreshTokens");
migrationBuilder.DropIndex(
name: "IX_Pastes_UserUID",
table: "Pastes");
migrationBuilder.DropColumn(
name: "UserUID",
table: "RefreshTokens");
migrationBuilder.DropColumn(
name: "UserUID",
table: "Pastes");
migrationBuilder.AlterColumn<int>(
name: "UID",
table: "Users",
type: "INTEGER",
nullable: false,
oldClrType: typeof(int),
oldType: "INTEGER")
.OldAnnotation("Sqlite:Autoincrement", true);
migrationBuilder.AddPrimaryKey(
name: "PK_Users",
table: "Users",
column: "UUID");
migrationBuilder.AddForeignKey(
name: "FK_Pastes_Users_AuthorUUID",
table: "Pastes",
column: "AuthorUUID",
principalTable: "Users",
principalColumn: "UUID",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_RefreshTokens_Users_UserUUID",
table: "RefreshTokens",
column: "UserUUID",
principalTable: "Users",
principalColumn: "UUID",
onDelete: ReferentialAction.Cascade);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Pastes_Users_AuthorUUID",
table: "Pastes");
migrationBuilder.DropForeignKey(
name: "FK_RefreshTokens_Users_UserUUID",
table: "RefreshTokens");
migrationBuilder.DropPrimaryKey(
name: "PK_Users",
table: "Users");
migrationBuilder.AlterColumn<int>(
name: "UID",
table: "Users",
type: "INTEGER",
nullable: false,
oldClrType: typeof(int),
oldType: "INTEGER")
.Annotation("Sqlite:Autoincrement", true);
migrationBuilder.AddColumn<int>(
name: "UserUID",
table: "RefreshTokens",
type: "INTEGER",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "UserUID",
table: "Pastes",
type: "INTEGER",
nullable: true);
migrationBuilder.AddPrimaryKey(
name: "PK_Users",
table: "Users",
column: "UID");
migrationBuilder.CreateIndex(
name: "IX_RefreshTokens_UserUID",
table: "RefreshTokens",
column: "UserUID");
migrationBuilder.CreateIndex(
name: "IX_Pastes_UserUID",
table: "Pastes",
column: "UserUID");
migrationBuilder.AddForeignKey(
name: "FK_Pastes_Users_UserUID",
table: "Pastes",
column: "UserUID",
principalTable: "Users",
principalColumn: "UID");
migrationBuilder.AddForeignKey(
name: "FK_RefreshTokens_Users_UserUID",
table: "RefreshTokens",
column: "UserUID",
principalTable: "Users",
principalColumn: "UID");
}
}
}
@@ -57,9 +57,6 @@ namespace SharpbinV3.Server.Migrations
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int?>("UserUID")
.HasColumnType("INTEGER");
b.Property<int>("Views")
.HasColumnType("INTEGER");
@@ -81,8 +78,6 @@ namespace SharpbinV3.Server.Migrations
b.HasIndex("UUID")
.IsUnique();
b.HasIndex("UserUID");
b.HasIndex("Views");
b.HasIndex("Visibility");
@@ -93,7 +88,6 @@ namespace SharpbinV3.Server.Migrations
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("UserUUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
@@ -113,21 +107,16 @@ namespace SharpbinV3.Server.Migrations
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<int?>("UserUID")
.HasColumnType("INTEGER");
b.HasKey("UserUUID");
b.HasIndex("UserUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<int>("UID")
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
.HasColumnType("TEXT");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
@@ -146,8 +135,8 @@ namespace SharpbinV3.Server.Migrations
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int>("UID")
.HasColumnType("INTEGER");
b.Property<string>("Username")
.IsRequired()
@@ -156,7 +145,7 @@ namespace SharpbinV3.Server.Migrations
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UID");
b.HasKey("UUID");
b.HasIndex("UUID")
.IsUnique();
@@ -168,7 +157,9 @@ namespace SharpbinV3.Server.Migrations
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("UserUID");
.HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
@@ -176,8 +167,10 @@ namespace SharpbinV3.Server.Migrations
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany()
.HasForeignKey("UserUID");
.WithMany("RefreshTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
@@ -185,6 +178,8 @@ namespace SharpbinV3.Server.Migrations
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
});
#pragma warning restore 612, 618
}
+8 -3
View File
@@ -4,6 +4,8 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Services;
using SharpbinV3.Server.Services.Verification;
using SharpbinV3.Server.Services.Verification.Providers;
using SharpbinV3.Server.Settings;
using System.Text;
using System.Threading.RateLimiting;
@@ -27,9 +29,11 @@ namespace SharpbinV3.Server
});
builder.Services.AddSingleton<ICompressionService, CompressionService>();
builder.Services.AddSingleton<IHostedService, PasteCleanUpService>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IPasteService, PasteService>();
builder.Services.AddScoped<UserService>();
builder.Services.AddScoped<AuthService>();
builder.Services.AddScoped<PasteService>();
builder.Services.AddScoped<VerificationService>();
builder.Services.AddHttpClient<IVerificationProvider, TurnstileVerificationProvider>();
builder.Services.AddHealthChecks()
.AddDbContextCheck<AppDbContext>("Database");
@@ -85,6 +89,7 @@ namespace SharpbinV3.Server
});
builder.Services.Configure<PasteSettings>(builder.Configuration.GetSection("PasteSettings"));
builder.Services.Configure<JWTSettings>(builder.Configuration.GetSection("JWTSettings"));
builder.Services.Configure<AuthSettings>(builder.Configuration.GetSection("AuthSettings"));
var app = builder.Build();
app.UseRateLimiter();
+1 -1
View File
@@ -12,7 +12,7 @@ using Bcrypt = BCrypt.Net.BCrypt;
namespace SharpbinV3.Server.Services
{
public sealed class AuthService(AppDbContext db, IOptions<JWTSettings> options) : IAuthService
public sealed class AuthService(AppDbContext db, IOptions<JWTSettings> options)
{
private readonly AppDbContext _db = db;
private readonly JWTSettings _jwtSettings = options.Value;
@@ -1,14 +0,0 @@
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
namespace SharpbinV3.Server.Services
{
public interface IAuthService
{
Task<User> CreateUser(string username, string password, string? email, string? displayName);
Task<JWTResult> GenerateJWTToken(User user);
Task<JWTResult> RefreshJWTToken(string token, string refreshToken);
Task<User> UpdateUser(User user);
Task UpdateLoginTime(User user);
}
}
@@ -1,20 +0,0 @@
using SharpbinV3.Server.Data.Entities;
namespace SharpbinV3.Server.Services
{
public interface IPasteService
{
Task<Paste> Create(User? author, string content, string title, string syntax, int visibility, long expiresAt);
Task<bool> Delete(Paste paste);
Task<Paste> Edit(Paste paste);
Task<bool> Exists(string id);
Task<bool> Exists(Guid uuid);
Task<bool> EditText(Paste paste, string text);
Task<Paste?> Get(string id);
Task<List<Paste>> GetList(int offset, int count, bool publicOnly = false);
Task<bool> ValidateSyntax(string syntax);
Task<bool> ValidateTitle(string title);
Task<bool> ValidateVisibility(int visibility);
Task<bool> ValidateExpiresAt(long expiresAt);
}
}
@@ -1,13 +0,0 @@
using SharpbinV3.Server.Data.Entities;
namespace SharpbinV3.Server.Services
{
public interface IUserService
{
Task<User?> GetByUID(int uid, bool withPastes = false);
Task<User?> GetByUsername(string username, bool withPastes = false);
Task<User?> GetByUUID(Guid uuid, bool withPastes = false);
Task<User?> GetByEmail(string email, bool withPastes = false);
Task<User> Update(User user);
}
}
+1 -1
View File
@@ -7,7 +7,7 @@ using System.Text;
namespace SharpbinV3.Server.Services
{
public sealed class PasteService(AppDbContext db, ICompressionService cs, IOptions<PasteSettings> options) : IPasteService
public sealed class PasteService(AppDbContext db, ICompressionService cs, IOptions<PasteSettings> options)
{
private readonly AppDbContext _db = db;
private readonly ICompressionService _cs = cs;
+1 -1
View File
@@ -5,7 +5,7 @@ using SharpbinV3.Server.Data.Entities;
namespace SharpbinV3.Server.Services
{
public sealed class UserService(AppDbContext db) : IUserService
public sealed class UserService(AppDbContext db)
{
private readonly AppDbContext _db = db;
public Task<User?> GetByUID(int uid, bool withPastes = false)
@@ -0,0 +1,9 @@
namespace SharpbinV3.Server.Services.Verification.Providers
{
public interface IVerificationProvider
{
int Priority { get; }
bool IsConfigured { get; }
Task<bool> VerifyAsync(string token, string? ip);
}
}
@@ -0,0 +1,39 @@
using Microsoft.Extensions.Options;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.Settings;
using System.Text.Json;
namespace SharpbinV3.Server.Services.Verification.Providers
{
public sealed class TurnstileVerificationProvider(IOptions<AuthSettings> options, HttpClient httpClient) : IVerificationProvider
{
private readonly AuthSettings _authSettings = options.Value;
private const string SiteverifyUrl = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
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)
{
if (_authSettings.CF_Turnstile_SecretKey is null)
throw new InvalidOperationException("Turnstile secret key is not configured.");
var parameters = new Dictionary<string, string>
{
{ "secret", _authSettings.CF_Turnstile_SecretKey },
{ "response", token }
};
if (!string.IsNullOrEmpty(ip))
parameters.Add("remoteip", 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);
return result?.Success ?? false;
}
}
}
@@ -0,0 +1,31 @@
using SharpbinV3.Server.Services.Verification.Providers;
namespace SharpbinV3.Server.Services.Verification
{
public sealed class VerificationService(IEnumerable<IVerificationProvider> providers)
{
private readonly IReadOnlyList<IVerificationProvider> _providers = [.. providers];
private IVerificationProvider? GetActiveProvider()
{
return _providers
.Where(p => p.IsConfigured)
.OrderByDescending(p => p.Priority)
.FirstOrDefault();
}
public async Task<bool> VerifyAsync(string? token, string? ip)
{
var provider = GetActiveProvider();
if (provider is null)
return true;
if (string.IsNullOrWhiteSpace(token))
return false;
return await provider.VerifyAsync(token, ip);
}
}
}
@@ -0,0 +1,8 @@
namespace SharpbinV3.Server.Settings
{
public class AuthSettings
{
public string CF_Turnstile_SiteKey { get; set; } = string.Empty;
public string CF_Turnstile_SecretKey { get; set; } = string.Empty;
}
}
+23
View File
@@ -2,11 +2,34 @@
{
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";
}
}
}
@@ -5,6 +5,10 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AuthSettings": {
"CF_Turnstile_SiteKey": "3x00000000000000000000FF",
"CF_Turnstile_SecretKey": "1x0000000000000000000000000000000AA"
},
"JwtSettings": {
"Secret": "ad277c181e51d2131017abc53a5805ccb85410ab902d2e1e09266304e4e86d6c38f2b2543b708d678dfdbfb76016dcf568925ddb25dc91638a69e479e31a23c9",
"Issuer": "SharpbinApi",