Skip to content

Commit

Permalink
Added user info to serilog
Browse files Browse the repository at this point in the history
  • Loading branch information
HeDo88TH committed Nov 26, 2024
1 parent d578601 commit 2cfa8c7
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
48 changes: 48 additions & 0 deletions Registry.Web/Middlewares/UserEnrichmentMiddleware.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Registry.Web.Identity;
using Serilog.Context;

namespace Registry.Web.Middlewares;

public class UserEnrichmentMiddleware : IMiddleware
{
private readonly ApplicationDbContext _dbContext;

public UserEnrichmentMiddleware(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}

public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
// Get user ID from the claims
var userIdClaim = context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;

if (userIdClaim != null)
{
// Enrich Serilog with the user ID
LogContext.PushProperty("UserId", userIdClaim);

// Get admin claim
var isAdmin = context.User.Claims.Any(c => c.Type == "admin" && c.Value == "true");

if (isAdmin)
{
LogContext.PushProperty("IsAdmin", true);
}

var user = await _dbContext.Users.FindAsync(userIdClaim);
if (user != null)
{
LogContext.PushProperty("UserName", user.UserName);
}
}

// Call the next middleware in the pipeline
await next(context);
}
}
2 changes: 2 additions & 0 deletions Registry.Web/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ public void ConfigureServices(IServiceCollection services)

services.AddTransient<TokenManagerMiddleware>();
services.AddTransient<JwtInCookieMiddleware>();
services.AddTransient<UserEnrichmentMiddleware>();
services.AddTransient<ITokenManager, TokenManager>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Expand Down Expand Up @@ -362,6 +363,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
app.UseResponseCaching();

app.UseMiddleware<TokenManagerMiddleware>();
app.UseMiddleware<UserEnrichmentMiddleware>();

app.UseHangfireDashboard(MagicStrings.HangFireUrl, new DashboardOptions
{
Expand Down

0 comments on commit 2cfa8c7

Please sign in to comment.