feat: enforce account usage limits
CI and Deploy / test (push) Successful in 2m39s
CI and Deploy / deploy (push) Successful in 55s

This commit is contained in:
cesnimda
2026-07-30 23:14:42 +02:00
parent 9cd2e5c2e3
commit 158970fa01
7 changed files with 74 additions and 16 deletions
@@ -1,6 +1,7 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
@@ -22,11 +23,13 @@ namespace JobTrackerApi.Controllers
private readonly AppPaths _paths;
private readonly JobTrackerContext _db;
private readonly UserManager<ApplicationUser>? _users;
public AttachmentsController(AppPaths paths, JobTrackerContext db)
public AttachmentsController(AppPaths paths, JobTrackerContext db, UserManager<ApplicationUser>? users = null)
{
_paths = paths;
_db = db;
_users = users;
}
public sealed record AttachmentDto(int Id, string FileName, DateTime UploadDate, string FileType, long FileSize, string? Purpose, bool UseForAi);
@@ -202,6 +205,19 @@ namespace JobTrackerApi.Controllers
var jobExists = await _db.JobApplications.AnyAsync(j => j.Id == jobId, cancellationToken);
if (!jobExists) return BadRequest("jobId does not exist.");
if (_users is not null)
{
var user = await _users.GetUserAsync(User);
if (user is null) return Unauthorized();
var roles = await _users.GetRolesAsync(user);
var limit = AccountPlans.ForRoles(roles).StorageBytes;
var used = await _db.Attachments.Where(a => a.JobApplication.OwnerUserId == user.Id).SumAsync(a => (long?)a.FileSize, cancellationToken) ?? 0;
var incoming = files.Sum(file => file.Length);
if (incoming > limit - used)
return StatusCode(StatusCodes.Status413PayloadTooLarge, $"Storage limit reached ({limit / 1_000_000} MB). Remove files or upgrade your plan.");
}
var folder = Path.Combine(_paths.AttachmentsRoot, jobId.ToString());
Directory.CreateDirectory(folder);