diff --git a/Endpoints/UserAccess.cs b/Endpoints/UserAccess.cs index d46e848..c71242a 100644 --- a/Endpoints/UserAccess.cs +++ b/Endpoints/UserAccess.cs @@ -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 +); \ No newline at end of file diff --git a/Program.cs b/Program.cs index b1efa7b..e257857 100644 --- a/Program.cs +++ b/Program.cs @@ -49,6 +49,10 @@ builder.Services.AddAuthorization(); var app = builder.Build(); + +await DatabaseHelper.InitDatabaseAsync(app); + + app.UseAuthentication(); app.UseAuthorization(); @@ -73,4 +77,16 @@ app.Run(); public sealed record RegisterDto(string Email, string Password); -public sealed record LoginDto(string Email, string Password); \ No newline at end of file +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(); + + await db.Database.EnsureCreatedAsync(); + } +} \ No newline at end of file diff --git a/appsettings.json b/appsettings.json index 2b17a11..056e9ef 100644 --- a/appsettings.json +++ b/appsettings.json @@ -9,4 +9,4 @@ } }, "AllowedHosts": "*" -} +} \ No newline at end of file