fix: add class context to all loggers, format
This commit is contained in:
parent
fb324e7576
commit
6c9d1c328b
16 changed files with 54 additions and 37 deletions
|
@ -9,11 +9,13 @@ namespace Foxnouns.Backend.Controllers.Authentication;
|
|||
[Route("/api/v2/auth")]
|
||||
public class AuthController(Config config, KeyCacheService keyCacheSvc, ILogger logger) : ApiControllerBase
|
||||
{
|
||||
private readonly ILogger _logger = logger.ForContext<AuthController>();
|
||||
|
||||
[HttpPost("urls")]
|
||||
[ProducesResponseType<UrlsResponse>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> UrlsAsync()
|
||||
{
|
||||
logger.Debug("Generating auth URLs for Discord: {Discord}, Google: {Google}, Tumblr: {Tumblr}",
|
||||
_logger.Debug("Generating auth URLs for Discord: {Discord}, Google: {Google}, Tumblr: {Tumblr}",
|
||||
config.DiscordAuth.Enabled,
|
||||
config.GoogleAuth.Enabled,
|
||||
config.TumblrAuth.Enabled);
|
||||
|
|
|
@ -20,6 +20,8 @@ public class DiscordAuthController(
|
|||
RemoteAuthService remoteAuthSvc,
|
||||
UserRendererService userRendererSvc) : ApiControllerBase
|
||||
{
|
||||
private readonly ILogger _logger = logger.ForContext<DiscordAuthController>();
|
||||
|
||||
[HttpPost("callback")]
|
||||
// TODO: duplicating attribute doesn't work, find another way to mark both as possible response
|
||||
// leaving it here for documentation purposes
|
||||
|
@ -34,7 +36,7 @@ public class DiscordAuthController(
|
|||
var user = await authSvc.AuthenticateUserAsync(AuthType.Discord, remoteUser.Id);
|
||||
if (user != null) return Ok(await GenerateUserTokenAsync(user));
|
||||
|
||||
logger.Debug("Discord user {Username} ({Id}) authenticated with no local account", remoteUser.Username,
|
||||
_logger.Debug("Discord user {Username} ({Id}) authenticated with no local account", remoteUser.Username,
|
||||
remoteUser.Id);
|
||||
|
||||
var ticket = AuthUtils.RandomToken();
|
||||
|
@ -51,7 +53,7 @@ public class DiscordAuthController(
|
|||
if (remoteUser == null) throw new ApiError.BadRequest("Invalid ticket", "ticket", req.Ticket);
|
||||
if (await db.AuthMethods.AnyAsync(a => a.AuthType == AuthType.Discord && a.RemoteId == remoteUser.Id))
|
||||
{
|
||||
logger.Error("Discord user {Id} has valid ticket but is already linked to an existing account",
|
||||
_logger.Error("Discord user {Id} has valid ticket but is already linked to an existing account",
|
||||
remoteUser.Id);
|
||||
throw new FoxnounsError("Discord ticket was issued for user with existing link");
|
||||
}
|
||||
|
@ -65,13 +67,13 @@ public class DiscordAuthController(
|
|||
private async Task<AuthController.AuthResponse> GenerateUserTokenAsync(User user)
|
||||
{
|
||||
var frontendApp = await db.GetFrontendApplicationAsync();
|
||||
logger.Debug("Logging user {Id} in with Discord", user.Id);
|
||||
_logger.Debug("Logging user {Id} in with Discord", user.Id);
|
||||
|
||||
var (tokenStr, token) =
|
||||
authSvc.GenerateToken(user, frontendApp, ["*"], clock.GetCurrentInstant() + Duration.FromDays(365));
|
||||
db.Add(token);
|
||||
|
||||
logger.Debug("Generated token {TokenId} for {UserId}", user.Id, token.Id);
|
||||
_logger.Debug("Generated token {TokenId} for {UserId}", user.Id, token.Id);
|
||||
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
|
|
|
@ -13,6 +13,8 @@ public class EmailAuthController(
|
|||
IClock clock,
|
||||
ILogger logger) : ApiControllerBase
|
||||
{
|
||||
private readonly ILogger _logger = logger.ForContext<EmailAuthController>();
|
||||
|
||||
[HttpPost("login")]
|
||||
[ProducesResponseType<AuthController.AuthResponse>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> LoginAsync([FromBody] LoginRequest req)
|
||||
|
@ -23,13 +25,13 @@ public class EmailAuthController(
|
|||
|
||||
var frontendApp = await db.GetFrontendApplicationAsync();
|
||||
|
||||
logger.Debug("Logging user {Id} in with email and password", user.Id);
|
||||
_logger.Debug("Logging user {Id} in with email and password", user.Id);
|
||||
|
||||
var (tokenStr, token) =
|
||||
authSvc.GenerateToken(user, frontendApp, ["*"], clock.GetCurrentInstant() + Duration.FromDays(365));
|
||||
db.Add(token);
|
||||
|
||||
logger.Debug("Generated token {TokenId} for {UserId}", user.Id, token.Id);
|
||||
_logger.Debug("Generated token {TokenId} for {UserId}", token.Id, user.Id);
|
||||
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
|
|
|
@ -14,11 +14,13 @@ public class DebugController(
|
|||
IClock clock,
|
||||
ILogger logger) : ApiControllerBase
|
||||
{
|
||||
private readonly ILogger _logger = logger.ForContext<DebugController>();
|
||||
|
||||
[HttpPost("users")]
|
||||
[ProducesResponseType<AuthController.AuthResponse>(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> CreateUserAsync([FromBody] CreateUserRequest req)
|
||||
{
|
||||
logger.Debug("Creating user with username {Username} and email {Email}", req.Username, req.Email);
|
||||
_logger.Debug("Creating user with username {Username} and email {Email}", req.Username, req.Email);
|
||||
|
||||
var user = await authSvc.CreateUserWithPasswordAsync(req.Username, req.Email, req.Password);
|
||||
var frontendApp = await db.GetFrontendApplicationAsync();
|
||||
|
|
|
@ -49,7 +49,8 @@ public static class DatabaseQueryExtensions
|
|||
throw new ApiError.NotFound("No member with that ID found.", code: ErrorCode.MemberNotFound);
|
||||
}
|
||||
|
||||
public static async Task<Member> ResolveMemberAsync(this DatabaseContext context, string userRef, string memberRef, Token? token)
|
||||
public static async Task<Member> ResolveMemberAsync(this DatabaseContext context, string userRef, string memberRef,
|
||||
Token? token)
|
||||
{
|
||||
var user = await context.ResolveUserAsync(userRef, token);
|
||||
return await context.ResolveMemberAsync(user.Id, memberRef);
|
||||
|
|
|
@ -39,7 +39,7 @@ public class User : BaseModel
|
|||
public required string Tooltip { get; set; }
|
||||
public bool Muted { get; set; }
|
||||
public bool Favourite { get; set; }
|
||||
|
||||
|
||||
// This type is generally serialized directly, so the converter is applied here.
|
||||
[JsonConverter(typeof(ScreamingSnakeCaseEnumConverter))]
|
||||
public PreferenceSize Size { get; set; }
|
||||
|
|
|
@ -97,7 +97,7 @@ public static class WebApplicationExtensions
|
|||
// Transient jobs
|
||||
.AddTransient<MemberAvatarUpdateInvocable>()
|
||||
.AddTransient<UserAvatarUpdateInvocable>();
|
||||
|
||||
|
||||
if (!config.Logging.EnableMetrics)
|
||||
services.AddHostedService<BackgroundMetricsCollectionService>();
|
||||
|
||||
|
|
|
@ -6,31 +6,31 @@
|
|||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Coravel" Version="5.0.4" />
|
||||
<PackageReference Include="Coravel" Version="5.0.4"/>
|
||||
<PackageReference Include="EFCore.NamingConventions" Version="8.0.3"/>
|
||||
<PackageReference Include="EntityFrameworkCore.Exceptions.PostgreSQL" Version="8.1.2" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.7" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.7" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.7" />
|
||||
<PackageReference Include="EntityFrameworkCore.Exceptions.PostgreSQL" Version="8.1.2"/>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.7"/>
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.7"/>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.7"/>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.7">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Minio" Version="6.0.3" />
|
||||
<PackageReference Include="Minio" Version="6.0.3"/>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3"/>
|
||||
<PackageReference Include="NodaTime" Version="3.1.11"/>
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.4"/>
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime" Version="8.0.4"/>
|
||||
<PackageReference Include="Npgsql.Json.NET" Version="8.0.3" />
|
||||
<PackageReference Include="prometheus-net" Version="8.2.1" />
|
||||
<PackageReference Include="prometheus-net.AspNetCore" Version="8.2.1" />
|
||||
<PackageReference Include="Sentry.AspNetCore" Version="4.9.0" />
|
||||
<PackageReference Include="Serilog" Version="4.0.1" />
|
||||
<PackageReference Include="Npgsql.Json.NET" Version="8.0.3"/>
|
||||
<PackageReference Include="prometheus-net" Version="8.2.1"/>
|
||||
<PackageReference Include="prometheus-net.AspNetCore" Version="8.2.1"/>
|
||||
<PackageReference Include="Sentry.AspNetCore" Version="4.9.0"/>
|
||||
<PackageReference Include="Serilog" Version="4.0.1"/>
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1"/>
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Seq" Version="8.0.0" />
|
||||
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.5" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0"/>
|
||||
<PackageReference Include="Serilog.Sinks.Seq" Version="8.0.0"/>
|
||||
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.5"/>
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2"/>
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="SetSourceRevisionId" BeforeTargets="InitializeSourceControlInformation">
|
||||
|
|
|
@ -15,7 +15,7 @@ public static class FoxnounsMetrics
|
|||
|
||||
public static readonly Gauge UsersActiveDayCount =
|
||||
Metrics.CreateGauge("foxnouns_user_count_active_day", "Number of users active in the last day");
|
||||
|
||||
|
||||
public static readonly Gauge MemberCount =
|
||||
Metrics.CreateGauge("foxnouns_member_count", "Number of total members");
|
||||
|
||||
|
|
|
@ -1,2 +1,2 @@
|
|||
global using ILogger = Serilog.ILogger;
|
||||
global using Log = Serilog.Log;
|
||||
global using Log = Serilog.Log;
|
|
@ -21,7 +21,7 @@ public class UserAvatarUpdateInvocable(DatabaseContext db, ObjectStorageService
|
|||
private async Task UpdateUserAvatarAsync(Snowflake id, string newAvatar)
|
||||
{
|
||||
_logger.Debug("Updating avatar for user {MemberId}", id);
|
||||
|
||||
|
||||
var user = await db.Users.FindAsync(id);
|
||||
if (user == null)
|
||||
{
|
||||
|
@ -55,7 +55,7 @@ public class UserAvatarUpdateInvocable(DatabaseContext db, ObjectStorageService
|
|||
private async Task ClearUserAvatarAsync(Snowflake id)
|
||||
{
|
||||
_logger.Debug("Clearing avatar for user {MemberId}", id);
|
||||
|
||||
|
||||
var user = await db.Users.FindAsync(id);
|
||||
if (user == null)
|
||||
{
|
||||
|
|
|
@ -110,6 +110,7 @@ public record HttpApiError
|
|||
|
||||
[JsonConverter(typeof(ScreamingSnakeCaseEnumConverter))]
|
||||
public required ErrorCode Code { get; init; }
|
||||
|
||||
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
|
||||
public string? ErrorId { get; init; }
|
||||
|
||||
|
|
|
@ -9,6 +9,8 @@ namespace Foxnouns.Backend.Services;
|
|||
|
||||
public class KeyCacheService(DatabaseContext db, IClock clock, ILogger logger)
|
||||
{
|
||||
private readonly ILogger _logger = logger.ForContext<KeyCacheService>();
|
||||
|
||||
public Task SetKeyAsync(string key, string value, Duration expireAfter) =>
|
||||
SetKeyAsync(key, value, clock.GetCurrentInstant() + expireAfter);
|
||||
|
||||
|
@ -40,7 +42,7 @@ public class KeyCacheService(DatabaseContext db, IClock clock, ILogger logger)
|
|||
public async Task DeleteExpiredKeysAsync(CancellationToken ct)
|
||||
{
|
||||
var count = await db.TemporaryKeys.Where(k => k.Expires < clock.GetCurrentInstant()).ExecuteDeleteAsync(ct);
|
||||
if (count != 0) logger.Information("Removed {Count} expired keys from the database", count);
|
||||
if (count != 0) _logger.Information("Removed {Count} expired keys from the database", count);
|
||||
}
|
||||
|
||||
public Task SetKeyAsync<T>(string key, T obj, Duration expiresAt) where T : class =>
|
||||
|
|
|
@ -7,21 +7,25 @@ namespace Foxnouns.Backend.Services;
|
|||
public class ObjectStorageService(ILogger logger, Config config, IMinioClient minio)
|
||||
{
|
||||
private readonly ILogger _logger = logger.ForContext<ObjectStorageService>();
|
||||
|
||||
|
||||
public async Task RemoveObjectAsync(string path)
|
||||
{
|
||||
logger.Debug("Deleting object at path {Path}", path);
|
||||
_logger.Debug("Deleting object at path {Path}", path);
|
||||
try
|
||||
{
|
||||
await minio.RemoveObjectAsync(new RemoveObjectArgs().WithBucket(config.Storage.Bucket).WithObject(path));
|
||||
}
|
||||
catch (InvalidObjectNameException)
|
||||
{
|
||||
// ignore non-existent objects
|
||||
}
|
||||
}
|
||||
|
||||
public async Task PutObjectAsync(string path, Stream data, string contentType)
|
||||
{
|
||||
_logger.Debug("Putting object at path {Path} with length {Length} and content type {ContentType}", path,
|
||||
data.Length, contentType);
|
||||
|
||||
await minio.PutObjectAsync(new PutObjectArgs()
|
||||
.WithBucket(config.Storage.Bucket)
|
||||
.WithObject(path)
|
||||
|
|
|
@ -17,7 +17,7 @@ public class PeriodicTasksService(ILogger logger, IServiceProvider services) : B
|
|||
private async Task RunPeriodicTasksAsync(CancellationToken ct)
|
||||
{
|
||||
_logger.Debug("Running periodic tasks");
|
||||
|
||||
|
||||
await using var scope = services.CreateAsyncScope();
|
||||
|
||||
var keyCacheSvc = scope.ServiceProvider.GetRequiredService<KeyCacheService>();
|
||||
|
|
|
@ -120,7 +120,6 @@ public static class ValidationUtils
|
|||
}
|
||||
|
||||
|
||||
|
||||
private static readonly string[] DefaultStatusOptions =
|
||||
[
|
||||
"favourite",
|
||||
|
@ -147,11 +146,13 @@ public static class ValidationUtils
|
|||
{
|
||||
case > Limits.FieldNameLimit:
|
||||
errors.Add(($"fields.{index}.name",
|
||||
ValidationError.LengthError("Field name is too long", 1, Limits.FieldNameLimit, field.Name.Length)));
|
||||
ValidationError.LengthError("Field name is too long", 1, Limits.FieldNameLimit,
|
||||
field.Name.Length)));
|
||||
break;
|
||||
case < 1:
|
||||
errors.Add(($"fields.{index}.name",
|
||||
ValidationError.LengthError("Field name is too short", 1, Limits.FieldNameLimit, field.Name.Length)));
|
||||
ValidationError.LengthError("Field name is too short", 1, Limits.FieldNameLimit,
|
||||
field.Name.Length)));
|
||||
break;
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue