Initial commit
This commit is contained in:
9
MealPlan.Api/.dockerignore
Normal file
9
MealPlan.Api/.dockerignore
Normal file
@@ -0,0 +1,9 @@
|
||||
bin/
|
||||
obj/
|
||||
logs/
|
||||
*.user
|
||||
.vs/
|
||||
.idea/
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
appsettings.Development.json
|
||||
100
MealPlan.Api/Controllers/AuthController.cs
Normal file
100
MealPlan.Api/Controllers/AuthController.cs
Normal file
@@ -0,0 +1,100 @@
|
||||
using System.Security.Claims;
|
||||
using MealPlan.Api.DTOs.Auth;
|
||||
using MealPlan.Api.Services;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
|
||||
namespace MealPlan.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/auth")]
|
||||
public class AuthController : ControllerBase
|
||||
{
|
||||
private readonly IAuthService _authService;
|
||||
|
||||
public AuthController(IAuthService authService) => _authService = authService;
|
||||
|
||||
/// <summary>Creates a new user account and returns an access + refresh token pair.</summary>
|
||||
[HttpPost("register")]
|
||||
[AllowAnonymous]
|
||||
[EnableRateLimiting("login")]
|
||||
[ProducesResponseType(typeof(TokenResponseDto), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status409Conflict)]
|
||||
public async Task<IActionResult> Register([FromBody] RegisterRequestDto request, CancellationToken ct)
|
||||
{
|
||||
var result = await _authService.RegisterAsync(request, ct);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
var status = result.Error?.Contains("already exists", StringComparison.OrdinalIgnoreCase) == true
|
||||
? StatusCodes.Status409Conflict
|
||||
: StatusCodes.Status400BadRequest;
|
||||
return StatusCode(status, new { error = result.Error });
|
||||
}
|
||||
|
||||
return StatusCode(StatusCodes.Status201Created, result.Tokens);
|
||||
}
|
||||
|
||||
/// <summary>Authenticates a user and returns an access + refresh token pair.</summary>
|
||||
[HttpPost("login")]
|
||||
[AllowAnonymous]
|
||||
[EnableRateLimiting("login")]
|
||||
[ProducesResponseType(typeof(TokenResponseDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> Login([FromBody] LoginRequestDto request, CancellationToken ct)
|
||||
{
|
||||
var result = await _authService.LoginAsync(request, ct);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
return Unauthorized(new { error = result.Error });
|
||||
}
|
||||
|
||||
return Ok(result.Tokens);
|
||||
}
|
||||
|
||||
/// <summary>Rotates a refresh token and issues a fresh token pair.</summary>
|
||||
[HttpPost("refresh")]
|
||||
[AllowAnonymous]
|
||||
[ProducesResponseType(typeof(TokenResponseDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> Refresh([FromBody] RefreshRequestDto request, CancellationToken ct)
|
||||
{
|
||||
var result = await _authService.RefreshAsync(request.RefreshToken, ct);
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
return Unauthorized(new { error = result.Error });
|
||||
}
|
||||
|
||||
return Ok(result.Tokens);
|
||||
}
|
||||
|
||||
/// <summary>Revokes the supplied refresh token. Always returns 204.</summary>
|
||||
[HttpPost("logout")]
|
||||
[AllowAnonymous]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
public IActionResult Logout([FromBody] RefreshRequestDto request)
|
||||
{
|
||||
_authService.Logout(request.RefreshToken);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
/// <summary>Returns the currently authenticated user's profile.</summary>
|
||||
[HttpGet("me")]
|
||||
[Authorize]
|
||||
[ProducesResponseType(typeof(UserInfoDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||
public async Task<IActionResult> Me(CancellationToken ct)
|
||||
{
|
||||
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier)
|
||||
?? User.FindFirstValue("sub");
|
||||
|
||||
if (string.IsNullOrEmpty(userId))
|
||||
{
|
||||
return Unauthorized();
|
||||
}
|
||||
|
||||
var info = await _authService.GetUserInfoAsync(userId, ct);
|
||||
return info is null ? Unauthorized() : Ok(info);
|
||||
}
|
||||
}
|
||||
54
MealPlan.Api/Controllers/RecipesController.cs
Normal file
54
MealPlan.Api/Controllers/RecipesController.cs
Normal file
@@ -0,0 +1,54 @@
|
||||
using MealPlan.Api.DTOs.Recipe;
|
||||
using MealPlan.Api.Services;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace MealPlan.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/recipes")]
|
||||
[Authorize]
|
||||
public class RecipesController : ControllerBase
|
||||
{
|
||||
private readonly IRecipeService _recipeService;
|
||||
|
||||
public RecipesController(IRecipeService recipeService) => _recipeService = recipeService;
|
||||
|
||||
/// <summary>Lists active recipes, optionally filtered by category and/or name search.</summary>
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(IReadOnlyList<RecipeListItemDto>), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> GetRecipes(
|
||||
[FromQuery] int? category,
|
||||
[FromQuery] string? search,
|
||||
CancellationToken ct)
|
||||
{
|
||||
if (category is < 0 or > 3)
|
||||
{
|
||||
return BadRequest(new { error = "category must be between 0 and 3." });
|
||||
}
|
||||
|
||||
var recipes = await _recipeService.GetRecipesAsync(category, search, ct);
|
||||
return Ok(recipes);
|
||||
}
|
||||
|
||||
/// <summary>Returns category metadata with active recipe counts.</summary>
|
||||
[HttpGet("categories")]
|
||||
[ProducesResponseType(typeof(IReadOnlyList<CategoryCountDto>), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> GetCategories(CancellationToken ct)
|
||||
{
|
||||
var categories = await _recipeService.GetCategoriesAsync(ct);
|
||||
return Ok(categories);
|
||||
}
|
||||
|
||||
/// <summary>Returns a single recipe with ingredients and ordered steps.</summary>
|
||||
[HttpGet("{id:int}")]
|
||||
[ProducesResponseType(typeof(RecipeDetailDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetRecipe(int id, CancellationToken ct)
|
||||
{
|
||||
var recipe = await _recipeService.GetRecipeByIdAsync(id, ct);
|
||||
return recipe is null
|
||||
? NotFound(new { error = $"Recipe {id} was not found." })
|
||||
: Ok(recipe);
|
||||
}
|
||||
}
|
||||
16
MealPlan.Api/DTOs/Auth/LoginRequestDto.cs
Normal file
16
MealPlan.Api/DTOs/Auth/LoginRequestDto.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace MealPlan.Api.DTOs.Auth;
|
||||
|
||||
/// <summary>Credentials submitted to <c>POST /api/auth/login</c>.</summary>
|
||||
public class LoginRequestDto
|
||||
{
|
||||
[Required]
|
||||
[EmailAddress]
|
||||
[MaxLength(256)]
|
||||
public string Email { get; set; } = string.Empty;
|
||||
|
||||
[Required]
|
||||
[MaxLength(256)]
|
||||
public string Password { get; set; } = string.Empty;
|
||||
}
|
||||
10
MealPlan.Api/DTOs/Auth/RefreshRequestDto.cs
Normal file
10
MealPlan.Api/DTOs/Auth/RefreshRequestDto.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace MealPlan.Api.DTOs.Auth;
|
||||
|
||||
/// <summary>Body for <c>POST /api/auth/refresh</c> and <c>POST /api/auth/logout</c>.</summary>
|
||||
public class RefreshRequestDto
|
||||
{
|
||||
[Required]
|
||||
public string RefreshToken { get; set; } = string.Empty;
|
||||
}
|
||||
20
MealPlan.Api/DTOs/Auth/RegisterRequestDto.cs
Normal file
20
MealPlan.Api/DTOs/Auth/RegisterRequestDto.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace MealPlan.Api.DTOs.Auth;
|
||||
|
||||
/// <summary>Payload for <c>POST /api/auth/register</c>.</summary>
|
||||
public class RegisterRequestDto
|
||||
{
|
||||
[Required]
|
||||
[EmailAddress]
|
||||
[MaxLength(256)]
|
||||
public string Email { get; set; } = string.Empty;
|
||||
|
||||
[MaxLength(256)]
|
||||
public string? UserName { get; set; }
|
||||
|
||||
[Required]
|
||||
[MinLength(8)]
|
||||
[MaxLength(256)]
|
||||
public string Password { get; set; } = string.Empty;
|
||||
}
|
||||
13
MealPlan.Api/DTOs/Auth/TokenResponseDto.cs
Normal file
13
MealPlan.Api/DTOs/Auth/TokenResponseDto.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
namespace MealPlan.Api.DTOs.Auth;
|
||||
|
||||
/// <summary>Token pair returned by login and refresh.</summary>
|
||||
public class TokenResponseDto
|
||||
{
|
||||
public string AccessToken { get; set; } = string.Empty;
|
||||
public string RefreshToken { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Access-token lifetime in seconds (clients use it to schedule silent refresh).</summary>
|
||||
public int ExpiresInSeconds { get; set; }
|
||||
|
||||
public string TokenType { get; set; } = "Bearer";
|
||||
}
|
||||
9
MealPlan.Api/DTOs/Auth/UserInfoDto.cs
Normal file
9
MealPlan.Api/DTOs/Auth/UserInfoDto.cs
Normal file
@@ -0,0 +1,9 @@
|
||||
namespace MealPlan.Api.DTOs.Auth;
|
||||
|
||||
/// <summary>Current-user payload returned by <c>GET /api/auth/me</c>.</summary>
|
||||
public class UserInfoDto
|
||||
{
|
||||
public string Id { get; set; } = string.Empty;
|
||||
public string? UserName { get; set; }
|
||||
public string? Email { get; set; }
|
||||
}
|
||||
9
MealPlan.Api/DTOs/Recipe/CategoryCountDto.cs
Normal file
9
MealPlan.Api/DTOs/Recipe/CategoryCountDto.cs
Normal file
@@ -0,0 +1,9 @@
|
||||
namespace MealPlan.Api.DTOs.Recipe;
|
||||
|
||||
/// <summary>Category metadata with the number of active recipes it contains.</summary>
|
||||
public class CategoryCountDto
|
||||
{
|
||||
public int Category { get; set; }
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public int Count { get; set; }
|
||||
}
|
||||
33
MealPlan.Api/DTOs/Recipe/RecipeDetailDto.cs
Normal file
33
MealPlan.Api/DTOs/Recipe/RecipeDetailDto.cs
Normal file
@@ -0,0 +1,33 @@
|
||||
namespace MealPlan.Api.DTOs.Recipe;
|
||||
|
||||
/// <summary>Full recipe detail including ingredients and ordered preparation steps.</summary>
|
||||
public class RecipeDetailDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public int MealCategory { get; set; }
|
||||
public int? Calories { get; set; }
|
||||
public decimal? Protein { get; set; }
|
||||
public decimal? Fat { get; set; }
|
||||
public decimal? Carbs { get; set; }
|
||||
public int? PrepTimeMinutes { get; set; }
|
||||
|
||||
public List<IngredientDto> Ingredients { get; set; } = new();
|
||||
public List<RecipeStepDto> Steps { get; set; } = new();
|
||||
}
|
||||
|
||||
public class IngredientDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public decimal? AmountGrams { get; set; }
|
||||
public string? Unit { get; set; }
|
||||
public int SortOrder { get; set; }
|
||||
}
|
||||
|
||||
public class RecipeStepDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public int StepNumber { get; set; }
|
||||
public string Description { get; set; } = string.Empty;
|
||||
}
|
||||
11
MealPlan.Api/DTOs/Recipe/RecipeListItemDto.cs
Normal file
11
MealPlan.Api/DTOs/Recipe/RecipeListItemDto.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
namespace MealPlan.Api.DTOs.Recipe;
|
||||
|
||||
/// <summary>Lightweight recipe projection used by list/grid views.</summary>
|
||||
public class RecipeListItemDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public int MealCategory { get; set; }
|
||||
public int? Calories { get; set; }
|
||||
public int? PrepTimeMinutes { get; set; }
|
||||
}
|
||||
65
MealPlan.Api/Data/AppDbContext.cs
Normal file
65
MealPlan.Api/Data/AppDbContext.cs
Normal file
@@ -0,0 +1,65 @@
|
||||
using MealPlan.Api.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace MealPlan.Api.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Database-first context for the existing PostgreSQL database.
|
||||
/// Tables are mapped explicitly; this context never creates or alters schema.
|
||||
/// </summary>
|
||||
public class AppDbContext : DbContext
|
||||
{
|
||||
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
|
||||
{
|
||||
}
|
||||
|
||||
public DbSet<Recipe> Recipes => Set<Recipe>();
|
||||
public DbSet<Ingredient> Ingredients => Set<Ingredient>();
|
||||
public DbSet<RecipeStep> RecipeSteps => Set<RecipeStep>();
|
||||
public DbSet<ApplicationUser> Users => Set<ApplicationUser>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
base.OnModelCreating(modelBuilder);
|
||||
|
||||
modelBuilder.HasDefaultSchema("diet");
|
||||
|
||||
modelBuilder.Entity<Recipe>(e =>
|
||||
{
|
||||
e.HasKey(r => r.Id);
|
||||
e.Property(r => r.Id).UseIdentityByDefaultColumn();
|
||||
e.Property(r => r.Protein).HasColumnType("numeric(6,2)");
|
||||
e.Property(r => r.Fat).HasColumnType("numeric(6,2)");
|
||||
e.Property(r => r.Carbs).HasColumnType("numeric(6,2)");
|
||||
|
||||
e.HasMany(r => r.Ingredients)
|
||||
.WithOne(i => i.Recipe!)
|
||||
.HasForeignKey(i => i.RecipeId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
e.HasMany(r => r.Steps)
|
||||
.WithOne(s => s.Recipe!)
|
||||
.HasForeignKey(s => s.RecipeId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<Ingredient>(e =>
|
||||
{
|
||||
e.HasKey(i => i.Id);
|
||||
e.Property(i => i.Id).UseIdentityByDefaultColumn();
|
||||
e.Property(i => i.AmountGrams).HasColumnType("numeric(8,2)");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<RecipeStep>(e =>
|
||||
{
|
||||
e.HasKey(s => s.Id);
|
||||
e.Property(s => s.Id).UseIdentityByDefaultColumn();
|
||||
});
|
||||
|
||||
modelBuilder.Entity<ApplicationUser>(e =>
|
||||
{
|
||||
e.HasKey(u => u.Id);
|
||||
e.Property(u => u.Id).HasColumnType("uuid");
|
||||
});
|
||||
}
|
||||
}
|
||||
27
MealPlan.Api/Dockerfile
Normal file
27
MealPlan.Api/Dockerfile
Normal file
@@ -0,0 +1,27 @@
|
||||
# ---------- Build stage ----------
|
||||
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
|
||||
WORKDIR /src
|
||||
|
||||
# Restore first to leverage Docker layer caching.
|
||||
COPY ["MealPlan.Api.csproj", "./"]
|
||||
RUN dotnet restore "MealPlan.Api.csproj"
|
||||
|
||||
COPY . .
|
||||
RUN dotnet publish "MealPlan.Api.csproj" -c Release -o /app/publish /p:UseAppHost=false
|
||||
|
||||
# ---------- Runtime stage ----------
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final
|
||||
WORKDIR /app
|
||||
|
||||
# Run as the non-root user shipped in the aspnet image.
|
||||
USER $APP_UID
|
||||
|
||||
ENV ASPNETCORE_URLS=http://+:5000 \
|
||||
ASPNETCORE_ENVIRONMENT=Production \
|
||||
DOTNET_RUNNING_IN_CONTAINER=true
|
||||
|
||||
EXPOSE 5000
|
||||
|
||||
COPY --from=build /app/publish .
|
||||
|
||||
ENTRYPOINT ["dotnet", "MealPlan.Api.dll"]
|
||||
28
MealPlan.Api/MealPlan.Api.csproj
Normal file
28
MealPlan.Api/MealPlan.Api.csproj
Normal file
@@ -0,0 +1,28 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>MealPlan.Api</RootNamespace>
|
||||
<AssemblyName>MealPlan.Api</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.8" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.3.1" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.8" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.8">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.8" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="8.0.2" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
62
MealPlan.Api/Middleware/ExceptionMiddleware.cs
Normal file
62
MealPlan.Api/Middleware/ExceptionMiddleware.cs
Normal file
@@ -0,0 +1,62 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace MealPlan.Api.Middleware;
|
||||
|
||||
/// <summary>
|
||||
/// Converts unhandled exceptions into RFC-7807-style JSON problem responses and logs them.
|
||||
/// Internal details are never leaked to the client.
|
||||
/// </summary>
|
||||
public class ExceptionMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly ILogger<ExceptionMiddleware> _logger;
|
||||
|
||||
public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
|
||||
{
|
||||
_next = next;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _next(context);
|
||||
}
|
||||
catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)
|
||||
{
|
||||
// Client disconnected; nothing actionable to report.
|
||||
_logger.LogDebug("Request {Path} was cancelled by the client", context.Request.Path);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Unhandled exception for {Method} {Path}",
|
||||
context.Request.Method, context.Request.Path);
|
||||
|
||||
if (context.Response.HasStarted)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
|
||||
context.Response.Clear();
|
||||
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
||||
context.Response.ContentType = "application/problem+json";
|
||||
|
||||
var payload = new
|
||||
{
|
||||
type = "https://httpstatuses.io/500",
|
||||
title = "An unexpected error occurred.",
|
||||
status = StatusCodes.Status500InternalServerError,
|
||||
traceId = context.TraceIdentifier,
|
||||
};
|
||||
|
||||
await context.Response.WriteAsync(JsonSerializer.Serialize(payload));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class ExceptionMiddlewareExtensions
|
||||
{
|
||||
public static IApplicationBuilder UseExceptionMiddleware(this IApplicationBuilder app) =>
|
||||
app.UseMiddleware<ExceptionMiddleware>();
|
||||
}
|
||||
32
MealPlan.Api/Models/ApplicationUser.cs
Normal file
32
MealPlan.Api/Models/ApplicationUser.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace MealPlan.Api.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Maps to the existing ASP.NET Core Identity "AspNetUsers" table.
|
||||
/// Only the columns described in the schema are mapped. Password verification uses
|
||||
/// ASP.NET Core Identity's <see cref="Microsoft.AspNetCore.Identity.IPasswordHasher{TUser}"/>,
|
||||
/// so no additional Identity tables are required for this read-only login flow.
|
||||
/// </summary>
|
||||
[Table("AspNetUsers")]
|
||||
public class ApplicationUser
|
||||
{
|
||||
[Column("Id")]
|
||||
public Guid Id { get; set; }
|
||||
|
||||
[Column("UserName")]
|
||||
public string? UserName { get; set; }
|
||||
|
||||
[Column("Email")]
|
||||
public string? Email { get; set; }
|
||||
|
||||
[Column("PasswordHash")]
|
||||
public string? PasswordHash { get; set; }
|
||||
|
||||
[Column("CreatedAt")]
|
||||
public DateTime CreatedAt { get; set; }
|
||||
|
||||
[Column("IsActive")]
|
||||
public bool IsActive { get; set; }
|
||||
}
|
||||
33
MealPlan.Api/Models/Ingredient.cs
Normal file
33
MealPlan.Api/Models/Ingredient.cs
Normal file
@@ -0,0 +1,33 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace MealPlan.Api.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Maps to the existing "Ingredients" table.
|
||||
/// </summary>
|
||||
[Table("Ingredients")]
|
||||
public class Ingredient
|
||||
{
|
||||
[Column("Id")]
|
||||
public int Id { get; set; }
|
||||
|
||||
[Column("RecipeId")]
|
||||
public int RecipeId { get; set; }
|
||||
|
||||
[Column("Name")]
|
||||
[MaxLength(255)]
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
[Column("AmountGrams")]
|
||||
public decimal? AmountGrams { get; set; }
|
||||
|
||||
[Column("Unit")]
|
||||
[MaxLength(50)]
|
||||
public string? Unit { get; set; }
|
||||
|
||||
[Column("SortOrder")]
|
||||
public int SortOrder { get; set; }
|
||||
|
||||
public Recipe? Recipe { get; set; }
|
||||
}
|
||||
12
MealPlan.Api/Models/MealCategory.cs
Normal file
12
MealPlan.Api/Models/MealCategory.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
namespace MealPlan.Api.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Meal categories. Integer values map directly to the "MealCategory" column on "Recipes".
|
||||
/// </summary>
|
||||
public enum MealCategory
|
||||
{
|
||||
Breakfast = 0,
|
||||
SecondBreakfast = 1,
|
||||
Lunch = 2,
|
||||
Dinner = 3
|
||||
}
|
||||
49
MealPlan.Api/Models/Recipe.cs
Normal file
49
MealPlan.Api/Models/Recipe.cs
Normal file
@@ -0,0 +1,49 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace MealPlan.Api.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Maps to the existing "Recipes" table. Database-first; no migrations manage this table.
|
||||
/// </summary>
|
||||
[Table("Recipes")]
|
||||
public class Recipe
|
||||
{
|
||||
[Column("Id")]
|
||||
public int Id { get; set; }
|
||||
|
||||
[Column("Name")]
|
||||
[MaxLength(255)]
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Stored as INT in the DB (0..3). Mapped to the <see cref="MealCategory"/> enum.</summary>
|
||||
[Column("MealCategory")]
|
||||
public int MealCategory { get; set; }
|
||||
|
||||
[Column("Calories")]
|
||||
public int? Calories { get; set; }
|
||||
|
||||
[Column("Protein")]
|
||||
public decimal? Protein { get; set; }
|
||||
|
||||
[Column("Fat")]
|
||||
public decimal? Fat { get; set; }
|
||||
|
||||
[Column("Carbs")]
|
||||
public decimal? Carbs { get; set; }
|
||||
|
||||
[Column("PrepTimeMinutes")]
|
||||
public int? PrepTimeMinutes { get; set; }
|
||||
|
||||
[Column("CreatedAt")]
|
||||
public DateTime CreatedAt { get; set; }
|
||||
|
||||
[Column("UpdatedAt")]
|
||||
public DateTime? UpdatedAt { get; set; }
|
||||
|
||||
[Column("IsActive")]
|
||||
public bool IsActive { get; set; }
|
||||
|
||||
public ICollection<Ingredient> Ingredients { get; set; } = new List<Ingredient>();
|
||||
public ICollection<RecipeStep> Steps { get; set; } = new List<RecipeStep>();
|
||||
}
|
||||
24
MealPlan.Api/Models/RecipeStep.cs
Normal file
24
MealPlan.Api/Models/RecipeStep.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace MealPlan.Api.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Maps to the existing "RecipeSteps" table.
|
||||
/// </summary>
|
||||
[Table("RecipeSteps")]
|
||||
public class RecipeStep
|
||||
{
|
||||
[Column("Id")]
|
||||
public int Id { get; set; }
|
||||
|
||||
[Column("RecipeId")]
|
||||
public int RecipeId { get; set; }
|
||||
|
||||
[Column("StepNumber")]
|
||||
public int StepNumber { get; set; }
|
||||
|
||||
[Column("Description")]
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
public Recipe? Recipe { get; set; }
|
||||
}
|
||||
17
MealPlan.Api/Models/RefreshToken.cs
Normal file
17
MealPlan.Api/Models/RefreshToken.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
namespace MealPlan.Api.Models;
|
||||
|
||||
/// <summary>
|
||||
/// In-memory refresh token record. Stored in a singleton store rather than the database,
|
||||
/// because the existing schema must not be modified and no migrations may be created.
|
||||
/// Rotation: every successful refresh invalidates the previous token and issues a new one.
|
||||
/// </summary>
|
||||
public class RefreshToken
|
||||
{
|
||||
public string Token { get; set; } = string.Empty;
|
||||
public string UserId { get; set; } = string.Empty;
|
||||
public DateTime ExpiresAtUtc { get; set; }
|
||||
public DateTime CreatedAtUtc { get; set; }
|
||||
public bool IsRevoked { get; set; }
|
||||
|
||||
public bool IsActive => !IsRevoked && DateTime.UtcNow < ExpiresAtUtc;
|
||||
}
|
||||
231
MealPlan.Api/Program.cs
Normal file
231
MealPlan.Api/Program.cs
Normal file
@@ -0,0 +1,231 @@
|
||||
using System.Text;
|
||||
using System.Threading.RateLimiting;
|
||||
using FluentValidation;
|
||||
using FluentValidation.AspNetCore;
|
||||
using MealPlan.Api.Data;
|
||||
using MealPlan.Api.Middleware;
|
||||
using MealPlan.Api.Models;
|
||||
using MealPlan.Api.Services;
|
||||
using MealPlan.Api.Validators;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Serilog;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Optional local overrides (connection string, secrets) — not committed; see appsettings.Local.json.example.
|
||||
builder.Configuration.AddJsonFile("appsettings.Local.json", optional: true, reloadOnChange: true);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Serilog: structured logging to console + rolling daily file.
|
||||
// ---------------------------------------------------------------------------
|
||||
builder.Host.UseSerilog((context, services, configuration) => configuration
|
||||
.ReadFrom.Configuration(context.Configuration)
|
||||
.ReadFrom.Services(services)
|
||||
.Enrich.FromLogContext()
|
||||
.WriteTo.Console()
|
||||
.WriteTo.File(
|
||||
path: "logs/mealplan-.log",
|
||||
rollingInterval: RollingInterval.Day,
|
||||
retainedFileCountLimit: 14,
|
||||
shared: true));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Configuration / options
|
||||
// ---------------------------------------------------------------------------
|
||||
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
|
||||
?? throw new InvalidOperationException(
|
||||
"ConnectionStrings__DefaultConnection is not configured.");
|
||||
|
||||
builder.Services.Configure<JwtOptions>(builder.Configuration.GetSection(JwtOptions.SectionName));
|
||||
var jwtOptions = builder.Configuration.GetSection(JwtOptions.SectionName).Get<JwtOptions>()
|
||||
?? throw new InvalidOperationException("Jwt configuration section is missing.");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(jwtOptions.Secret) || jwtOptions.Secret.Length < 32)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Jwt__Secret must be configured and at least 32 characters long.");
|
||||
}
|
||||
|
||||
var allowedOrigin = builder.Configuration["CORS:AllowedOrigin"];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// EF Core (PostgreSQL, database-first — no migrations)
|
||||
// ---------------------------------------------------------------------------
|
||||
builder.Services.AddDbContext<AppDbContext>(options =>
|
||||
options.UseNpgsql(connectionString, npgsql => npgsql.EnableRetryOnFailure()));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Application services
|
||||
// ---------------------------------------------------------------------------
|
||||
builder.Services.AddSingleton<IRefreshTokenStore, InMemoryRefreshTokenStore>();
|
||||
builder.Services.AddHostedService<RefreshTokenCleanupService>();
|
||||
builder.Services.AddSingleton<IPasswordHasher<ApplicationUser>, PasswordHasher<ApplicationUser>>();
|
||||
builder.Services.AddScoped<ITokenService, TokenService>();
|
||||
builder.Services.AddScoped<IAuthService, AuthService>();
|
||||
builder.Services.AddScoped<IRecipeService, RecipeService>();
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Authentication / authorization (JWT bearer)
|
||||
// ---------------------------------------------------------------------------
|
||||
builder.Services
|
||||
.AddAuthentication(options =>
|
||||
{
|
||||
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
})
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = jwtOptions.Issuer,
|
||||
ValidAudience = jwtOptions.Audience,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.Secret)),
|
||||
ClockSkew = TimeSpan.Zero,
|
||||
};
|
||||
});
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Rate limiting: max 5 login attempts per minute per client IP.
|
||||
// ---------------------------------------------------------------------------
|
||||
builder.Services.AddRateLimiter(options =>
|
||||
{
|
||||
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||
|
||||
options.AddPolicy("login", httpContext =>
|
||||
{
|
||||
var clientIp = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||
return RateLimitPartition.GetFixedWindowLimiter(clientIp, _ => new FixedWindowRateLimiterOptions
|
||||
{
|
||||
PermitLimit = 5,
|
||||
Window = TimeSpan.FromMinutes(1),
|
||||
QueueLimit = 0,
|
||||
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CORS: restricted to the configured frontend origin only.
|
||||
// ---------------------------------------------------------------------------
|
||||
const string corsPolicy = "frontend";
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy(corsPolicy, policy =>
|
||||
{
|
||||
if (builder.Environment.IsDevelopment())
|
||||
{
|
||||
// Vite may use 5173, 5174, 5175, etc. when ports are busy.
|
||||
policy.SetIsOriginAllowed(origin =>
|
||||
!string.IsNullOrEmpty(origin) &&
|
||||
Uri.TryCreate(origin, UriKind.Absolute, out var uri) &&
|
||||
(uri.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase) ||
|
||||
uri.Host.Equals("127.0.0.1", StringComparison.OrdinalIgnoreCase)))
|
||||
.AllowAnyHeader()
|
||||
.AllowAnyMethod();
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(allowedOrigin))
|
||||
{
|
||||
policy.WithOrigins(allowedOrigin)
|
||||
.AllowAnyHeader()
|
||||
.AllowAnyMethod();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Forwarded headers so the app honors the original scheme/IP behind the nginx proxy.
|
||||
builder.Services.Configure<ForwardedHeadersOptions>(options =>
|
||||
{
|
||||
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
|
||||
options.KnownNetworks.Clear();
|
||||
options.KnownProxies.Clear();
|
||||
});
|
||||
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddFluentValidationAutoValidation();
|
||||
builder.Services.AddFluentValidationClientsideAdapters();
|
||||
builder.Services.AddValidatorsFromAssemblyContaining<LoginRequestValidator>();
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
// Kestrel listens on 5000 (HTTP) inside the container; TLS is terminated at nginx.
|
||||
builder.WebHost.ConfigureKestrel(options => options.AddServerHeader = false);
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// HTTP request pipeline
|
||||
// ---------------------------------------------------------------------------
|
||||
app.UseForwardedHeaders();
|
||||
app.UseSerilogRequestLogging();
|
||||
app.UseExceptionMiddleware();
|
||||
|
||||
// Security headers on every response.
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
var headers = context.Response.Headers;
|
||||
headers["X-Frame-Options"] = "DENY";
|
||||
headers["X-Content-Type-Options"] = "nosniff";
|
||||
headers["Referrer-Policy"] = "no-referrer";
|
||||
headers["Content-Security-Policy"] =
|
||||
"default-src 'self'; frame-ancestors 'none'; base-uri 'self'; object-src 'none'";
|
||||
headers["X-Permitted-Cross-Domain-Policies"] = "none";
|
||||
await next();
|
||||
});
|
||||
|
||||
// Behind nginx, X-Forwarded-Proto makes HTTPS redirection work for the public URL.
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
if (app.Environment.IsProduction())
|
||||
{
|
||||
app.UseHsts();
|
||||
}
|
||||
else
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
|
||||
app.UseCors(corsPolicy);
|
||||
app.UseRateLimiter();
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
app.MapGet("/health", () => Results.Ok(new { status = "ok" })).AllowAnonymous();
|
||||
|
||||
try
|
||||
{
|
||||
Log.Information("Starting MealPlan API");
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
var authEndpoints = app.Services.GetRequiredService<Microsoft.AspNetCore.Routing.EndpointDataSource>()
|
||||
.Endpoints
|
||||
.OfType<Microsoft.AspNetCore.Routing.RouteEndpoint>()
|
||||
.Where(e => e.RoutePattern.RawText?.Contains("auth", StringComparison.OrdinalIgnoreCase) == true)
|
||||
.Select(e => e.RoutePattern.RawText)
|
||||
.Distinct()
|
||||
.OrderBy(x => x);
|
||||
Log.Information("Auth endpoints: {Endpoints}", string.Join(", ", authEndpoints));
|
||||
}
|
||||
|
||||
app.Run();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Fatal(ex, "MealPlan API terminated unexpectedly");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Log.CloseAndFlush();
|
||||
}
|
||||
14
MealPlan.Api/Properties/launchSettings.json
Normal file
14
MealPlan.Api/Properties/launchSettings.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "http://localhost:5000",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
17
MealPlan.Api/Services/AuthResult.cs
Normal file
17
MealPlan.Api/Services/AuthResult.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
using MealPlan.Api.DTOs.Auth;
|
||||
|
||||
namespace MealPlan.Api.Services;
|
||||
|
||||
/// <summary>Outcome of an auth operation. Avoids throwing for expected failures (bad credentials, etc.).</summary>
|
||||
public class AuthResult
|
||||
{
|
||||
public bool Succeeded { get; private init; }
|
||||
public string? Error { get; private init; }
|
||||
public TokenResponseDto? Tokens { get; private init; }
|
||||
|
||||
public static AuthResult Success(TokenResponseDto tokens) =>
|
||||
new() { Succeeded = true, Tokens = tokens };
|
||||
|
||||
public static AuthResult Fail(string error) =>
|
||||
new() { Succeeded = false, Error = error };
|
||||
}
|
||||
172
MealPlan.Api/Services/AuthService.cs
Normal file
172
MealPlan.Api/Services/AuthService.cs
Normal file
@@ -0,0 +1,172 @@
|
||||
using MealPlan.Api.Data;
|
||||
using MealPlan.Api.DTOs.Auth;
|
||||
using MealPlan.Api.Models;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace MealPlan.Api.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Read-only authentication against the existing "AspNetUsers" table.
|
||||
/// Password verification uses ASP.NET Core Identity's <see cref="IPasswordHasher{TUser}"/> so
|
||||
/// it is compatible with hashes produced by ASP.NET Core Identity.
|
||||
/// </summary>
|
||||
public class AuthService : IAuthService
|
||||
{
|
||||
private readonly AppDbContext _db;
|
||||
private readonly ITokenService _tokenService;
|
||||
private readonly IRefreshTokenStore _refreshTokenStore;
|
||||
private readonly IPasswordHasher<ApplicationUser> _passwordHasher;
|
||||
private readonly ILogger<AuthService> _logger;
|
||||
|
||||
public AuthService(
|
||||
AppDbContext db,
|
||||
ITokenService tokenService,
|
||||
IRefreshTokenStore refreshTokenStore,
|
||||
IPasswordHasher<ApplicationUser> passwordHasher,
|
||||
ILogger<AuthService> logger)
|
||||
{
|
||||
_db = db;
|
||||
_tokenService = tokenService;
|
||||
_refreshTokenStore = refreshTokenStore;
|
||||
_passwordHasher = passwordHasher;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<AuthResult> RegisterAsync(RegisterRequestDto request, CancellationToken ct = default)
|
||||
{
|
||||
var normalizedEmail = request.Email.Trim().ToLowerInvariant();
|
||||
|
||||
var emailTaken = await _db.Users
|
||||
.AsNoTracking()
|
||||
.AnyAsync(u => u.Email != null && u.Email.ToLower() == normalizedEmail, ct);
|
||||
|
||||
if (emailTaken)
|
||||
{
|
||||
return AuthResult.Fail("An account with this email already exists.");
|
||||
}
|
||||
|
||||
var user = new ApplicationUser
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Email = request.Email.Trim(),
|
||||
UserName = string.IsNullOrWhiteSpace(request.UserName)
|
||||
? request.Email.Trim()
|
||||
: request.UserName.Trim(),
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
IsActive = true,
|
||||
};
|
||||
|
||||
user.PasswordHash = _passwordHasher.HashPassword(user, request.Password);
|
||||
|
||||
_db.Users.Add(user);
|
||||
await _db.SaveChangesAsync(ct);
|
||||
|
||||
_logger.LogInformation("User {UserId} registered with email {Email}", user.Id, user.Email);
|
||||
return AuthResult.Success(IssueTokens(user));
|
||||
}
|
||||
|
||||
public async Task<AuthResult> LoginAsync(LoginRequestDto request, CancellationToken ct = default)
|
||||
{
|
||||
var normalizedEmail = request.Email.Trim();
|
||||
|
||||
var user = await _db.Users
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(u => u.Email != null && u.Email.ToLower() == normalizedEmail.ToLower(), ct);
|
||||
|
||||
// Uniform failure message to avoid user enumeration.
|
||||
const string invalidCredentials = "Invalid email or password.";
|
||||
|
||||
if (user is null || string.IsNullOrEmpty(user.PasswordHash))
|
||||
{
|
||||
_logger.LogWarning("Login failed: user not found for {Email}", normalizedEmail);
|
||||
return AuthResult.Fail(invalidCredentials);
|
||||
}
|
||||
|
||||
if (!user.IsActive)
|
||||
{
|
||||
_logger.LogWarning("Login failed: inactive account {UserId}", user.Id);
|
||||
return AuthResult.Fail("This account is disabled.");
|
||||
}
|
||||
|
||||
var verification = _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, request.Password);
|
||||
if (verification == PasswordVerificationResult.Failed)
|
||||
{
|
||||
_logger.LogWarning("Login failed: bad password for {UserId}", user.Id);
|
||||
return AuthResult.Fail(invalidCredentials);
|
||||
}
|
||||
|
||||
_logger.LogInformation("User {UserId} logged in", user.Id);
|
||||
return AuthResult.Success(IssueTokens(user));
|
||||
}
|
||||
|
||||
public async Task<AuthResult> RefreshAsync(string refreshToken, CancellationToken ct = default)
|
||||
{
|
||||
var existing = _refreshTokenStore.Get(refreshToken);
|
||||
if (existing is null || !existing.IsActive)
|
||||
{
|
||||
_logger.LogWarning("Refresh failed: token missing or inactive");
|
||||
return AuthResult.Fail("Invalid or expired refresh token.");
|
||||
}
|
||||
|
||||
// Rotation: immediately invalidate the presented token.
|
||||
_refreshTokenStore.Revoke(refreshToken);
|
||||
|
||||
if (!Guid.TryParse(existing.UserId, out var refreshUserId))
|
||||
{
|
||||
return AuthResult.Fail("Invalid or expired refresh token.");
|
||||
}
|
||||
|
||||
var user = await _db.Users
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(u => u.Id == refreshUserId, ct);
|
||||
|
||||
if (user is null || !user.IsActive)
|
||||
{
|
||||
_logger.LogWarning("Refresh failed: user {UserId} missing or inactive", existing.UserId);
|
||||
return AuthResult.Fail("Invalid or expired refresh token.");
|
||||
}
|
||||
|
||||
return AuthResult.Success(IssueTokens(user));
|
||||
}
|
||||
|
||||
public void Logout(string refreshToken) => _refreshTokenStore.Revoke(refreshToken);
|
||||
|
||||
public async Task<UserInfoDto?> GetUserInfoAsync(string userId, CancellationToken ct = default)
|
||||
{
|
||||
if (!Guid.TryParse(userId, out var parsedUserId))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var user = await _db.Users
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(u => u.Id == parsedUserId, ct);
|
||||
|
||||
if (user is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new UserInfoDto
|
||||
{
|
||||
Id = user.Id.ToString(),
|
||||
UserName = user.UserName,
|
||||
Email = user.Email,
|
||||
};
|
||||
}
|
||||
|
||||
private TokenResponseDto IssueTokens(ApplicationUser user)
|
||||
{
|
||||
var accessToken = _tokenService.CreateAccessToken(user);
|
||||
var refreshToken = _tokenService.CreateRefreshToken(user.Id.ToString());
|
||||
|
||||
return new TokenResponseDto
|
||||
{
|
||||
AccessToken = accessToken,
|
||||
RefreshToken = refreshToken.Token,
|
||||
ExpiresInSeconds = _tokenService.AccessTokenLifetimeSeconds,
|
||||
TokenType = "Bearer",
|
||||
};
|
||||
}
|
||||
}
|
||||
18
MealPlan.Api/Services/IAuthService.cs
Normal file
18
MealPlan.Api/Services/IAuthService.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using MealPlan.Api.DTOs.Auth;
|
||||
|
||||
namespace MealPlan.Api.Services;
|
||||
|
||||
public interface IAuthService
|
||||
{
|
||||
Task<AuthResult> RegisterAsync(RegisterRequestDto request, CancellationToken ct = default);
|
||||
|
||||
Task<AuthResult> LoginAsync(LoginRequestDto request, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Validates and rotates a refresh token, issuing a fresh token pair.</summary>
|
||||
Task<AuthResult> RefreshAsync(string refreshToken, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Revokes the supplied refresh token. Idempotent.</summary>
|
||||
void Logout(string refreshToken);
|
||||
|
||||
Task<UserInfoDto?> GetUserInfoAsync(string userId, CancellationToken ct = default);
|
||||
}
|
||||
12
MealPlan.Api/Services/IRecipeService.cs
Normal file
12
MealPlan.Api/Services/IRecipeService.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using MealPlan.Api.DTOs.Recipe;
|
||||
|
||||
namespace MealPlan.Api.Services;
|
||||
|
||||
public interface IRecipeService
|
||||
{
|
||||
Task<IReadOnlyList<RecipeListItemDto>> GetRecipesAsync(int? category, string? search, CancellationToken ct = default);
|
||||
|
||||
Task<RecipeDetailDto?> GetRecipeByIdAsync(int id, CancellationToken ct = default);
|
||||
|
||||
Task<IReadOnlyList<CategoryCountDto>> GetCategoriesAsync(CancellationToken ct = default);
|
||||
}
|
||||
20
MealPlan.Api/Services/IRefreshTokenStore.cs
Normal file
20
MealPlan.Api/Services/IRefreshTokenStore.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using MealPlan.Api.Models;
|
||||
|
||||
namespace MealPlan.Api.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Stores issued refresh tokens. Backed by an in-memory implementation because the
|
||||
/// existing database schema must not be modified and no migrations may be added.
|
||||
/// </summary>
|
||||
public interface IRefreshTokenStore
|
||||
{
|
||||
void Add(RefreshToken token);
|
||||
|
||||
RefreshToken? Get(string token);
|
||||
|
||||
/// <summary>Marks a token revoked. Returns the revoked token if it existed and was active.</summary>
|
||||
RefreshToken? Revoke(string token);
|
||||
|
||||
/// <summary>Removes expired/revoked tokens to bound memory usage.</summary>
|
||||
void RemoveExpired();
|
||||
}
|
||||
16
MealPlan.Api/Services/ITokenService.cs
Normal file
16
MealPlan.Api/Services/ITokenService.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using System.Security.Claims;
|
||||
using MealPlan.Api.Models;
|
||||
|
||||
namespace MealPlan.Api.Services;
|
||||
|
||||
public interface ITokenService
|
||||
{
|
||||
/// <summary>Creates a signed JWT access token for the given user.</summary>
|
||||
string CreateAccessToken(ApplicationUser user);
|
||||
|
||||
/// <summary>Generates and persists a new refresh token for the given user id.</summary>
|
||||
RefreshToken CreateRefreshToken(string userId);
|
||||
|
||||
/// <summary>Access-token lifetime in seconds (exposed to clients for scheduling refresh).</summary>
|
||||
int AccessTokenLifetimeSeconds { get; }
|
||||
}
|
||||
43
MealPlan.Api/Services/InMemoryRefreshTokenStore.cs
Normal file
43
MealPlan.Api/Services/InMemoryRefreshTokenStore.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
using System.Collections.Concurrent;
|
||||
using MealPlan.Api.Models;
|
||||
|
||||
namespace MealPlan.Api.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Thread-safe in-memory refresh token store registered as a singleton.
|
||||
/// Note: tokens live only for the lifetime of the process. For multi-instance
|
||||
/// deployments this should be swapped for a shared store (e.g. Redis), but it
|
||||
/// satisfies the "do not modify the database" constraint of this project.
|
||||
/// </summary>
|
||||
public class InMemoryRefreshTokenStore : IRefreshTokenStore
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, RefreshToken> _tokens = new();
|
||||
|
||||
public void Add(RefreshToken token) => _tokens[token.Token] = token;
|
||||
|
||||
public RefreshToken? Get(string token) =>
|
||||
_tokens.TryGetValue(token, out var found) ? found : null;
|
||||
|
||||
public RefreshToken? Revoke(string token)
|
||||
{
|
||||
if (!_tokens.TryGetValue(token, out var found))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var wasActive = found.IsActive;
|
||||
found.IsRevoked = true;
|
||||
return wasActive ? found : null;
|
||||
}
|
||||
|
||||
public void RemoveExpired()
|
||||
{
|
||||
foreach (var kvp in _tokens)
|
||||
{
|
||||
if (kvp.Value.IsRevoked || DateTime.UtcNow >= kvp.Value.ExpiresAtUtc)
|
||||
{
|
||||
_tokens.TryRemove(kvp.Key, out _);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
17
MealPlan.Api/Services/JwtOptions.cs
Normal file
17
MealPlan.Api/Services/JwtOptions.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
namespace MealPlan.Api.Services;
|
||||
|
||||
/// <summary>Strongly-typed JWT settings bound from the "Jwt" configuration section / env vars.</summary>
|
||||
public class JwtOptions
|
||||
{
|
||||
public const string SectionName = "Jwt";
|
||||
|
||||
public string Secret { get; set; } = string.Empty;
|
||||
public string Issuer { get; set; } = string.Empty;
|
||||
public string Audience { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Access-token lifetime in minutes. Defaults to 15 per the security spec.</summary>
|
||||
public int AccessTokenMinutes { get; set; } = 15;
|
||||
|
||||
/// <summary>Refresh-token lifetime in days. Defaults to 7 per the security spec.</summary>
|
||||
public int RefreshTokenDays { get; set; } = 7;
|
||||
}
|
||||
107
MealPlan.Api/Services/RecipeService.cs
Normal file
107
MealPlan.Api/Services/RecipeService.cs
Normal file
@@ -0,0 +1,107 @@
|
||||
using MealPlan.Api.Data;
|
||||
using MealPlan.Api.DTOs.Recipe;
|
||||
using MealPlan.Api.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace MealPlan.Api.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Read-only recipe queries. All filtering is done with EF Core LINQ (parameterized);
|
||||
/// no raw SQL is used anywhere.
|
||||
/// </summary>
|
||||
public class RecipeService : IRecipeService
|
||||
{
|
||||
private readonly AppDbContext _db;
|
||||
|
||||
public RecipeService(AppDbContext db) => _db = db;
|
||||
|
||||
public async Task<IReadOnlyList<RecipeListItemDto>> GetRecipesAsync(
|
||||
int? category, string? search, CancellationToken ct = default)
|
||||
{
|
||||
var query = _db.Recipes.AsNoTracking().Where(r => r.IsActive);
|
||||
|
||||
if (category is >= 0 and <= 3)
|
||||
{
|
||||
query = query.Where(r => r.MealCategory == category);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(search))
|
||||
{
|
||||
var term = search.Trim();
|
||||
query = query.Where(r => EF.Functions.ILike(r.Name, $"%{term}%"));
|
||||
}
|
||||
|
||||
return await query
|
||||
.OrderBy(r => r.Name)
|
||||
.Select(r => new RecipeListItemDto
|
||||
{
|
||||
Id = r.Id,
|
||||
Name = r.Name,
|
||||
MealCategory = r.MealCategory,
|
||||
Calories = r.Calories,
|
||||
PrepTimeMinutes = r.PrepTimeMinutes,
|
||||
})
|
||||
.ToListAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<RecipeDetailDto?> GetRecipeByIdAsync(int id, CancellationToken ct = default)
|
||||
{
|
||||
return await _db.Recipes
|
||||
.AsNoTracking()
|
||||
.Where(r => r.Id == id && r.IsActive)
|
||||
.Select(r => new RecipeDetailDto
|
||||
{
|
||||
Id = r.Id,
|
||||
Name = r.Name,
|
||||
MealCategory = r.MealCategory,
|
||||
Calories = r.Calories,
|
||||
Protein = r.Protein,
|
||||
Fat = r.Fat,
|
||||
Carbs = r.Carbs,
|
||||
PrepTimeMinutes = r.PrepTimeMinutes,
|
||||
Ingredients = r.Ingredients
|
||||
.OrderBy(i => i.SortOrder)
|
||||
.ThenBy(i => i.Id)
|
||||
.Select(i => new IngredientDto
|
||||
{
|
||||
Id = i.Id,
|
||||
Name = i.Name,
|
||||
AmountGrams = i.AmountGrams,
|
||||
Unit = i.Unit,
|
||||
SortOrder = i.SortOrder,
|
||||
})
|
||||
.ToList(),
|
||||
Steps = r.Steps
|
||||
.OrderBy(s => s.StepNumber)
|
||||
.Select(s => new RecipeStepDto
|
||||
{
|
||||
Id = s.Id,
|
||||
StepNumber = s.StepNumber,
|
||||
Description = s.Description,
|
||||
})
|
||||
.ToList(),
|
||||
})
|
||||
.FirstOrDefaultAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<CategoryCountDto>> GetCategoriesAsync(CancellationToken ct = default)
|
||||
{
|
||||
var counts = await _db.Recipes
|
||||
.AsNoTracking()
|
||||
.Where(r => r.IsActive)
|
||||
.GroupBy(r => r.MealCategory)
|
||||
.Select(g => new { Category = g.Key, Count = g.Count() })
|
||||
.ToListAsync(ct);
|
||||
|
||||
// Always return all four categories, even when a category has zero recipes.
|
||||
return Enum.GetValues<MealCategory>()
|
||||
.Select(category => new CategoryCountDto
|
||||
{
|
||||
Category = (int)category,
|
||||
Name = category.ToString(),
|
||||
Count = counts.FirstOrDefault(c => c.Category == (int)category)?.Count ?? 0,
|
||||
})
|
||||
.OrderBy(c => c.Category)
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
35
MealPlan.Api/Services/RefreshTokenCleanupService.cs
Normal file
35
MealPlan.Api/Services/RefreshTokenCleanupService.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
namespace MealPlan.Api.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Periodically purges expired and revoked refresh tokens from the in-memory store.
|
||||
/// </summary>
|
||||
public class RefreshTokenCleanupService : BackgroundService
|
||||
{
|
||||
private readonly IRefreshTokenStore _store;
|
||||
private readonly ILogger<RefreshTokenCleanupService> _logger;
|
||||
|
||||
public RefreshTokenCleanupService(
|
||||
IRefreshTokenStore store,
|
||||
ILogger<RefreshTokenCleanupService> logger)
|
||||
{
|
||||
_store = store;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
_store.RemoveExpired();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Refresh token cleanup failed");
|
||||
}
|
||||
|
||||
await Task.Delay(TimeSpan.FromHours(1), stoppingToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
82
MealPlan.Api/Services/TokenService.cs
Normal file
82
MealPlan.Api/Services/TokenService.cs
Normal file
@@ -0,0 +1,82 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using MealPlan.Api.Models;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace MealPlan.Api.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Issues JWT access tokens and rotating refresh tokens.
|
||||
/// Refresh tokens are cryptographically random opaque strings tracked in <see cref="IRefreshTokenStore"/>.
|
||||
/// </summary>
|
||||
public class TokenService : ITokenService
|
||||
{
|
||||
private readonly JwtOptions _options;
|
||||
private readonly IRefreshTokenStore _refreshTokenStore;
|
||||
|
||||
public TokenService(IOptions<JwtOptions> options, IRefreshTokenStore refreshTokenStore)
|
||||
{
|
||||
_options = options.Value;
|
||||
_refreshTokenStore = refreshTokenStore;
|
||||
}
|
||||
|
||||
public int AccessTokenLifetimeSeconds => _options.AccessTokenMinutes * 60;
|
||||
|
||||
public string CreateAccessToken(ApplicationUser user)
|
||||
{
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.Secret));
|
||||
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||
|
||||
var userId = user.Id.ToString();
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(JwtRegisteredClaimNames.Sub, userId),
|
||||
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
|
||||
new(ClaimTypes.NameIdentifier, userId),
|
||||
};
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(user.Email))
|
||||
{
|
||||
claims.Add(new Claim(JwtRegisteredClaimNames.Email, user.Email));
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(user.UserName))
|
||||
{
|
||||
claims.Add(new Claim(ClaimTypes.Name, user.UserName));
|
||||
}
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: _options.Issuer,
|
||||
audience: _options.Audience,
|
||||
claims: claims,
|
||||
notBefore: DateTime.UtcNow,
|
||||
expires: DateTime.UtcNow.AddMinutes(_options.AccessTokenMinutes),
|
||||
signingCredentials: credentials);
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
|
||||
public RefreshToken CreateRefreshToken(string userId)
|
||||
{
|
||||
var token = new RefreshToken
|
||||
{
|
||||
Token = GenerateSecureToken(),
|
||||
UserId = userId,
|
||||
CreatedAtUtc = DateTime.UtcNow,
|
||||
ExpiresAtUtc = DateTime.UtcNow.AddDays(_options.RefreshTokenDays),
|
||||
IsRevoked = false,
|
||||
};
|
||||
|
||||
_refreshTokenStore.Add(token);
|
||||
return token;
|
||||
}
|
||||
|
||||
private static string GenerateSecureToken()
|
||||
{
|
||||
var bytes = RandomNumberGenerator.GetBytes(64);
|
||||
return Convert.ToBase64String(bytes);
|
||||
}
|
||||
}
|
||||
19
MealPlan.Api/Validators/LoginRequestValidator.cs
Normal file
19
MealPlan.Api/Validators/LoginRequestValidator.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using FluentValidation;
|
||||
using MealPlan.Api.DTOs.Auth;
|
||||
|
||||
namespace MealPlan.Api.Validators;
|
||||
|
||||
public class LoginRequestValidator : AbstractValidator<LoginRequestDto>
|
||||
{
|
||||
public LoginRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.Email)
|
||||
.NotEmpty()
|
||||
.EmailAddress()
|
||||
.MaximumLength(256);
|
||||
|
||||
RuleFor(x => x.Password)
|
||||
.NotEmpty()
|
||||
.MaximumLength(256);
|
||||
}
|
||||
}
|
||||
14
MealPlan.Api/Validators/RefreshRequestValidator.cs
Normal file
14
MealPlan.Api/Validators/RefreshRequestValidator.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
using FluentValidation;
|
||||
using MealPlan.Api.DTOs.Auth;
|
||||
|
||||
namespace MealPlan.Api.Validators;
|
||||
|
||||
public class RefreshRequestValidator : AbstractValidator<RefreshRequestDto>
|
||||
{
|
||||
public RefreshRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.RefreshToken)
|
||||
.NotEmpty()
|
||||
.MaximumLength(512);
|
||||
}
|
||||
}
|
||||
27
MealPlan.Api/Validators/RegisterRequestValidator.cs
Normal file
27
MealPlan.Api/Validators/RegisterRequestValidator.cs
Normal file
@@ -0,0 +1,27 @@
|
||||
using FluentValidation;
|
||||
using MealPlan.Api.DTOs.Auth;
|
||||
|
||||
namespace MealPlan.Api.Validators;
|
||||
|
||||
public class RegisterRequestValidator : AbstractValidator<RegisterRequestDto>
|
||||
{
|
||||
public RegisterRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.Email)
|
||||
.NotEmpty()
|
||||
.EmailAddress()
|
||||
.MaximumLength(256);
|
||||
|
||||
RuleFor(x => x.UserName)
|
||||
.MaximumLength(256)
|
||||
.When(x => !string.IsNullOrWhiteSpace(x.UserName));
|
||||
|
||||
RuleFor(x => x.Password)
|
||||
.NotEmpty()
|
||||
.MinimumLength(8)
|
||||
.MaximumLength(256)
|
||||
.Matches(@"[A-Z]").WithMessage("Password must contain at least one uppercase letter.")
|
||||
.Matches(@"[a-z]").WithMessage("Password must contain at least one lowercase letter.")
|
||||
.Matches(@"[0-9]").WithMessage("Password must contain at least one digit.");
|
||||
}
|
||||
}
|
||||
19
MealPlan.Api/appsettings.Development.json
Normal file
19
MealPlan.Api/appsettings.Development.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"Jwt": {
|
||||
"Secret": "dev-only-insecure-secret-change-me-please-32+chars",
|
||||
"Issuer": "DailyMeals",
|
||||
"Audience": "DailyMeals"
|
||||
},
|
||||
"CORS": {
|
||||
"AllowedOrigin": "http://localhost:5173"
|
||||
},
|
||||
"Serilog": {
|
||||
"MinimumLevel": {
|
||||
"Default": "Debug",
|
||||
"Override": {
|
||||
"Microsoft.AspNetCore": "Information",
|
||||
"Microsoft.EntityFrameworkCore": "Information"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
5
MealPlan.Api/appsettings.Local.json.example
Normal file
5
MealPlan.Api/appsettings.Local.json.example
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Host=your-db-host;Port=5432;Database=mealplan;Username=user;Password=secret"
|
||||
}
|
||||
}
|
||||
25
MealPlan.Api/appsettings.json
Normal file
25
MealPlan.Api/appsettings.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": ""
|
||||
},
|
||||
"Jwt": {
|
||||
"Secret": "",
|
||||
"Issuer": "DailyMeals",
|
||||
"Audience": "DailyMeals",
|
||||
"AccessTokenMinutes": 15,
|
||||
"RefreshTokenDays": 7
|
||||
},
|
||||
"CORS": {
|
||||
"AllowedOrigin": ""
|
||||
},
|
||||
"Serilog": {
|
||||
"MinimumLevel": {
|
||||
"Default": "Information",
|
||||
"Override": {
|
||||
"Microsoft.AspNetCore": "Warning",
|
||||
"Microsoft.EntityFrameworkCore": "Warning"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
Reference in New Issue
Block a user