chore: format via csharpier

This commit is contained in:
2026-01-09 15:13:57 -05:00
parent 284c5e927e
commit 7a2eb699f4
35 changed files with 784 additions and 464 deletions
+66 -33
View File
@@ -1,13 +1,13 @@
using Microsoft.EntityFrameworkCore;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
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,13 +21,23 @@ 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
{
@@ -35,7 +45,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())
@@ -45,6 +55,7 @@ namespace SharpbinV3.Server.Services
await _db.SaveChangesAsync();
return user;
}
public async Task<CreateJWT> GenerateJWTToken(User user)
{
var jwtHandler = new JwtSecurityTokenHandler();
@@ -57,7 +68,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)
@@ -79,20 +90,24 @@ 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);
}
@@ -106,7 +121,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);
}
@@ -117,7 +132,9 @@ 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,
};
}
@@ -127,28 +144,39 @@ 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();
@@ -167,7 +195,9 @@ 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;
@@ -178,9 +208,12 @@ 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,6 +1,5 @@
using System.IO.Compression;
namespace SharpbinV3.Server.Services
{
public class CompressionService : ICompressionService
@@ -21,16 +20,21 @@ 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,14 +3,21 @@ 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
{
@@ -36,7 +43,6 @@ namespace SharpbinV3.Server.Services
await db.SaveChangesAsync(stoppingToken);
logger.LogInformation("Deleted {Count} expired pastes", deletedCount);
}
}
}
}
+28 -10
View File
@@ -1,19 +1,31 @@
using Microsoft.EntityFrameworkCore;
using System.Text;
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)
@@ -50,20 +62,24 @@ 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);
@@ -79,39 +95,41 @@ 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,7 +12,11 @@ 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");
@@ -24,11 +28,16 @@ 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))
@@ -44,30 +53,58 @@ 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,17 +1,23 @@
using Microsoft.Extensions.Options;
using System.Text.Json;
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)
{
@@ -23,7 +29,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,5 +8,4 @@
public Guid? UserUUID { get; init; }
public string? Code { get; init; }
}
}
@@ -14,7 +14,10 @@ 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();