Revert "chore: format via csharpier"

This reverts commit 7a2eb699f4.
This commit is contained in:
2026-01-09 15:24:19 -05:00
parent 7a2eb699f4
commit 6bea6c49be
35 changed files with 464 additions and 784 deletions
+33 -66
View File
@@ -1,13 +1,13 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs.Auth;
using SharpbinV3.Server.Settings;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Bcrypt = BCrypt.Net.BCrypt;
namespace SharpbinV3.Server.Services
@@ -21,23 +21,13 @@ namespace SharpbinV3.Server.Services
public int[] Roles { get; set; } = [];
public DateTime Expires { get; set; }
}
public sealed class AuthService(
AppDbContext db,
IOptions<JWTSettings> jwtOptions,
IOptions<AuthSettings> authOptions
)
public sealed class AuthService(AppDbContext db, IOptions<JWTSettings> jwtOptions, IOptions<AuthSettings> authOptions)
{
private readonly AppDbContext _db = db;
private readonly JWTSettings _jwtSettings = jwtOptions.Value;
private readonly AuthSettings _authSettings = authOptions.Value;
public async Task<User> CreateUser(
string username,
string password,
string? email,
string? displayName
)
public async Task<User> CreateUser(string username, string password, string? email, string? displayName)
{
var user = new User
{
@@ -45,7 +35,7 @@ namespace SharpbinV3.Server.Services
PasswordHash = Bcrypt.HashPassword(password),
Email = email,
DisplayName = displayName,
UUID = Guid.CreateVersion7(),
UUID = Guid.CreateVersion7()
};
if (_authSettings.First_User_Admin && !await _db.Users.AnyAsync())
@@ -55,7 +45,6 @@ namespace SharpbinV3.Server.Services
await _db.SaveChangesAsync();
return user;
}
public async Task<CreateJWT> GenerateJWTToken(User user)
{
var jwtHandler = new JwtSecurityTokenHandler();
@@ -68,7 +57,7 @@ namespace SharpbinV3.Server.Services
new("Username", user.Username),
new("DisplayName", user.DisplayName ?? ""),
new("TOTP_Enabled", totpEnabled.ToString()),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
if (user.Roles != null)
@@ -90,24 +79,20 @@ namespace SharpbinV3.Server.Services
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha256Signature
),
)
};
var token = jwtHandler.CreateToken(descriptor);
var jwtToken = jwtHandler.WriteToken(token);
var existingToken = await _db.RefreshTokens.FirstOrDefaultAsync(rt =>
rt.UserUUID == user.UUID
);
var existingToken = await _db.RefreshTokens.FirstOrDefaultAsync(rt => rt.UserUUID == user.UUID);
if (existingToken != null)
{
existingToken.JwtId = token.Id;
existingToken.Used = false;
existingToken.CreatedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
existingToken.ExpiresAt = DateTimeOffset
.UtcNow.AddMonths(6)
.ToUnixTimeMilliseconds();
existingToken.ExpiresAt = DateTimeOffset.UtcNow.AddMonths(6).ToUnixTimeMilliseconds();
existingToken.Token = Utilities.GenerateRandomString(36) + Guid.NewGuid();
_db.RefreshTokens.Update(existingToken);
}
@@ -121,7 +106,7 @@ namespace SharpbinV3.Server.Services
UserUUID = user.UUID,
CreatedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
ExpiresAt = DateTimeOffset.UtcNow.AddMonths(6).ToUnixTimeMilliseconds(),
Token = Utilities.GenerateRandomString(36) + Guid.NewGuid(),
Token = Utilities.GenerateRandomString(36) + Guid.NewGuid()
};
await _db.RefreshTokens.AddAsync(refreshToken);
}
@@ -132,9 +117,7 @@ namespace SharpbinV3.Server.Services
{
Token = jwtToken,
Success = true,
RefreshToken =
existingToken?.Token
?? (await _db.RefreshTokens.FirstAsync(rt => rt.UserUUID == user.UUID)).Token,
RefreshToken = existingToken?.Token ?? (await _db.RefreshTokens.FirstAsync(rt => rt.UserUUID == user.UUID)).Token
};
}
@@ -144,39 +127,28 @@ namespace SharpbinV3.Server.Services
var key = Encoding.UTF8.GetBytes(_jwtSettings.Secret);
try
{
var principal = jwtHandler.ValidateToken(
token,
new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidIssuer = _jwtSettings.Issuer,
ValidateAudience = true,
ValidAudience = _jwtSettings.Audience,
ClockSkew = TimeSpan.Zero,
ValidateLifetime = false,
RequireSignedTokens = true,
ValidAlgorithms = [SecurityAlgorithms.HmacSha256],
},
out SecurityToken validatedToken
);
var principal = jwtHandler.ValidateToken(token, new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidIssuer = _jwtSettings.Issuer,
ValidateAudience = true,
ValidAudience = _jwtSettings.Audience,
ClockSkew = TimeSpan.Zero,
ValidateLifetime = false,
RequireSignedTokens = true,
ValidAlgorithms = [SecurityAlgorithms.HmacSha256]
}, out SecurityToken validatedToken);
var jwtId = validatedToken.Id;
var storedRefreshToken = await _db.RefreshTokens.FirstOrDefaultAsync(rt =>
rt.Token == refreshToken
);
if (
storedRefreshToken == null
var storedRefreshToken = await _db.RefreshTokens
.FirstOrDefaultAsync(rt => rt.Token == refreshToken);
if (storedRefreshToken == null
|| storedRefreshToken.Used
|| storedRefreshToken.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
|| storedRefreshToken.JwtId != jwtId
)
|| storedRefreshToken.JwtId != jwtId)
{
return new CreateJWT()
{
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();
@@ -195,9 +167,7 @@ namespace SharpbinV3.Server.Services
public async Task<User> UpdateUser(User user)
{
var existingUser =
await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID)
?? throw new Exception("User not found");
var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found");
existingUser.Username = user.Username;
existingUser.Email = user.Email;
existingUser.DisplayName = user.DisplayName;
@@ -208,12 +178,9 @@ namespace SharpbinV3.Server.Services
await _db.SaveChangesAsync();
return user;
}
public async Task UpdateLoginTime(User user)
{
var existingUser =
await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID)
?? throw new Exception("User not found");
var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found");
existingUser.LastLogin = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
_db.Users.Update(existingUser);
await _db.SaveChangesAsync();
@@ -1,5 +1,6 @@
using System.IO.Compression;
namespace SharpbinV3.Server.Services
{
public class CompressionService : ICompressionService
@@ -20,21 +21,16 @@ namespace SharpbinV3.Server.Services
return data;
}
public byte[] Compress(string data)
{
ArgumentNullException.ThrowIfNull(data);
return Compress(System.Text.Encoding.UTF8.GetBytes(data));
}
public byte[] Decompress(byte[] compressedData)
{
ArgumentNullException.ThrowIfNull(compressedData);
if (!IsCompressed(compressedData))
throw new ArgumentException(
"Data is not in a valid compressed format.",
nameof(compressedData)
);
throw new ArgumentException("Data is not in a valid compressed format.", nameof(compressedData));
using (MemoryStream ms = new())
{
@@ -3,21 +3,14 @@ using SharpbinV3.Server.Data;
namespace SharpbinV3.Server.Services
{
public class PasteCleanUpService(
IServiceProvider serviceProvider,
ILogger<PasteCleanUpService> logger
) : BackgroundService
public class PasteCleanUpService(IServiceProvider serviceProvider, ILogger<PasteCleanUpService> logger) : BackgroundService
{
private readonly TimeSpan _period = TimeSpan.FromMinutes(5);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(_period);
await Cleanup(stoppingToken);
while (
!stoppingToken.IsCancellationRequested
&& await timer.WaitForNextTickAsync(stoppingToken)
)
while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
@@ -43,6 +36,7 @@ namespace SharpbinV3.Server.Services
await db.SaveChangesAsync(stoppingToken);
logger.LogInformation("Deleted {Count} expired pastes", deletedCount);
}
}
}
}
+10 -28
View File
@@ -1,31 +1,19 @@
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Settings;
using System.Text;
namespace SharpbinV3.Server.Services
{
public sealed class PasteService(
AppDbContext db,
ICompressionService cs,
IOptions<PasteSettings> options
)
public sealed class PasteService(AppDbContext db, ICompressionService cs, IOptions<PasteSettings> options)
{
private readonly AppDbContext _db = db;
private readonly ICompressionService _cs = cs;
private readonly PasteSettings _pasteSettings = options.Value;
public async Task<Paste> Create(
User? author,
string content,
string title,
string syntax,
int visibility,
long expiresAt,
bool shouldCompress
)
public async Task<Paste> Create(User? author, string content, string title, string syntax, int visibility, long expiresAt, bool shouldCompress)
{
var data = Encoding.UTF8.GetBytes(content);
if (shouldCompress)
@@ -62,24 +50,20 @@ namespace SharpbinV3.Server.Services
var result = await _db.SaveChangesAsync();
return result > 0;
}
public async Task<Paste> Edit(Paste paste)
{
_db.Pastes.Update(paste);
await _db.SaveChangesAsync();
return paste;
}
public async Task<bool> Exists(string id)
{
return await _db.Pastes.AnyAsync(p => p.ID == id);
}
public async Task<bool> Exists(Guid uuid)
{
return await _db.Pastes.AnyAsync(p => p.UUID == uuid);
}
public async Task<bool> EditText(Paste paste, string text)
{
var data = Encoding.UTF8.GetBytes(text);
@@ -95,41 +79,39 @@ namespace SharpbinV3.Server.Services
var result = await _db.SaveChangesAsync();
return result > 0;
}
public async Task<Paste?> Get(string id)
{
var paste = await _db.Pastes.Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id);
return paste ?? null;
}
public async Task<List<Paste>> GetList(int offset, int count, bool publicOnly = false)
{
var query = _db.Pastes.AsQueryable();
if (publicOnly)
query = query.Where(p => p.Visibility == 0);
return await query.OrderByDescending(p => p.PID).Skip(offset).Take(count).ToListAsync();
return await query
.OrderByDescending(p => p.PID)
.Skip(offset)
.Take(count)
.ToListAsync();
}
public async Task<bool> ValidateSyntax(string syntax)
{
return await Task.FromResult(_pasteSettings.ValidSyntaxLanguages.Contains(syntax));
}
public async Task<bool> ValidateTitle(string title)
{
return await Task.FromResult(title.Length <= _pasteSettings.MaxTitleLength);
}
public async Task<bool> ValidateVisibility(int visibility)
{
return await Task.FromResult(visibility >= 0 && visibility <= 2);
}
public async Task<bool> ValidateExpiresAt(long expiresAt)
{
if (expiresAt == 0)
return true;
if (expiresAt == 0) return true;
var currentTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
return await Task.FromResult(expiresAt > currentTime - 1000);
}
+1 -1
View File
@@ -2,12 +2,12 @@
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
namespace SharpbinV3.Server.Services
{
public sealed class UserService(AppDbContext db)
{
private readonly AppDbContext _db = db;
public Task<User?> GetByUID(int uid, bool withPastes = false)
{
IQueryable<User> query = _db.Users;
@@ -12,11 +12,7 @@ namespace SharpbinV3.Server.Services.Verification.Providers
private readonly IDataProtector _protector;
private readonly IMemoryCache _cache;
public TotpVerificationProvider(
AppDbContext db,
IDataProtectionProvider dataProtectionProvider,
IMemoryCache cache
)
public TotpVerificationProvider(AppDbContext db, IDataProtectionProvider dataProtectionProvider, IMemoryCache cache)
{
_db = db;
_protector = dataProtectionProvider.CreateProtector("TotpSecret-v1");
@@ -28,16 +24,11 @@ namespace SharpbinV3.Server.Services.Verification.Providers
public async Task<bool> VerifyAsync(VerificationContext ctx)
{
if (ctx.UserUUID is null)
return false;
if (string.IsNullOrWhiteSpace(ctx.Code))
return false;
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 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))
@@ -53,58 +44,30 @@ namespace SharpbinV3.Server.Services.Verification.Providers
public string ToBase32(byte[] data) => Base32Encoding.ToString(data);
public byte[] FromBase32(string base32) =>
string.IsNullOrWhiteSpace(base32) ? [] : Base32Encoding.ToBytes(base32);
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"
)
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}";
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
)
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
)
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)
);
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);
private string ComputeCode(byte[] key, long timestep, int digits) => new Totp(key, totpSize: digits).ComputeTotp(DateTime.UtcNow);
}
}
@@ -1,23 +1,17 @@
using System.Text.Json;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.DTOs.Auth;
using SharpbinV3.Server.Settings;
using System.Text.Json;
namespace SharpbinV3.Server.Services.Verification.Providers
{
public sealed class TurnstileVerificationProvider(
IOptions<AuthSettings> options,
HttpClient httpClient
) : IVerificationProvider
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";
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 bool IsConfigured => !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SecretKey) && !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SiteKey);
public async Task<bool> VerifyAsync(VerificationContext ctx)
{
@@ -29,7 +23,7 @@ namespace SharpbinV3.Server.Services.Verification.Providers
var parameters = new Dictionary<string, string>
{
{ "secret", _authSettings.CF_Turnstile_SecretKey },
{ "response", ctx.Token },
{ "response", ctx.Token }
};
if (!string.IsNullOrEmpty(ctx.Ip))
@@ -8,4 +8,5 @@
public Guid? UserUUID { get; init; }
public string? Code { get; init; }
}
}
@@ -14,10 +14,7 @@ namespace SharpbinV3.Server.Services.Verification
.FirstOrDefault();
}
public async Task<bool> VerifyAsync(
VerificationContext context,
IVerificationProvider? provider = null
)
public async Task<bool> VerifyAsync(VerificationContext context, IVerificationProvider? provider = null)
{
var activeProvider = provider ?? GetActiveProvider();