/me endpoint

This commit is contained in:
Goran 2026-01-20 19:32:45 +01:00
parent 30cb58e3f7
commit 9bbd2985c5
3 changed files with 59 additions and 2 deletions

View File

@ -18,6 +18,7 @@ public static class UserAccess
MapPostRegister(routes);
MapPostLogout(routes);
MapGetMe(routes);
MapGetUserById(routes);
}
@ -118,6 +119,39 @@ public static class UserAccess
private static void MapGetMe(IEndpointRouteBuilder routes)
{
routes.MapGet("/me", async (HttpContext context, ClaimsPrincipal user, AppDbContext db) =>
{
var id = user.FindFirstValue(ClaimTypes.NameIdentifier);
if (id is null)
{
context.Response.StatusCode = 401;
return;
}
var u = await db.Users
.AsNoTracking()
.Where(x => x.Id == id)
.Select(x => new PublicUserDto(
x.Id,
x.Email,
x.Name,
x.ProfilePicture
))
.FirstAsync();
context.Response.StatusCode = 200;
await context.Response.WriteAsync(JsonSerializer.Serialize(u));
}).RequireAuthorization();
}
private static void MapGetUserById(IEndpointRouteBuilder routes)
{
routes.MapGet("/user/{id}", async context =>
@ -130,3 +164,10 @@ public static class UserAccess
}
}
public sealed record PublicUserDto(
string Id,
string Name,
string Description,
string ProfilePicture
);

View File

@ -49,6 +49,10 @@ builder.Services.AddAuthorization();
var app = builder.Build();
await DatabaseHelper.InitDatabaseAsync(app);
app.UseAuthentication();
app.UseAuthorization();
@ -74,3 +78,15 @@ app.Run();
public sealed record RegisterDto(string Email, string Password);
public sealed record LoginDto(string Email, string Password);
static class DatabaseHelper
{
public static async Task InitDatabaseAsync(WebApplication app)
{
using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.EnsureCreatedAsync();
}
}