chore(codebase): full cleanup pass

This commit is contained in:
2025-06-21 01:58:48 -04:00
parent 8323477cd0
commit 81b5db34ef
92 changed files with 529 additions and 452 deletions

View File

@@ -112,7 +112,7 @@ csharp_style_conditional_delegate_call = true:suggestion
# Modifier preferences
csharp_prefer_static_local_function = true:warning
csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:silent
csharp_preferred_modifier_order = public, private, protected, internal, static, extern, new, virtual, abstract, sealed, override, readonly, unsafe, volatile, async:silent
# Code-block preferences
csharp_prefer_braces = true:silent

View File

@@ -1,5 +1,6 @@
using System.Text;
using Hutopy.Modules.Identity.Data;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Facebook;
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Authentication.JwtBearer;
@@ -33,14 +34,14 @@ public static class DependencyInjection
public static IServiceCollection AddAuthorizationAndAuthentication(this IServiceCollection services,
ConfigurationManager configuration)
{
var authenticationBuilder = services
AuthenticationBuilder authenticationBuilder = services
.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
});
var authJwt = configuration.GetSection("Authentication:Jwt");
IConfigurationSection authJwt = configuration.GetSection("Authentication:Jwt");
if (authJwt.Exists())
{
authenticationBuilder.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, jwtBearerOptions =>
@@ -59,7 +60,7 @@ public static class DependencyInjection
});
}
var authGoogle = configuration.GetSection("Authentication:Google");
IConfigurationSection authGoogle = configuration.GetSection("Authentication:Google");
if (authGoogle.Exists())
{
authenticationBuilder.AddGoogle(GoogleDefaults.AuthenticationScheme, options =>
@@ -71,7 +72,7 @@ public static class DependencyInjection
});
}
var authFacebook = configuration.GetSection("Authentication:Facebook");
IConfigurationSection authFacebook = configuration.GetSection("Authentication:Facebook");
if (authFacebook.Exists())
{
authenticationBuilder.AddFacebook(FacebookDefaults.AuthenticationScheme, options =>

View File

@@ -1,2 +1,5 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<wpf:ResourceDictionary xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:System;assembly=mscorlib"
xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xml:space="preserve">
<s:Boolean x:Key="/Default/UserDictionary/Words/=hutopy/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

View File

@@ -10,38 +10,38 @@
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<WarningsAsErrors />
<WarningsAsErrors/>
<CodeAnalysisRuleSet>analyzers.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.Storage.Blobs" Version="12.24.0" />
<PackageReference Include="Azure.Extensions.AspNetCore.Configuration.Secrets" Version="1.4.0" />
<PackageReference Include="Azure.Identity" Version="1.13.2" />
<PackageReference Include="FastEndpoints" Version="5.35.0" />
<PackageReference Include="JetBrains.Annotations" Version="2024.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Facebook" Version="9.0.6" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="9.0.6" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.6" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="9.0.6" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="9.0.6" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.6" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="9.0.6" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
<PackageReference Include="NSwag.AspNetCore" Version="14.3.0" />
<PackageReference Include="Azure.Storage.Blobs" Version="12.24.0"/>
<PackageReference Include="Azure.Extensions.AspNetCore.Configuration.Secrets" Version="1.4.0"/>
<PackageReference Include="Azure.Identity" Version="1.13.2"/>
<PackageReference Include="FastEndpoints" Version="5.35.0"/>
<PackageReference Include="JetBrains.Annotations" Version="2024.3.0"/>
<PackageReference Include="Microsoft.AspNetCore.Authentication.Facebook" Version="9.0.6"/>
<PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="9.0.6"/>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.6"/>
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="9.0.6"/>
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="9.0.6"/>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.6"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.6"/>
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="9.0.6"/>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4"/>
<PackageReference Include="NSwag.AspNetCore" Version="14.3.0"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.6">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.0" />
<PackageReference Include="Postmark" Version="5.2.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.8" />
<PackageReference Include="Stripe.net" Version="47.4.0" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="4.14.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="9.0.0" PrivateAssets="all" />
<PackageReference Include="SonarAnalyzer.CSharp" Version="10.12.0.118525" PrivateAssets="all" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507" PrivateAssets="all" />
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.0"/>
<PackageReference Include="Postmark" Version="5.2.0"/>
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.8"/>
<PackageReference Include="Stripe.net" Version="47.4.0"/>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="4.14.0" PrivateAssets="all"/>
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="9.0.0" PrivateAssets="all"/>
<PackageReference Include="SonarAnalyzer.CSharp" Version="10.12.0.118525" PrivateAssets="all"/>
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507" PrivateAssets="all"/>
</ItemGroup>

View File

@@ -1,6 +1,6 @@
namespace Hutopy.Infrastructure.BlobStorage.Contracts;
public static class ContainerNames
internal static class ContainerNames
{
public const string Users = "users";
public const string Creators = "creators";

View File

@@ -3,7 +3,7 @@ namespace Hutopy.Infrastructure.BlobStorage.Contracts;
public interface IBlobStorage
{
/// <summary>
/// Upload a file to blob storage.
/// Upload a file to blob storage.
/// </summary>
/// <param name="containerName">The name of the container where the file is stored.</param>
/// <param name="blobName">The blob name (path within the container, include the file name).</param>
@@ -19,7 +19,7 @@ public interface IBlobStorage
CancellationToken ct = default);
/// <summary>
/// Download a file to blob storage.
/// Download a file to blob storage.
/// </summary>
/// <param name="blobName">The blob name (path within the container).</param>
/// <param name="containerName">The name of the container where the file is stored. (users)</param>

View File

@@ -15,12 +15,12 @@ public class AzureBlobStorage : IBlobStorage
public AzureBlobStorage(IConfiguration configuration, ILogger<AzureBlobStorage> logger)
{
_logger = logger;
var connectionString = configuration.GetConnectionString("AzureBlob");
string? connectionString = configuration.GetConnectionString("AzureBlob");
_blobServiceClient = new BlobServiceClient(connectionString);
}
/// <summary>
/// Upload a file to microsoft azure blob storage.
/// Upload a file to microsoft azure blob storage.
/// </summary>
/// <param name="containerName">The name of the container where the file is stored.</param>
/// <param name="blobName">The blob name (path within the container, include the file name).</param>
@@ -59,7 +59,7 @@ public class AzureBlobStorage : IBlobStorage
try
{
// Get a reference to a container
var containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
BlobContainerClient? containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
// Create the container if it does not exist
await containerClient.CreateIfNotExistsAsync(
@@ -67,18 +67,18 @@ public class AzureBlobStorage : IBlobStorage
cancellationToken: ct);
// Get a reference to a blob
var blobClient = containerClient.GetBlobClient(blobName);
BlobClient? blobClient = containerClient.GetBlobClient(blobName);
// Define the BlobHttpHeaders to include the content type
var blobHttpHeaders = new BlobHttpHeaders { ContentType = contentType };
BlobHttpHeaders blobHttpHeaders = new() { ContentType = contentType };
// Upload the file
var response = await blobClient.UploadAsync(
Response<BlobContentInfo>? response = await blobClient.UploadAsync(
stream,
new BlobUploadOptions { HttpHeaders = blobHttpHeaders },
ct);
var fileUri = blobClient.Uri.ToString();
string fileUri = blobClient.Uri.ToString();
_logger.LogInformation(
"""
@@ -112,7 +112,7 @@ public class AzureBlobStorage : IBlobStorage
}
/// <summary>
/// Download a file to microsoft's azure blob storage.
/// Download a file to microsoft's azure blob storage.
/// </summary>
/// <param name="blobName">The blob name (path within the container).</param>
/// <param name="containerName">The name of the container where the file is stored. (users)</param>
@@ -126,10 +126,10 @@ public class AzureBlobStorage : IBlobStorage
try
{
// Get a reference to a container
var containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
BlobContainerClient? containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
// Get a reference to a blob
var blobClient = containerClient.GetBlobClient(blobName);
BlobClient? blobClient = containerClient.GetBlobClient(blobName);
// Download the blob to a stream
BlobDownloadInfo download = await blobClient.DownloadAsync(ct);

View File

@@ -9,7 +9,7 @@ namespace Hutopy.Infrastructure.Payments.Stripe.Services;
public class MembershipPaymentProcessor(
IOptions<StripeOptions> stripeOptions)
: IMembershipPaymentProcessor
: IMembershipPaymentProcessor
{
public async Task<MembershipCheckoutSession> CreateCheckoutSessionAsync(
Guid userId,
@@ -22,16 +22,16 @@ public class MembershipPaymentProcessor(
StripeConfiguration.ApiKey = stripeOptions.Value.SecretKey;
// Create Stripe customer for the user if not already created
var customerService = new CustomerService();
var customer = await customerService.CreateAsync(
CustomerService customerService = new();
Customer? customer = await customerService.CreateAsync(
new CustomerCreateOptions
{
Metadata = new Dictionary<string, string> { { "userId", userId.ToString() } }
});
// Create Checkout Session for the subscription
var sessionService = new SessionService();
var session = await sessionService.CreateAsync(
SessionService sessionService = new();
Session? session = await sessionService.CreateAsync(
new SessionCreateOptions
{
Customer = customer.Id,
@@ -44,7 +44,11 @@ public class MembershipPaymentProcessor(
SubscriptionData = new SessionSubscriptionDataOptions
{
ApplicationFeePercent = stripeOptions.Value.HutopyRate,
TransferData = new SessionSubscriptionDataTransferDataOptions { Destination = creatorReference.StripeAccountId }
TransferData =
new SessionSubscriptionDataTransferDataOptions
{
Destination = creatorReference.StripeAccountId
}
},
SuccessUrl = successUrl, // Redirect after successful payment
CancelUrl = cancelUrl, // Redirect after canceled payment
@@ -61,5 +65,4 @@ public class MembershipPaymentProcessor(
session.Id,
session.Url);
}
}

View File

@@ -19,8 +19,8 @@ public sealed class MembershipTierProcessor(
StripeConfiguration.ApiKey = stripeOptions.Value.SecretKey;
// Create the product
var productService = new ProductService();
var product = await productService.CreateAsync(
ProductService productService = new();
Product? product = await productService.CreateAsync(
new ProductCreateOptions
{
Name = productName,
@@ -28,7 +28,7 @@ public sealed class MembershipTierProcessor(
});
// Create the price for the product
var priceService = new PriceService();
PriceService priceService = new();
await priceService.CreateAsync(
new PriceCreateOptions
{

View File

@@ -24,14 +24,14 @@ public class StripeTipProcessor(
StripeConfiguration.ApiKey = stripeOptions.Value.SecretKey;
// Create Stripe customer for the user if not already created
var customerService = new CustomerService();
var customer = await customerService.CreateAsync(
CustomerService customerService = new();
Customer? customer = await customerService.CreateAsync(
new CustomerCreateOptions(),
cancellationToken: ct);
// Create paymentIntent for the user
var sessionService = new SessionService();
var session = await sessionService.CreateAsync(
SessionService sessionService = new();
Session? session = await sessionService.CreateAsync(
new SessionCreateOptions
{
ClientReferenceId = tipId.ToString(),
@@ -68,7 +68,7 @@ public class StripeTipProcessor(
CancelUrl = cancelUrl, // Redirect after canceled payment
Metadata = new Dictionary<string, string>
{
{ "creatorId", creator.Id.ToString() }, { "creatorName", creator.Name }, { "message", message },
{ "creatorId", creator.Id.ToString() }, { "creatorName", creator.Name }, { "message", message }
}
},
cancellationToken: ct);

View File

@@ -41,17 +41,22 @@ public static class ClaimsPrincipalExtensions
private static object? GetClaim<TValue>(this ClaimsPrincipal claims, string key)
{
var claim = claims.FindFirst(key);
Claim? claim = claims.FindFirst(key);
return claim is null ? null : claims.GetRequiredClaim<TValue>(key);
}
private static object GetRequiredClaim<TValue>(this ClaimsPrincipal claims, string key)
{
var claim = claims.FindFirst(key);
Claim? claim = claims.FindFirst(key);
if (claim is null) throw new MissingClaimException(key);
if (claim is null)
{
throw new MissingClaimException(key);
}
return typeof(TValue) == typeof(Guid) ? Guid.Parse(claim.Value) : Convert.ChangeType(claim.Value, typeof(TValue));
return typeof(TValue) == typeof(Guid)
? Guid.Parse(claim.Value)
: Convert.ChangeType(claim.Value, typeof(TValue));
}
}

View File

@@ -19,10 +19,10 @@ public static class JwtTokenHelper
string lastname,
string? portraitUrl)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
SymmetricSecurityKey securityKey = new(Encoding.UTF8.GetBytes(key));
SigningCredentials credentials = new(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new List<Claim>([
List<Claim> claims = new([
new Claim(JwtRegisteredClaimNames.Sub, userId),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.NameIdentifier, userId), new Claim(ClaimTypes.Email, email),
@@ -40,10 +40,10 @@ public static class JwtTokenHelper
claims.Add(new Claim(KnownClaims.PortraitUrl, portraitUrl));
}
var token = new JwtSecurityToken(
issuer: issuer,
audience: audience,
claims: claims,
JwtSecurityToken token = new(
issuer,
audience,
claims,
expires: DateTime.Now.Add(expiresIn),
signingCredentials: credentials);

View File

@@ -21,37 +21,53 @@ public static class PasswordGenerator
bool requireSpecialCharacter = true)
{
// Create pools based on the requirements
var characterPool = new StringBuilder();
StringBuilder characterPool = new();
if (requireNumber)
{
characterPool.Append(LowerLetters);
}
if (requireCapital)
{
characterPool.Append(UpperLetters);
}
if (requireNumber)
{
characterPool.Append(Numbers);
}
if (requireSpecialCharacter)
{
characterPool.Append(SpecialCharacters);
}
// Ensure that the length is within the specified bounds
var password = new char[length];
char[] password = new char[length];
// Ensure at least one character from each required category is included
int index = 0;
if (requireLowercase)
{
password[index++] = LowerLetters[Random.Next(LowerLetters.Length)];
}
if (requireCapital)
{
password[index++] = UpperLetters[Random.Next(UpperLetters.Length)];
}
if (requireNumber)
{
password[index++] = Numbers[Random.Next(Numbers.Length)];
}
if (requireSpecialCharacter)
{
password[index++] = SpecialCharacters[Random.Next(SpecialCharacters.Length)];
}
// Fill the rest with the password
for (int i = index; i < length; i++)

View File

@@ -6,7 +6,7 @@ public static class RefreshTokenGenerator
{
public static string Next()
{
var randomNumber = new byte[32];
byte[] randomNumber = new byte[32];
RandomNumberGenerator.Fill(randomNumber);
return Convert.ToBase64String(randomNumber);
}

View File

@@ -13,50 +13,60 @@ public static class YouTubeUrlHelper
RegexOptions.Compiled);
/// <summary>
/// Extracts the video ID from a YouTube URL or returns the input if it's already a video ID.
/// Extracts the video ID from a YouTube URL or returns the input if it's already a video ID.
/// </summary>
/// <param name="input">The YouTube URL or video ID</param>
/// <returns>The extracted video ID or null if invalid</returns>
public static string? ExtractVideoId(string? input)
{
if (string.IsNullOrWhiteSpace(input))
{
return null;
}
// If it's already a valid video ID, return it
if (IsValidVideoId(input))
{
return input;
}
// Try to extract video ID from URL
var match = VideoIdRegex.Match(input);
Match match = VideoIdRegex.Match(input);
return match.Success ? match.Groups[1].Value : null;
}
/// <summary>
/// Validates if the input is a valid YouTube video ID.
/// Validates if the input is a valid YouTube video ID.
/// </summary>
/// <param name="input">The video ID to validate</param>
/// <returns>True if the input is a valid video ID</returns>
public static bool IsValidVideoId(string? input)
{
if (string.IsNullOrWhiteSpace(input))
{
return false;
}
return ShortUrlRegex.IsMatch(input);
}
/// <summary>
/// Validates if the input is a valid YouTube URL or video ID.
/// Validates if the input is a valid YouTube URL or video ID.
/// </summary>
/// <param name="input">The URL or video ID to validate</param>
/// <returns>True if the input is a valid YouTube URL or video ID</returns>
public static bool IsValidYouTubeUrlOrId(string? input)
{
if (string.IsNullOrWhiteSpace(input))
{
return false;
}
// Check if it's a valid video ID
if (IsValidVideoId(input))
{
return true;
}
// Check if it's a valid YouTube URL
return VideoIdRegex.IsMatch(input);

View File

@@ -5,7 +5,7 @@ namespace Hutopy.Modules.Contents.Data;
public class Album : Entity
{
public bool IsDeleted { get; private set; } // private set → EF updates it
public bool IsDeleted { get; private set; } // private set → EF updates it
[MaxLength(255)] public required string Title { get; set; }
public IList<AlbumPhoto> Photos { get; set; } = new List<AlbumPhoto>();
}

View File

@@ -24,7 +24,7 @@ public class ContentsDbContext(
modelBuilder
.Entity<Album>()
.Property(c => c.IsDeleted)
.HasComputedColumnSql("\"DeletedAt\" IS NOT NULL", stored: true);
.HasComputedColumnSql("\"DeletedAt\" IS NOT NULL", true);
modelBuilder
.Entity<Album>()
@@ -40,7 +40,7 @@ public class ContentsDbContext(
modelBuilder
.Entity<AlbumPhoto>()
.Property(c => c.IsDeleted)
.HasComputedColumnSql("\"DeletedAt\" IS NOT NULL", stored: true);
.HasComputedColumnSql("\"DeletedAt\" IS NOT NULL", true);
modelBuilder
.Entity<AlbumPhoto>()

View File

@@ -17,9 +17,9 @@ public static class DependencyInjection
this IApplicationBuilder app,
CancellationToken cancellationToken = default)
{
var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
using var scope = scopeFactory.CreateScope();
await using var context = scope.ServiceProvider.GetRequiredService<ContentsDbContext>();
IServiceScopeFactory scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
using IServiceScope scope = scopeFactory.CreateScope();
await using ContentsDbContext context = scope.ServiceProvider.GetRequiredService<ContentsDbContext>();
await context.Database.MigrateAsync(cancellationToken);
return app;

View File

@@ -23,6 +23,7 @@ public record AddPhotoToAlbumResponse(
public sealed class AddPhotoToAlbumRequestValidator : Validator<AddPhotoToAlbumRequest>
{
private const int MaxFileSizeBytes = 10 * 1024 * 1024; // 10MB
private static readonly string[] AllowedImageTypes =
[
"image/jpeg",
@@ -74,14 +75,14 @@ public class AddPhotoToAlbumHandler(
AddPhotoToAlbumRequest request,
CancellationToken ct)
{
var userId = User.GetUserId();
Guid userId = User.GetUserId();
// Fetch the album we want to add photos to
var album = await context
Album? album = await context
.Albums
.SingleOrDefaultAsync(
a => a.Id == request.AlbumId && a.CreatedBy == userId,
cancellationToken: ct);
ct);
if (album is null)
{
@@ -90,7 +91,7 @@ public class AddPhotoToAlbumHandler(
}
// Check if a photo with the same ID already exists
var existingPhoto = await context
bool existingPhoto = await context
.AlbumPhotos
.AnyAsync(p => p.Id == request.PhotoId, ct);
@@ -102,16 +103,16 @@ public class AddPhotoToAlbumHandler(
try
{
var (originalUrl, thumbnailUrl) = await ProcessAndUploadImage(request, ct);
(string originalUrl, string thumbnailUrl) = await ProcessAndUploadImage(request, ct);
// Get the next order number
var nextOrder = await context
int nextOrder = await context
.AlbumPhotos
.Where(p => p.AlbumId == request.AlbumId)
.MaxAsync(p => (int?)p.Order, ct) ?? 0;
// Create the album photo
var photo = new AlbumPhoto
AlbumPhoto photo = new()
{
Id = request.PhotoId,
CreatedBy = userId,
@@ -143,23 +144,23 @@ public class AddPhotoToAlbumHandler(
AddPhotoToAlbumRequest request,
CancellationToken ct)
{
var originalFileName = Path.GetFileName(request.File.FileName);
var nameWithoutExt = Path.GetFileNameWithoutExtension(originalFileName);
var extension = Path.GetExtension(originalFileName);
string originalFileName = Path.GetFileName(request.File.FileName);
string nameWithoutExt = Path.GetFileNameWithoutExtension(originalFileName);
string extension = Path.GetExtension(originalFileName);
var filenameOriginal = $"{nameWithoutExt}{extension}";
var filenameThumbnail = $"{nameWithoutExt}.thumbnail{extension}";
string filenameOriginal = $"{nameWithoutExt}{extension}";
string filenameThumbnail = $"{nameWithoutExt}.thumbnail{extension}";
var blobOriginal = $"{SubDirectoryNames.Albums}/{request.AlbumId}/{filenameOriginal}";
var blobThumbnail = $"{SubDirectoryNames.Albums}/{request.AlbumId}/{filenameThumbnail}";
string blobOriginal = $"{SubDirectoryNames.Albums}/{request.AlbumId}/{filenameOriginal}";
string blobThumbnail = $"{SubDirectoryNames.Albums}/{request.AlbumId}/{filenameThumbnail}";
// Process the original image
await using var originalStream = request.File.OpenReadStream();
using var image = await Image.LoadAsync(originalStream, ct);
await using Stream originalStream = request.File.OpenReadStream();
using Image image = await Image.LoadAsync(originalStream, ct);
// Calculate target size while preserving the original aspect ratio
var originalWidth = image.Width;
var originalHeight = image.Height;
int originalWidth = image.Width;
int originalHeight = image.Height;
double ratioX = (double)MaxThumbnailWidth / originalWidth;
double ratioY = (double)MaxThumbnailHeight / originalHeight;
@@ -169,20 +170,20 @@ public class AddPhotoToAlbumHandler(
int newHeight = (int)(originalHeight * ratio);
// Create thumbnail
using var thumbnailStream = new MemoryStream();
using MemoryStream thumbnailStream = new();
image.Mutate(x => x.Resize(newWidth, newHeight));
await image.SaveAsync(thumbnailStream, image.Metadata.DecodedImageFormat!, ct);
thumbnailStream.Position = 0;
// Upload both versions
var originalUrl = await blobStorage.UploadFileAsync(
string originalUrl = await blobStorage.UploadFileAsync(
ContainerNames.Creators,
blobOriginal,
request.File.OpenReadStream(),
request.File.ContentType,
ct);
var thumbnailUrl = await blobStorage.UploadFileAsync(
string thumbnailUrl = await blobStorage.UploadFileAsync(
ContainerNames.Creators,
blobThumbnail,
thumbnailStream,

View File

@@ -48,7 +48,7 @@ public class CreateAlbumHandler(
CancellationToken ct)
{
// Check if an album with the same ID already exists
var existingAlbum = await context
bool existingAlbum = await context
.Albums
.AnyAsync(a => a.Id == request.AlbumId, ct);
@@ -58,12 +58,7 @@ public class CreateAlbumHandler(
return;
}
var album = new Album
{
Id = request.AlbumId,
CreatedBy = User.GetUserId(),
Title = request.Title
};
Album album = new() { Id = request.AlbumId, CreatedBy = User.GetUserId(), Title = request.Title };
context.Albums.Add(album);
await context.SaveChangesAsync(ct);

View File

@@ -49,12 +49,12 @@ public class GetAlbumHandler(
GetAlbumRequest request,
CancellationToken ct)
{
var album = await context
Album? album = await context
.Albums
.Include(a => a.Photos.OrderBy(p => p.Order))
.SingleOrDefaultAsync(
a => a.Id == request.AlbumId,
cancellationToken: ct);
ct);
if (album is null)
{
@@ -62,7 +62,7 @@ public class GetAlbumHandler(
return;
}
var photos = album.Photos
List<AlbumPhotoDto> photos = album.Photos
.Select(p => new AlbumPhotoDto(
p.Id,
p.OriginalUrl,

View File

@@ -33,14 +33,14 @@ public class RemoveAlbumHandler(
RemoveAlbumRequest request,
CancellationToken ct)
{
var userId = User.GetUserId();
Guid userId = User.GetUserId();
var album = await context
Album? album = await context
.Albums
.Include(a => a.Photos)
.SingleOrDefaultAsync(
a => a.Id == request.AlbumId && a.CreatedBy == userId,
cancellationToken: ct);
ct);
if (album is null)
{
@@ -53,7 +53,7 @@ public class RemoveAlbumHandler(
album.DeletedAt = DateTimeOffset.UtcNow;
// Soft delete all photos in the album
foreach (var photo in album.Photos)
foreach (AlbumPhoto photo in album.Photos)
{
photo.DeletedBy = userId;
photo.DeletedAt = DateTimeOffset.UtcNow;

View File

@@ -38,14 +38,14 @@ public class RemovePhotoFromAlbumHandler(
RemovePhotoFromAlbumRequest request,
CancellationToken ct)
{
var userId = User.GetUserId();
Guid userId = User.GetUserId();
var album = await context
Album? album = await context
.Albums
.Include(a => a.Photos)
.SingleOrDefaultAsync(
a => a.Id == request.AlbumId && a.CreatedBy == userId,
cancellationToken: ct);
ct);
if (album is null)
{
@@ -53,7 +53,7 @@ public class RemovePhotoFromAlbumHandler(
return;
}
var photo = album.Photos
AlbumPhoto? photo = album.Photos
.SingleOrDefault(p => p.Id == request.PhotoId);
if (photo is null)

View File

@@ -12,9 +12,9 @@ public class Creator
public DateTimeOffset? DeletedAt { get; set; }
/// <summary>
/// Softdelete flag (false by default, true once DeletedAt is set)
/// Softdelete flag (false by default, true once DeletedAt is set)
/// </summary>
public bool IsDeleted { get; private set; } // private set → EF updates it
public bool IsDeleted { get; private set; } // private set → EF updates it
[MaxLength(2048)] public string? BannerUrl { get; set; }
[MaxLength(2048)] public string? PortraitUrl { get; set; }

View File

@@ -17,7 +17,7 @@ public class CreatorsDbContext(
modelBuilder
.Entity<Slugs>()
.Property(x => x.NormalizedName)
.HasComputedColumnSql("LOWER(\"Name\")", stored: true);
.HasComputedColumnSql("LOWER(\"Name\")", true);
modelBuilder
.Entity<Slugs>()
@@ -27,7 +27,7 @@ public class CreatorsDbContext(
modelBuilder
.Entity<Creator>()
.Property(c => c.IsDeleted)
.HasComputedColumnSql("\"DeletedAt\" IS NOT NULL", stored: true); // bool
.HasComputedColumnSql("\"DeletedAt\" IS NOT NULL", true); // bool
modelBuilder
.Entity<Creator>()

View File

@@ -25,10 +25,10 @@ public static class DependencyInjection
this IApplicationBuilder app,
CancellationToken cancellationToken = default)
{
var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
using var scope = scopeFactory.CreateScope();
await using var context = scope.ServiceProvider.GetRequiredService<CreatorsDbContext>();
await context.Database.MigrateAsync(cancellationToken: cancellationToken);
IServiceScopeFactory scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
using IServiceScope scope = scopeFactory.CreateScope();
await using CreatorsDbContext context = scope.ServiceProvider.GetRequiredService<CreatorsDbContext>();
await context.Database.MigrateAsync(cancellationToken);
return app;
}

View File

@@ -29,11 +29,11 @@ public static class ChangeBanner
Request request,
CancellationToken ct)
{
var creator = await context
Creator? creator = await context
.Creators
.SingleOrDefaultAsync(
c => c.Id == request.CreatorId,
cancellationToken: ct);
ct);
if (creator is null)
{
@@ -41,7 +41,7 @@ public static class ChangeBanner
return;
}
var blobUrl = await blobStorage.UploadFileAsync(
string blobUrl = await blobStorage.UploadFileAsync(
ContainerNames.Creators,
$"{request.CreatorId}/{SubDirectoryNames.Profile}/{CommonFileNames.BannerPicture}",
request.File.OpenReadStream(),

View File

@@ -38,12 +38,12 @@ public class ChangeEmailHandler(
ChangeEmailRequest request,
CancellationToken ct)
{
var creator = await context
Creator? creator = await context
.Creators
.Include(c => c.Presentation)
.SingleOrDefaultAsync(
c => c.Id == request.CreatorId,
cancellationToken: ct);
ct);
if (creator is null)
{

View File

@@ -44,11 +44,11 @@ public class ChangeLogoHandler(
ChangeLogoRequest request,
CancellationToken ct)
{
var creator = await context
Creator? creator = await context
.Creators
.SingleOrDefaultAsync(
c => c.Id == request.CreatorId,
cancellationToken: ct);
ct);
if (creator is null)
{
@@ -56,7 +56,7 @@ public class ChangeLogoHandler(
return;
}
var blobUrl = await blobStorage.UploadFileAsync(
string blobUrl = await blobStorage.UploadFileAsync(
ContainerNames.Creators,
$"{request.CreatorId}/{SubDirectoryNames.Profile}/{CommonFileNames.ProfilePicture}",
request.File.OpenReadStream(),

View File

@@ -34,11 +34,11 @@ public class ChangeNameHandler(
ChangeNameRequest request,
CancellationToken ct)
{
var creator = await context
Creator creator = await context
.Creators
.SingleAsync(
c => c.Id == request.CreatorId,
cancellationToken: ct);
ct);
creator.Name = request.Name;

View File

@@ -38,12 +38,12 @@ public class ChangePhoneNumberHandler(
ChangePhoneNumberRequest request,
CancellationToken ct)
{
var creator = await context
Creator? creator = await context
.Creators
.Include(c => c.Presentation)
.SingleOrDefaultAsync(
c => c.Id == request.CreatorId,
cancellationToken: ct);
ct);
if (creator is null)
{

View File

@@ -45,12 +45,12 @@ public class ChangePresentationInfosHandler(
ChangePresentationInfosRequest request,
CancellationToken ct)
{
var creator = await context
Creator? creator = await context
.Creators
.Include(c => c.Presentation)
.SingleOrDefaultAsync(
c => c.Id == request.CreatorId,
cancellationToken: ct);
ct);
if (creator is null)
{

View File

@@ -1,5 +1,6 @@
using Hutopy.Infrastructure.Security;
using Hutopy.Modules.Creators.Data;
using Microsoft.EntityFrameworkCore.Storage;
namespace Hutopy.Modules.Creators.Features;
@@ -39,15 +40,15 @@ public class ChangeSlugHandler(
ChangeSlugRequest request,
CancellationToken ct)
{
await using var transaction = await context.Database.BeginTransactionAsync(ct);
await using IDbContextTransaction transaction = await context.Database.BeginTransactionAsync(ct);
try
{
var creator = await context
Creator creator = await context
.Creators
.SingleAsync(
c => c.Id == request.CreatorId,
cancellationToken: ct);
ct);
if (creator.CreatedBy != User.GetUserId())
{
@@ -55,7 +56,7 @@ public class ChangeSlugHandler(
return;
}
var reservation = await context
Slugs? reservation = await context
.Slugs
.FirstOrDefaultAsync(
s => s.Id == request.SlugReservationId,
@@ -67,7 +68,7 @@ public class ChangeSlugHandler(
return;
}
var previousReservation = await context
Slugs? previousReservation = await context
.Slugs
.FirstOrDefaultAsync(
s => s.UsedBy == request.CreatorId,

View File

@@ -27,12 +27,12 @@ public class ChangeSocialsHandler(
public override async Task HandleAsync(ChangeSocialsRequest request, CancellationToken ct)
{
var creator = await context
Creator creator = await context
.Creators
.Include(c => c.Socials)
.SingleAsync(
c => c.Id == request.CreatorId,
cancellationToken: ct);
ct);
creator.Socials.FacebookUrl = request.FacebookUrl;
creator.Socials.InstagramUrl = request.InstagramUrl;

View File

@@ -22,11 +22,11 @@ public class ChangeTitleHandler(
ChangeTitleRequest request,
CancellationToken ct)
{
var creator = await context
Creator creator = await context
.Creators
.SingleAsync(
c => c.Id == request.CreatorId,
cancellationToken: ct);
ct);
creator.Title = request.Title;

View File

@@ -1,5 +1,6 @@
using Hutopy.Infrastructure.Security;
using Hutopy.Modules.Creators.Data;
using Microsoft.EntityFrameworkCore.Storage;
namespace Hutopy.Modules.Creators.Features;
@@ -40,11 +41,11 @@ public sealed class CreateCreatorHandler(
CreateCreatorRequest req,
CancellationToken ct)
{
await using var transaction = await context.Database.BeginTransactionAsync(ct);
await using IDbContextTransaction transaction = await context.Database.BeginTransactionAsync(ct);
try
{
var slug = await context
Slugs slug = await context
.Slugs
.SingleAsync(s => s.Id == req.SlugReservationId, ct);
@@ -61,10 +62,7 @@ public sealed class CreateCreatorHandler(
await context.Creators.AddAsync(
new Creator
{
Id = req.CreatorId,
CreatedBy = User.GetUserId(),
Name = slug.Name,
Slug = slug.NormalizedName
Id = req.CreatorId, CreatedBy = User.GetUserId(), Name = slug.Name, Slug = slug.NormalizedName
},
ct);

View File

@@ -28,7 +28,7 @@ public class GetCreatorByIdHandler(
public override void Configure()
{
Get("/api/creators/{CreatorId}");
Options((o => o.WithTags("Creators")));
Options(o => o.WithTags("Creators"));
AllowAnonymous();
}
@@ -36,13 +36,19 @@ public class GetCreatorByIdHandler(
GetCreatorByIdRequest req,
CancellationToken ct)
{
var creator = await context
Creator? creator = await context
.Creators
.FindAsync(
[req.CreatorId],
cancellationToken: ct);
ct);
if (creator is null) await SendNotFoundAsync(ct);
else await SendAsync(creator, cancellation: ct);
if (creator is null)
{
await SendNotFoundAsync(ct);
}
else
{
await SendAsync(creator, cancellation: ct);
}
}
}

View File

@@ -49,7 +49,7 @@ public class GetCreatorBySlugHandler(
public override void Configure()
{
Get("/api/creators/@{Name}");
Options((o => o.WithTags("Creators")));
Options(o => o.WithTags("Creators"));
AllowAnonymous();
}
@@ -57,9 +57,9 @@ public class GetCreatorBySlugHandler(
GetCreatorBySlugRequest req,
CancellationToken ct)
{
var creatorName = req.Name.ToLower();
string creatorName = req.Name.ToLower();
var response = await context
GetCreatorBySlugResponse? response = await context
.Creators
.IgnoreQueryFilters()
.Where(c => EF.Functions.ILike(c.Slug, creatorName))

View File

@@ -34,12 +34,12 @@ public sealed class RemoveCreatorHandler(
RemoveCreatorRequest req,
CancellationToken ct)
{
var creatorSlug = req.CreatorSlug.ToLower();
string creatorSlug = req.CreatorSlug.ToLower();
var creator = await context
Creator? creator = await context
.Creators
.Where(c => EF.Functions.ILike(c.Slug, creatorSlug))
.SingleOrDefaultAsync(cancellationToken: ct);
.SingleOrDefaultAsync(ct);
if (creator is null)
{

View File

@@ -4,6 +4,7 @@ using Hutopy.Infrastructure.Security;
using Hutopy.Modules.Creators.Configuration;
using Hutopy.Modules.Creators.Data;
using Hutopy.Modules.Creators.Services;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Options;
using Npgsql;
@@ -45,24 +46,22 @@ public sealed class ReserveSlug(
ReserveSlugRequest req,
CancellationToken ct)
{
await using var transaction = await context.Database.BeginTransactionAsync(ct);
await using IDbContextTransaction transaction = await context.Database.BeginTransactionAsync(ct);
try
{
// First, purge any expired slugs
await slugPurger.PurgeExpiredSlugsAsync(ct);
var reservation = await context.Slugs.FirstOrDefaultAsync(
Slugs? reservation = await context.Slugs.FirstOrDefaultAsync(
s => s.Id == req.ReservationId && s.CreatedBy == User.GetUserId(),
cancellationToken: ct);
ct);
if (reservation == null)
{
reservation = new Slugs
{
Id = req.ReservationId,
CreatedBy = User.GetUserId(),
CreatedAt = DateTimeOffset.UtcNow,
Id = req.ReservationId, CreatedBy = User.GetUserId(), CreatedAt = DateTimeOffset.UtcNow
};
context.Slugs.Attach(reservation);

View File

@@ -34,13 +34,13 @@ public sealed class RestoreCreatorHandler(
RestoreCreatorRequest req,
CancellationToken ct)
{
var creatorSlug = req.CreatorSlug.ToLower();
string creatorSlug = req.CreatorSlug.ToLower();
var creator = await context
Creator? creator = await context
.Creators
.IgnoreQueryFilters()
.Where(c => EF.Functions.ILike(c.Slug, creatorSlug))
.SingleOrDefaultAsync(cancellationToken: ct);
.SingleOrDefaultAsync(ct);
if (creator is null)
{

View File

@@ -19,7 +19,7 @@ public class SlugPurger(CreatorsDbContext context)
try
{
var now = DateTimeOffset.UtcNow;
DateTimeOffset now = DateTimeOffset.UtcNow;
if (now - s_lastPurgeTime < MinTimeBetweenPurges)
{
// Not enough time has passed since the last purge

View File

@@ -1,20 +1,18 @@
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace Hutopy.Modules.Identity.Data
namespace Hutopy.Modules.Identity.Data;
public class IdentityDbContext(
DbContextOptions<IdentityDbContext> options)
: IdentityDbContext<User, Role, Guid>(options)
{
public class IdentityDbContext(
DbContextOptions<IdentityDbContext> options)
: IdentityDbContext<User, Role, Guid>(options)
public const string SchemaName = "Identity";
protected override void OnModelCreating(ModelBuilder
modelBuilder)
{
public const string SchemaName = "Identity";
protected override void OnModelCreating(ModelBuilder
modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.HasDefaultSchema(SchemaName);
}
base.OnModelCreating(modelBuilder);
modelBuilder.HasDefaultSchema(SchemaName);
}
}

View File

@@ -10,19 +10,22 @@ public class IdentityService(
{
public async Task<UserModel?> GetCurrentUserAsync()
{
var currentUserId = contextAccessor.HttpContext?.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
string? currentUserId = contextAccessor.HttpContext?.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(currentUserId))
{
return null;
}
UserModel? ret;
var user = await userManager.FindByIdAsync(currentUserId);
User? user = await userManager.FindByIdAsync(currentUserId);
if (user == null) ret = null;
if (user == null)
{
ret = null;
}
else
{
var userModel = new UserModel
UserModel userModel = new()
{
Id = user.Id,
Username = user.UserName ?? string.Empty,
@@ -44,17 +47,22 @@ public class IdentityService(
public async Task<IList<string>> GetCurrentUserRolesAsync()
{
var currentUserModel = await GetCurrentUserAsync();
UserModel? currentUserModel = await GetCurrentUserAsync();
if (currentUserModel is null) return [];
if (currentUserModel is null)
{
return [];
}
var currentUser = await userManager.FindByIdAsync(currentUserModel.Id.ToString());
User? currentUser = await userManager.FindByIdAsync(currentUserModel.Id.ToString());
if (currentUser is null) return [];
if (currentUser is null)
{
return [];
}
var userRoles = await userManager.GetRolesAsync(currentUser);
IList<string> userRoles = await userManager.GetRolesAsync(currentUser);
return userRoles;
}
}

View File

@@ -17,4 +17,3 @@ public class User : IdentityUser<Guid>
public DateTime RefreshTokenExpiryTime { get; set; }
public string Fullname => $"{Lastname}, {Firstname}";
}

View File

@@ -1,5 +1,6 @@
using Hutopy.Infrastructure.Security;
using Hutopy.Modules.Identity.Data;
using Microsoft.AspNetCore.Identity;
namespace Hutopy.Modules.Identity.Handlers;
@@ -22,7 +23,7 @@ public class ChangeAddressHandler(
ChangeAddressRequest request,
CancellationToken ct)
{
var user = await userManager.FindByIdAsync(HttpContext.User.GetUserId().ToString());
User? user = await userManager.FindByIdAsync(HttpContext.User.GetUserId().ToString());
if (user is null)
{
@@ -32,11 +33,15 @@ public class ChangeAddressHandler(
user.Address = request.Address;
var result = await userManager.UpdateAsync(user);
IdentityResult result = await userManager.UpdateAsync(user);
if (result.Succeeded)
{
await SendOkAsync(ct);
}
else
{
await SendUnauthorizedAsync(ct);
}
}
}

View File

@@ -1,5 +1,6 @@
using Hutopy.Infrastructure.Security;
using Hutopy.Modules.Identity.Data;
using Microsoft.AspNetCore.Identity;
namespace Hutopy.Modules.Identity.Handlers;
@@ -22,7 +23,7 @@ public class ChangeAliasHandler(
ChangeAliasRequest request,
CancellationToken ct)
{
var user = await userManager.FindByIdAsync(HttpContext.User.GetUserId().ToString());
User? user = await userManager.FindByIdAsync(HttpContext.User.GetUserId().ToString());
if (user is null)
{
@@ -32,11 +33,15 @@ public class ChangeAliasHandler(
user.Alias = request.Alias;
var result = await userManager.UpdateAsync(user);
IdentityResult result = await userManager.UpdateAsync(user);
if (result.Succeeded)
{
await SendOkAsync(ct);
}
else
{
await SendUnauthorizedAsync(ct);
}
}
}

View File

@@ -1,5 +1,6 @@
using Hutopy.Infrastructure.Security;
using Hutopy.Modules.Identity.Data;
using Microsoft.AspNetCore.Identity;
namespace Hutopy.Modules.Identity.Handlers;
@@ -22,7 +23,7 @@ public class ChangeBirthDateHandler(
ChangeBirthDateRequest request,
CancellationToken ct)
{
var user = await userManager.FindByIdAsync(HttpContext.User.GetUserId().ToString());
User? user = await userManager.FindByIdAsync(HttpContext.User.GetUserId().ToString());
if (user is null)
{
@@ -32,11 +33,15 @@ public class ChangeBirthDateHandler(
user.BirthDate = request.BirthDate;
var result = await userManager.UpdateAsync(user);
IdentityResult result = await userManager.UpdateAsync(user);
if (result.Succeeded)
{
await SendOkAsync(ct);
}
else
{
await SendUnauthorizedAsync(ct);
}
}
}

View File

@@ -1,5 +1,6 @@
using Hutopy.Infrastructure.Security;
using Hutopy.Modules.Identity.Data;
using Microsoft.AspNetCore.Identity;
namespace Hutopy.Modules.Identity.Handlers;
@@ -22,7 +23,7 @@ public class ChangeEmailHandler(
ChangeEmailRequest request,
CancellationToken ct)
{
var user = await userManager.FindByIdAsync(HttpContext.User.GetUserId().ToString());
User? user = await userManager.FindByIdAsync(HttpContext.User.GetUserId().ToString());
if (user is null)
{
@@ -33,11 +34,15 @@ public class ChangeEmailHandler(
user.Email = request.Email;
// TODO: check to see if identity resets the `email confirmed` flag - @jonathan
var result = await userManager.UpdateAsync(user);
IdentityResult result = await userManager.UpdateAsync(user);
if (result.Succeeded)
{
await SendOkAsync(ct);
}
else
{
await SendUnauthorizedAsync(ct);
}
}
}

View File

@@ -1,5 +1,6 @@
using Hutopy.Infrastructure.Security;
using Hutopy.Modules.Identity.Data;
using Microsoft.AspNetCore.Identity;
namespace Hutopy.Modules.Identity.Handlers;
@@ -23,7 +24,7 @@ public class ChangeFullnameHandler(
ChangeFullnameRequest request,
CancellationToken ct)
{
var user = await userManager.FindByIdAsync(HttpContext.User.GetUserId().ToString());
User? user = await userManager.FindByIdAsync(HttpContext.User.GetUserId().ToString());
if (user is null)
{
@@ -34,11 +35,15 @@ public class ChangeFullnameHandler(
user.Firstname = request.Firstname;
user.Lastname = request.Lastname;
var result = await userManager.UpdateAsync(user);
IdentityResult result = await userManager.UpdateAsync(user);
if (result.Succeeded)
{
await SendOkAsync(ct);
}
else
{
await SendUnauthorizedAsync(ct);
}
}
}

View File

@@ -1,5 +1,6 @@
using Hutopy.Infrastructure.Security;
using Hutopy.Modules.Identity.Data;
using Microsoft.AspNetCore.Identity;
namespace Hutopy.Modules.Identity.Handlers;
@@ -22,7 +23,7 @@ public class ChangePhoneHandler(
ChangePhoneRequest request,
CancellationToken ct)
{
var user = await userManager.FindByIdAsync(HttpContext.User.GetUserId().ToString());
User? user = await userManager.FindByIdAsync(HttpContext.User.GetUserId().ToString());
if (user is null)
{
@@ -33,11 +34,15 @@ public class ChangePhoneHandler(
user.PhoneNumber = request.PhoneNumber;
// TODO: check to see if identity resets the `phone confirmed` flag - @jonathan
var result = await userManager.UpdateAsync(user);
IdentityResult result = await userManager.UpdateAsync(user);
if (result.Succeeded)
{
await SendOkAsync(ct);
}
else
{
await SendUnauthorizedAsync(ct);
}
}
}

View File

@@ -1,6 +1,7 @@
using Hutopy.Infrastructure.BlobStorage.Contracts;
using Hutopy.Infrastructure.Security;
using Hutopy.Modules.Identity.Data;
using Microsoft.AspNetCore.Identity;
namespace Hutopy.Modules.Identity.Handlers;
@@ -40,7 +41,7 @@ public class ChangePortraitHandler(
ChangePortraitRequest request,
CancellationToken ct)
{
var user = await userManager.FindByIdAsync(HttpContext.User.GetUserId().ToString());
User? user = await userManager.FindByIdAsync(HttpContext.User.GetUserId().ToString());
if (user is null)
{
@@ -48,7 +49,7 @@ public class ChangePortraitHandler(
return;
}
var blobUrl = await blobStorage.UploadFileAsync(
string blobUrl = await blobStorage.UploadFileAsync(
ContainerNames.Users,
$"{user.Id}/{SubDirectoryNames.Profile}/{CommonFileNames.ProfilePicture}",
request.File.OpenReadStream(),
@@ -57,7 +58,7 @@ public class ChangePortraitHandler(
user.PortraitUrl = blobUrl;
var result = await userManager.UpdateAsync(user);
IdentityResult result = await userManager.UpdateAsync(user);
if (result.Succeeded)
{

View File

@@ -17,7 +17,7 @@ public class GetCurrentUserQueryHandler(
public override async Task HandleAsync(
CancellationToken cancellationToken)
{
var userModel = await identityService.GetCurrentUserAsync();
UserModel? userModel = await identityService.GetCurrentUserAsync();
if (userModel is null)
{
@@ -25,7 +25,7 @@ public class GetCurrentUserQueryHandler(
return;
}
var roles = await identityService.GetCurrentUserRolesAsync();
IList<string> roles = await identityService.GetCurrentUserRolesAsync();
await SendOkAsync(
new UserDto

View File

@@ -1,5 +1,6 @@
using Hutopy.Infrastructure.BlobStorage.Contracts;
using Hutopy.Modules.Identity.Data;
using Hutopy.Modules.Identity.Models;
namespace Hutopy.Modules.Identity.Handlers;
@@ -19,7 +20,7 @@ public class GetCurrentUserPortraitHandler(
public override async Task HandleAsync(
CancellationToken cancellationToken)
{
var identityUser = await identityService.GetCurrentUserAsync();
UserModel? identityUser = await identityService.GetCurrentUserAsync();
if (identityUser is null)
{
@@ -27,7 +28,7 @@ public class GetCurrentUserPortraitHandler(
return;
}
var stream = await blobStorage.DownloadFileAsync(
MemoryStream stream = await blobStorage.DownloadFileAsync(
ContainerNames.Users,
$"{identityUser.Id.ToString()}/{SubDirectoryNames.Profile}/{CommonFileNames.ProfilePicture}",
cancellationToken);

View File

@@ -32,7 +32,7 @@ public class RefreshTokenHandler(
CancellationToken ct)
{
// Find the user using the refresh token
var user = await userManager.Users
User? user = await userManager.Users
.FirstOrDefaultAsync(u => u.RefreshToken == request.RefreshToken, ct);
if (user == null || user.RefreshTokenExpiryTime <= DateTime.UtcNow)
@@ -52,20 +52,20 @@ public class RefreshTokenHandler(
await userManager.UpdateAsync(user);
// Generate a new access token
var accessToken = JwtTokenHelper.GenerateJwtToken(
expiresIn: jwtOptions.Value.Lifetime,
issuer: jwtOptions.Value.Issuer,
audience: jwtOptions.Value.Audience,
key: jwtOptions.Value.Key,
userId: user.Id.ToString(),
email: user.Email ?? string.Empty,
alias: user.Alias,
firstname: user.Firstname ?? string.Empty,
lastname: user.Lastname ?? string.Empty,
portraitUrl: user.PortraitUrl);
string accessToken = JwtTokenHelper.GenerateJwtToken(
jwtOptions.Value.Lifetime,
jwtOptions.Value.Issuer,
jwtOptions.Value.Audience,
jwtOptions.Value.Key,
user.Id.ToString(),
user.Email ?? string.Empty,
user.Alias,
user.Firstname ?? string.Empty,
user.Lastname ?? string.Empty,
user.PortraitUrl);
await SendOkAsync(
new RefreshTokenResponse(accessToken, user.RefreshToken),
cancellation: ct);
ct);
}
}

View File

@@ -1,4 +1,5 @@
using Hutopy.Modules.Identity.Data;
using Microsoft.AspNetCore.Identity;
namespace Hutopy.Modules.Identity.Handlers;
@@ -25,7 +26,7 @@ public class ResetPasswordHandler(
CancellationToken ct)
{
// Find user by email
var user = await userManager.FindByEmailAsync(request.Email);
User? user = await userManager.FindByEmailAsync(request.Email);
if (user is null)
{
await SendStringAsync(
@@ -36,7 +37,7 @@ public class ResetPasswordHandler(
}
// Reset password with token
var result = await userManager.ResetPasswordAsync(
IdentityResult result = await userManager.ResetPasswordAsync(
user,
request.Token,
request.NewPassword);

View File

@@ -1,5 +1,6 @@
using Hutopy.Infrastructure.Security;
using Hutopy.Modules.Identity.Data;
using Microsoft.AspNetCore.Identity;
namespace Hutopy.Modules.Identity.Handlers;
@@ -23,18 +24,18 @@ public class SetPasswordHandler(
CancellationToken ct)
{
// Get current user id from claims
var userId = User.GetUserId().ToString();
string userId = User.GetUserId().ToString();
// Get user from database
var user = await userManager.FindByIdAsync(userId);
User? user = await userManager.FindByIdAsync(userId);
if (user is null)
{
await SendForbiddenAsync(ct);
return;
}
var resetToken = await userManager.GeneratePasswordResetTokenAsync(user);
var result = await userManager.ResetPasswordAsync(user, resetToken, request.NewPassword);
string resetToken = await userManager.GeneratePasswordResetTokenAsync(user);
IdentityResult result = await userManager.ResetPasswordAsync(user, resetToken, request.NewPassword);
if (!result.Succeeded)
{

View File

@@ -9,7 +9,7 @@ public sealed class UserLookup(
{
public async Task<UserReference?> GetUserAsync(Guid userId, CancellationToken cancellationToken = default)
{
var user = await userManager.FindByIdAsync(userId.ToString());
User? user = await userManager.FindByIdAsync(userId.ToString());
return user is null
? null

View File

@@ -14,7 +14,7 @@ public class Membership
public DateTimeOffset? StartDate { get; set; }
public DateTimeOffset? EndDate { get; set; }
public bool IsActive => EndDate == null || EndDate > DateTimeOffset.UtcNow;
[MaxLength(256)]public string? StripeSubscriptionId { get; set; }
[MaxLength(256)] public string? StripeSubscriptionId { get; set; }
public ICollection<Payment> Payments { get; set; } = [];
}

View File

@@ -9,5 +9,4 @@ public class Payment
public decimal Amount { get; set; }
[MaxLength(8)] public required string Currency { get; set; }
[MaxLength(2048)] public required string InvoiceUrl { get; set; }
}

View File

@@ -22,10 +22,10 @@ public static class DependencyInjection
this IApplicationBuilder app,
CancellationToken cancellationToken = default)
{
var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
using var scope = scopeFactory.CreateScope();
await using var context = scope.ServiceProvider.GetRequiredService<MembershipsDbContext>();
await context.Database.MigrateAsync(cancellationToken: cancellationToken);
IServiceScopeFactory scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
using IServiceScope scope = scopeFactory.CreateScope();
await using MembershipsDbContext context = scope.ServiceProvider.GetRequiredService<MembershipsDbContext>();
await context.Database.MigrateAsync(cancellationToken);
return app;
}

View File

@@ -24,11 +24,11 @@ public class CancelMembershipHandler(
CancelMembershipRequest req,
CancellationToken ct)
{
var subscription = await dbContext
Membership? subscription = await dbContext
.Memberships
.FindAsync(
[req.SubscriptionId],
cancellationToken: ct);
ct);
if (subscription is not { EndDate: null }
|| subscription.StripeSubscriptionId is null)

View File

@@ -27,9 +27,9 @@ public class CreateMembershipTierEndpoint(
CreateMembershipTierRequest req,
CancellationToken ct)
{
var tierId = Guid.CreateVersion7();
Guid tierId = Guid.CreateVersion7();
var productId = await membershipTierProcessor.CreateAsync(
string productId = await membershipTierProcessor.CreateAsync(
req.CreatorId,
tierId,
req.Name,
@@ -37,14 +37,14 @@ public class CreateMembershipTierEndpoint(
req.Price);
// Record the new Tier
var tier = new MembershipTier
MembershipTier tier = new()
{
Id = tierId,
CreatorId = req.CreatorId,
Price = req.Price,
Name = req.Name,
Description = req.Description,
StripeProductId = productId,
StripeProductId = productId
};
dbContext.MembershipTiers.Add(tier);

View File

@@ -28,16 +28,16 @@ public class GetActiveMembershipsHandler(
public override async Task HandleAsync(
CancellationToken ct)
{
var subscriptions = await dbContext
List<Membership> subscriptions = await dbContext
.Memberships
.Where(subscription => subscription.UserId == User.GetUserId())
.Where(subscription => subscription.State == MembershipState.Active)
.ToListAsync(ct);
var result = await Task.WhenAll(
GetActiveMembershipsResponse[] result = await Task.WhenAll(
subscriptions.Select(async subscription =>
{
var creator = await creatorLookup.GetCreatorAsync(subscription.CreatorId, ct);
CreatorReference? creator = await creatorLookup.GetCreatorAsync(subscription.CreatorId, ct);
return new GetActiveMembershipsResponse(
subscription.Id,

View File

@@ -34,7 +34,7 @@ public class GetMembershipTiersEndpoint(
GetMembershipTiersRequest req,
CancellationToken ct)
{
var tiers = await dbContext
List<TierModel> tiers = await dbContext
.MembershipTiers
.Where(tier => tier.CreatorId == req.CreatorId)
.Select(tier => new TierModel(

View File

@@ -44,7 +44,7 @@ public class SubscribeHandler(
SubscribeRequest req,
CancellationToken ct)
{
var tier = await dbContext
MembershipTier? tier = await dbContext
.MembershipTiers
.Where(tier => tier.Id == req.MembershipTierId)
.FirstOrDefaultAsync(ct);
@@ -54,7 +54,7 @@ public class SubscribeHandler(
return;
}
var creator = await creatorLookup.GetCreatorAsync(tier.CreatorId, ct);
CreatorReference? creator = await creatorLookup.GetCreatorAsync(tier.CreatorId, ct);
if (creator == null)
{
await SendNotFoundAsync(ct);
@@ -68,7 +68,7 @@ public class SubscribeHandler(
}
// Process Stripe subscription
var checkoutSession = await membershipPaymentProcessor.CreateCheckoutSessionAsync(
MembershipCheckoutSession checkoutSession = await membershipPaymentProcessor.CreateCheckoutSessionAsync(
User.GetUserId(),
creator,
tier.Id,
@@ -78,6 +78,6 @@ public class SubscribeHandler(
await SendOkAsync(
new SubscriptionResponse { StripeCheckoutUrl = checkoutSession.Url },
cancellation: ct);
ct);
}
}

View File

@@ -15,7 +15,7 @@ public class MembershipNotifier(
string tierId,
CancellationToken cancellationToken = default)
{
var membership = new Membership
Membership membership = new()
{
Id = Guid.CreateVersion7(),
CreatedAt = DateTimeOffset.UtcNow,
@@ -40,17 +40,17 @@ public class MembershipNotifier(
string currency,
CancellationToken cancellationToken = default)
{
var membership = await dbContext
Membership? membership = await dbContext
.Memberships
.SingleOrDefaultAsync(
m => m.StripeSubscriptionId == stripeSubscriptionId,
cancellationToken: cancellationToken);
cancellationToken);
if (membership is null)
{
return;
}
var payment = new Payment
Payment payment = new()
{
Id = Guid.CreateVersion7(),
CreatedAt = DateTimeOffset.UtcNow,
@@ -73,11 +73,11 @@ public class MembershipNotifier(
DateTimeOffset? endDate,
CancellationToken cancellationToken = default)
{
var membership = await dbContext
Membership? membership = await dbContext
.Memberships
.SingleOrDefaultAsync(
s => s.StripeSubscriptionId == subscriptionId,
cancellationToken: cancellationToken);
cancellationToken);
if (membership == null)
{
return;
@@ -92,11 +92,11 @@ public class MembershipNotifier(
string subscriptionId,
CancellationToken cancellationToken)
{
var membership = await dbContext
Membership? membership = await dbContext
.Memberships
.SingleOrDefaultAsync(
s => s.StripeSubscriptionId == subscriptionId,
cancellationToken: cancellationToken);
cancellationToken);
if (membership == null)
{
return;

View File

@@ -10,6 +10,8 @@ public class MessagingDbContext(
{
public const string SchemaName = "Messaging";
public DbSet<Message> Messages { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(SchemaName);
@@ -21,8 +23,6 @@ public class MessagingDbContext(
.HasDefaultValueSql("CURRENT_TIMESTAMP");
}
public DbSet<Message> Messages { get; set; }
public async Task<IEnumerable<MessageDto>> GetMessagesAsync(
Guid subjectId,
Guid? parentId,
@@ -30,7 +30,7 @@ public class MessagingDbContext(
int pageSize,
CancellationToken ct = default)
{
var query = Messages
IQueryable<Message> query = Messages
.Where(c => c.SubjectId == subjectId)
.Where(c => c.ParentId == parentId);
@@ -39,7 +39,7 @@ public class MessagingDbContext(
var lastMessage = await Messages
.Where(c => c.Id == lastId.Value)
.Select(c => new { c.CreatedAt, c.Id })
.FirstOrDefaultAsync(cancellationToken: ct);
.FirstOrDefaultAsync(ct);
if (lastMessage != null)
{
@@ -49,17 +49,17 @@ public class MessagingDbContext(
}
}
var messages = await query
List<Message> messages = await query
.OrderByDescending(c => c.CreatedAt)
.ThenByDescending(c => c.Id)
.Take(pageSize)
.ToListAsync(cancellationToken: ct);
.ToListAsync(ct);
var result = await Task.WhenAll(
MessageDto[] result = await Task.WhenAll(
messages.Select(async message =>
{
var writer = await userLookup.GetUserAsync(message.CreatedBy, ct);
UserReference? writer = await userLookup.GetUserAsync(message.CreatedBy, ct);
return new MessageDto(
message.Id,
message.SubjectId,
@@ -80,11 +80,11 @@ public class MessagingDbContext(
int pageSize,
CancellationToken ct = default)
{
var query = Messages
IQueryable<Message> query = Messages
.Where(c => c.SubjectId == subjectId)
.Where(c => c.ParentId == parentId);
var messageCount = await query
int messageCount = await query
.Take(pageSize)
.CountAsync(ct);

View File

@@ -17,10 +17,10 @@ public static class DependencyInjection
this IApplicationBuilder app,
CancellationToken cancellationToken = default)
{
var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
using var scope = scopeFactory.CreateScope();
await using var context = scope.ServiceProvider.GetRequiredService<MessagingDbContext>();
await context.Database.MigrateAsync(cancellationToken: cancellationToken);
IServiceScopeFactory scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
using IServiceScope scope = scopeFactory.CreateScope();
await using MessagingDbContext context = scope.ServiceProvider.GetRequiredService<MessagingDbContext>();
await context.Database.MigrateAsync(cancellationToken);
return app;
}

View File

@@ -40,7 +40,7 @@ public class AddMessage(
AddMessageRequest req,
CancellationToken ct)
{
var message = new Message
Message message = new()
{
Id = req.Id ?? Guid.CreateVersion7(),
SubjectId = req.SubjectId,

View File

@@ -45,7 +45,7 @@ internal sealed class AddReply(
AddReplyRequest req,
CancellationToken ct)
{
var message = new Message
Message message = new()
{
Id = Guid.CreateVersion7(),
SubjectId = req.SubjectId,

View File

@@ -39,7 +39,7 @@ public class ChangeMessage(
ChangeMessageRequest req,
CancellationToken ct)
{
var message = await context.Messages.FirstOrDefaultAsync(x => x.Id == req.Id, ct);
Message? message = await context.Messages.FirstOrDefaultAsync(x => x.Id == req.Id, ct);
if (message is null)
{
@@ -47,7 +47,7 @@ public class ChangeMessage(
return;
}
var userId = HttpContext.User.GetUserId();
Guid userId = HttpContext.User.GetUserId();
if (message.CreatedBy != userId)
{
await SendForbiddenAsync(ct);

View File

@@ -30,7 +30,7 @@ public class DeleteMessage(
DeleteMessageRequest req,
CancellationToken ct)
{
var message = await context.Messages.FirstOrDefaultAsync(x => x.Id == req.MessageId, ct);
Message? message = await context.Messages.FirstOrDefaultAsync(x => x.Id == req.MessageId, ct);
if (message is null)
{
@@ -38,7 +38,7 @@ public class DeleteMessage(
return;
}
var userId = HttpContext.User.GetUserId();
Guid userId = HttpContext.User.GetUserId();
if (message.CreatedBy != userId)
{
await SendForbiddenAsync(ct);

View File

@@ -28,17 +28,14 @@ public class GetMessageCount(
GetMessageCountRequest req,
CancellationToken ct)
{
var messageCount = await context.GetMessageCountAsync(
int messageCount = await context.GetMessageCountAsync(
req.SubjectId,
null,
req.PageSize,
ct);
await SendAsync(
new()
{
Count = messageCount
},
new GetMessageCountResponse { Count = messageCount },
cancellation: ct);
}
}

View File

@@ -30,7 +30,7 @@ public class GetMessages(
GetMessagesRequest req,
CancellationToken ct)
{
var messages = await context.GetMessagesAsync(
IEnumerable<MessageDto> messages = await context.GetMessagesAsync(
req.SubjectId,
null,
req.LastId,

View File

@@ -30,16 +30,16 @@ public class GetMessagesByUser(
GetMessagesByUserRequest req,
CancellationToken ct)
{
var messages = await context
List<Message> messages = await context
.Messages
.Where(c => c.CreatedBy == req.UserId)
.Where(c => c.ParentId == null)
.ToListAsync(cancellationToken: ct);
.ToListAsync(ct);
var result = await Task.WhenAll(
MessageDto[] result = await Task.WhenAll(
messages.Select(async message =>
{
var user = await userLookup.GetUserAsync(message.CreatedBy, ct);
UserReference? user = await userLookup.GetUserAsync(message.CreatedBy, ct);
return new MessageDto
{

View File

@@ -31,7 +31,7 @@ public class GetReplies(
GetRepliesRequest req,
CancellationToken ct)
{
var replies = await context.GetMessagesAsync(
IEnumerable<MessageDto> replies = await context.GetMessagesAsync(
req.SubjectId,
req.ParentId,
req.LastId,

View File

@@ -17,5 +17,5 @@ public class Tip : Entity
public enum TipStatus : short
{
Pending = 0,
Paid = 1,
Paid = 1
}

View File

@@ -21,10 +21,10 @@ public static class DependencyInjection
this IApplicationBuilder app,
CancellationToken cancellationToken = default)
{
var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
using var scope = scopeFactory.CreateScope();
await using var context = scope.ServiceProvider.GetRequiredService<MessagingDbContext>();
await context.Database.MigrateAsync(cancellationToken: cancellationToken);
IServiceScopeFactory scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
using IServiceScope scope = scopeFactory.CreateScope();
await using MessagingDbContext context = scope.ServiceProvider.GetRequiredService<MessagingDbContext>();
await context.Database.MigrateAsync(cancellationToken);
return app;
}

View File

@@ -24,15 +24,15 @@ public class GetReceivedTipsHandler(
public override async Task HandleAsync(
CancellationToken ct)
{
var tips = await dbContext
List<Tip> tips = await dbContext
.Tips
.Where(tip => tip.CreatorId == User.GetUserId())
.ToListAsync(ct);
var result = await Task.WhenAll(
TipReceivedModel[] result = await Task.WhenAll(
tips.Select(async tip =>
{
var tipper = await userLookup.GetUserAsync(tip.CreatorId, ct);
UserReference? tipper = await userLookup.GetUserAsync(tip.CreatorId, ct);
return new TipReceivedModel(
tip.Id,

View File

@@ -18,13 +18,16 @@ using NSwag;
using NSwag.Generation.AspNetCore.Processors;
using NSwag.Generation.Processors.Security;
var builder = WebApplication.CreateBuilder(args);
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
if (!builder.Environment.IsDevelopment())
{
var vaultUri = Environment.GetEnvironmentVariable("VaultUri");
string? vaultUri = Environment.GetEnvironmentVariable("VaultUri");
if (vaultUri is null) throw new InvalidOperationException("Missing VaultUri configuration setting");
if (vaultUri is null)
{
throw new InvalidOperationException("Missing VaultUri configuration setting");
}
builder.Configuration.AddAzureKeyVault(new Uri(vaultUri), new DefaultAzureCredential());
}
@@ -60,15 +63,16 @@ builder.Services.AddOpenApiDocument((
Type = OpenApiSecuritySchemeType.ApiKey,
Name = "Authorization",
In = OpenApiSecurityApiKeyLocation.Header,
Description = "Type into the textbox: Bearer {your JWT token}.",
Description = "Type into the textbox: Bearer {your JWT token}."
});
configure.OperationProcessors.Add(new AspNetCoreOperationTagsProcessor());
configure.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("JWT"));
});
var postgresConnectionString = builder.Configuration.GetConnectionString("PostgresConnection")
?? throw new InvalidOperationException("Missing ConnectionStrings:PostgresConnection");
string postgresConnectionString = builder.Configuration.GetConnectionString("PostgresConnection")
?? throw new InvalidOperationException(
"Missing ConnectionStrings:PostgresConnection");
builder.Services.AddFastEndpoints();
builder.AddInfrastructureModule();
@@ -84,10 +88,9 @@ builder.AddContentModule(options =>
options.UseNpgsql(
postgresConnectionString,
o => o.MigrationsHistoryTable("__EFMigrationsHistory", ContentsDbContext.SchemaName)));
builder.AddMembershipModule(
options => options.UseNpgsql(
postgresConnectionString,
o => o.MigrationsHistoryTable("__EFMigrationsHistory", MembershipsDbContext.SchemaName)));
builder.AddMembershipModule(options => options.UseNpgsql(
postgresConnectionString,
o => o.MigrationsHistoryTable("__EFMigrationsHistory", MembershipsDbContext.SchemaName)));
builder.AddTippingModule(options =>
options.UseNpgsql(
postgresConnectionString,
@@ -97,7 +100,7 @@ builder.AddMessagingModule(options =>
postgresConnectionString,
o => o.MigrationsHistoryTable("__EFMigrationsHistory", MessagingDbContext.SchemaName)));
var app = builder.Build();
WebApplication app = builder.Build();
app.UseForwardedHeaders(
new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedProto }

View File

@@ -1,7 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Custom Rules" ToolsVersion="16.0">
<Rules AnalyzerId="Microsoft.CodeAnalysis.CSharp" RuleNamespace="Microsoft.CodeAnalysis.CSharp">
<Rule Id="CS1591" Action="None" /> <!-- Missing XML comment -->
<Rule Id="SA1600" Action="None"/> <!-- Elements should be documented -->
<Rule Id="SA1633" Action="None"/> <!-- Missing File header comment -->
</Rules>
<Rules AnalyzerId="SonarAnalyzer.CSharp" RuleNamespace="SonarAnalyzer.CSharp">
<!-- <Rule Id="S1118" Action="Warning" /> Utility classes should not have public constructors -->