Compare commits

..

5 Commits

Author SHA1 Message Date
cesnimda 717d1b9963 perf(db): add remaining hot-path indexes (status filter, correspondence/event FKs)
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 20:22:23 +02:00
cesnimda 3e09e74fc8 refactor(api): extract Gmail DTOs/parsers, batch N+1 loops
- Move inline DTOs to GmailDtos.cs, pure parse helpers to GmailParsing.cs
- Batch per-message existence checks in CreateSuggestedJob/RefreshLinkedThreads
- Remove redundant second pass in RelinkThread, reuse existing HashSet
- Replace ToListAsync+scan with FirstOrDefaultAsync for GmailReviewDecisions lookups

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 20:17:33 +02:00
cesnimda 4cfdc95b59 refactor(api): extract ProfileCv DTOs, add missing AsNoTracking on reads 2026-07-12 20:12:36 +02:00
cesnimda ea6c3650f3 refactor(api): extract JobApplications DTOs and helpers, fix N+1 aggregation
- Move inline DTOs to JobApplicationDtos.cs, pure static helpers to JobApplicationHelpers.cs
- GetStats aggregates server-side (COUNT/GROUP BY) instead of loading the full table
- Cache RuleSettings via IMemoryCache, keyed per-user (RulesEngine.GetSettings falls back
  to per-user UserRuleSettings overrides, so a single global cache key would leak settings
  across users)
- Add missing AsNoTracking() to read-only GET endpoints (GetAll, GetById, GetBoard,
  GetReminders, GetStatusSuggestion, GetMatchScore, GetCandidateFit, GetFocusPlan,
  GetInterviewPrep, GetReadiness)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 20:08:59 +02:00
cesnimda bd07876a41 fix(db): stop startup crash from MySQL composite-index key length
Prod was hard-down: InitializeJobTrackerAsync threw an unhandled
MySqlException ("Specified key was too long; max key length is 3072
bytes") while creating IX_JobApplications_OwnerUserId_FollowUpAt,
which crashed Program.Main before the app could start (surfaced to
users as a 500 on Google sign-in, but really affected every request).

Root cause: this reconciler assumes OwnerUserId is varchar(255), but
the live column was provisioned wider by an earlier EF migration,
close enough to the utf8mb4 3072-byte limit that pairing it with a
second column tips a composite index over.

Fix:
- Prefix-index OwnerUserId at 191 chars (safe under the legacy
  767-byte-per-column limit, still far wider than the GUID-like
  Identity ids actually stored) in every composite/unique index that
  includes it, so index creation no longer depends on the column's
  actual declared width.
- Wrap each CREATE INDEX in try/catch + LogWarning instead of letting
  it propagate: a schema reconciler is best-effort and one failed
  index must never crash startup, matching the existing non-fatal
  pattern already used a few lines below for legacy-schema ownership
  claims.

Backend build + full test suite (177 passing) verified green.
2026-07-12 19:50:58 +02:00
52 changed files with 1261 additions and 4405 deletions
+11 -36
View File
@@ -28,9 +28,6 @@ namespace JobTrackerApi.Data
public DbSet<CvUploadArtifact> CvUploadArtifacts => Set<CvUploadArtifact>();
public DbSet<CvExtractionRun> CvExtractionRuns => Set<CvExtractionRun>();
public DbSet<TailoredCvDraft> TailoredCvDrafts => Set<TailoredCvDraft>();
public DbSet<TwoFactorRecoveryCode> TwoFactorRecoveryCodes => Set<TwoFactorRecoveryCode>();
public DbSet<TrustedDevice> TrustedDevices => Set<TrustedDevice>();
public DbSet<UserSession> UserSessions => Set<UserSession>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
@@ -74,6 +71,11 @@ namespace JobTrackerApi.Data
modelBuilder.Entity<JobApplication>()
.HasIndex(j => new { j.OwnerUserId, j.FollowUpAt });
// Board/list endpoints that filter by both IsDeleted and Status. Same MySQL
// longtext-prefix caveat as above; the reconciler applies `Status(50)` there.
modelBuilder.Entity<JobApplication>()
.HasIndex(j => new { j.OwnerUserId, j.IsDeleted, j.Status });
modelBuilder.Entity<Company>()
.HasIndex(c => c.OwnerUserId);
@@ -84,6 +86,9 @@ namespace JobTrackerApi.Data
.HasForeignKey(c => c.JobApplicationId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Correspondence>()
.HasIndex(c => c.JobApplicationId);
modelBuilder.Entity<GmailConnection>()
.HasQueryFilter(x => CurrentUserId != null && x.OwnerUserId == CurrentUserId);
@@ -114,6 +119,9 @@ namespace JobTrackerApi.Data
.HasForeignKey(e => e.JobApplicationId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<JobEvent>()
.HasIndex(e => e.JobApplicationId);
modelBuilder.Entity<CvUploadArtifact>()
.HasQueryFilter(x => CurrentUserId != null && x.OwnerUserId == CurrentUserId);
@@ -144,39 +152,6 @@ namespace JobTrackerApi.Data
.WithOne(j => j.TailoredCvDraft)
.HasForeignKey<TailoredCvDraft>(x => x.JobApplicationId)
.OnDelete(DeleteBehavior.Cascade);
// No FK to AspNetUsers: the login-time challenge endpoint reads these rows before a
// session (and thus CurrentUserId) exists, via IgnoreQueryFilters() -- same convention
// as AdminAuditController's cross-cutting queries.
modelBuilder.Entity<TwoFactorRecoveryCode>()
.HasQueryFilter(x => CurrentUserId != null && x.UserId == CurrentUserId);
modelBuilder.Entity<TwoFactorRecoveryCode>()
.HasIndex(x => new { x.UserId, x.UsedAtUtc });
// No FK to AspNetUsers: the login-time trusted-device check reads these rows before a
// session (and thus CurrentUserId) exists, via IgnoreQueryFilters() -- same convention
// as TwoFactorRecoveryCode above.
modelBuilder.Entity<TrustedDevice>()
.HasQueryFilter(x => CurrentUserId != null && x.UserId == CurrentUserId);
modelBuilder.Entity<TrustedDevice>()
.HasIndex(x => x.UserId);
modelBuilder.Entity<TrustedDevice>()
.HasIndex(x => x.TokenHash);
// No FK to AspNetUsers, same convention as TrustedDevice/TwoFactorRecoveryCode above: the
// OnTokenValidated auth check reads this table before CurrentUserId is meaningfully set
// for the request being validated, via IgnoreQueryFilters().
modelBuilder.Entity<UserSession>()
.HasKey(x => x.Id);
modelBuilder.Entity<UserSession>()
.HasQueryFilter(x => CurrentUserId != null && x.UserId == CurrentUserId);
modelBuilder.Entity<UserSession>()
.HasIndex(x => x.UserId);
}
}
}
@@ -1,12 +1,10 @@
using JobTrackerApi.Controllers;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using JobTrackerApi.Tests.TestSupport;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging.Abstractions;
@@ -19,388 +17,6 @@ namespace JobTrackerApi.Tests;
public sealed class AuthAndSystemControllerTests
{
[Fact]
public async Task Login_locks_account_after_five_failed_attempts_and_rejects_sixth_even_with_correct_password()
{
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com" };
var userManager = CreateUserManager();
userManager.Setup(x => x.FindByEmailAsync("person@example.com")).ReturnsAsync(user);
userManager.Setup(x => x.FindByNameAsync("person@example.com")).ReturnsAsync((ApplicationUser?)null);
var failedCount = 0;
var lockedOut = false;
userManager.Setup(x => x.IsLockedOutAsync(user)).Returns(() => Task.FromResult(lockedOut));
userManager.Setup(x => x.AccessFailedAsync(user))
.Callback(() =>
{
failedCount++;
if (failedCount >= 5) lockedOut = true;
})
.ReturnsAsync(IdentityResult.Success);
userManager.Setup(x => x.CheckPasswordAsync(user, "wrong-password")).ReturnsAsync(false);
userManager.Setup(x => x.CheckPasswordAsync(user, "correct-password")).ReturnsAsync(true);
var controller = new AuthController(BuildConfig(), userManager.Object, Mock.Of<ITokenService>(), Mock.Of<IAppEmailSender>(), Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(), NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), TestHostFactory.CreateInMemoryDb());
for (var i = 0; i < 5; i++)
{
var attempt = await controller.Login(new AuthController.LoginRequest("person@example.com", "wrong-password"), CancellationToken.None);
Assert.IsType<UnauthorizedResult>(attempt);
}
Assert.True(lockedOut);
var sixthAttempt = await controller.Login(new AuthController.LoginRequest("person@example.com", "correct-password"), CancellationToken.None);
Assert.IsType<UnauthorizedResult>(sixthAttempt);
userManager.Verify(x => x.CheckPasswordAsync(user, "correct-password"), Times.Never);
}
[Fact]
public async Task Login_skips_two_factor_when_trusted_device_cookie_matches_current_user()
{
var dbName = Guid.NewGuid().ToString();
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com", TwoFactorEnabled = true, TotpSecretEncrypted = "irrelevant" };
const string token = "trusted-device-token";
using (var seedDb = BuildDb(dbName, null))
{
seedDb.TrustedDevices.Add(new TrustedDevice
{
UserId = "user-1",
TokenHash = TrustedDeviceService.HashToken(token),
CreatedAtUtc = DateTimeOffset.UtcNow,
LastSeenAtUtc = DateTimeOffset.UtcNow,
ExpiresAtUtc = DateTimeOffset.UtcNow.AddDays(30),
});
seedDb.SaveChanges();
}
var controller = BuildLoginController(user, "correct-password", out var db, dbName, token);
using (db)
{
var result = await controller.Login(new AuthController.LoginRequest("person@example.com", "correct-password"), CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result);
var session = Assert.IsType<AuthController.AuthSessionResult>(ok.Value);
Assert.True(session.Authenticated);
}
}
[Fact]
public async Task Login_does_not_skip_two_factor_when_trusted_device_belongs_to_different_user()
{
var dbName = Guid.NewGuid().ToString();
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com", TwoFactorEnabled = true, TotpSecretEncrypted = "irrelevant" };
const string token = "trusted-device-token";
using (var seedDb = BuildDb(dbName, null))
{
seedDb.TrustedDevices.Add(new TrustedDevice
{
UserId = "user-2", // a different account -- must not skip 2FA for user-1
TokenHash = TrustedDeviceService.HashToken(token),
CreatedAtUtc = DateTimeOffset.UtcNow,
LastSeenAtUtc = DateTimeOffset.UtcNow,
ExpiresAtUtc = DateTimeOffset.UtcNow.AddDays(30),
});
seedDb.SaveChanges();
}
var controller = BuildLoginController(user, "correct-password", out var db, dbName, token);
using (db)
{
var result = await controller.Login(new AuthController.LoginRequest("person@example.com", "correct-password"), CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result);
Assert.IsType<AuthController.TwoFactorRequiredResult>(ok.Value);
}
}
[Fact]
public async Task Login_does_not_skip_two_factor_when_trusted_device_is_expired()
{
var dbName = Guid.NewGuid().ToString();
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com", TwoFactorEnabled = true, TotpSecretEncrypted = "irrelevant" };
const string token = "trusted-device-token";
using (var seedDb = BuildDb(dbName, null))
{
seedDb.TrustedDevices.Add(new TrustedDevice
{
UserId = "user-1",
TokenHash = TrustedDeviceService.HashToken(token),
CreatedAtUtc = DateTimeOffset.UtcNow.AddDays(-31),
LastSeenAtUtc = DateTimeOffset.UtcNow.AddDays(-31),
ExpiresAtUtc = DateTimeOffset.UtcNow.AddDays(-1), // expired yesterday
});
seedDb.SaveChanges();
}
var controller = BuildLoginController(user, "correct-password", out var db, dbName, token);
using (db)
{
var result = await controller.Login(new AuthController.LoginRequest("person@example.com", "correct-password"), CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result);
Assert.IsType<AuthController.TwoFactorRequiredResult>(ok.Value);
}
}
[Fact]
public async Task Login_does_not_skip_two_factor_when_no_trusted_device_cookie_present()
{
var dbName = Guid.NewGuid().ToString();
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com", TwoFactorEnabled = true, TotpSecretEncrypted = "irrelevant" };
var controller = BuildLoginController(user, "correct-password", out var db, dbName, cookieToken: null);
using (db)
{
var result = await controller.Login(new AuthController.LoginRequest("person@example.com", "correct-password"), CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result);
Assert.IsType<AuthController.TwoFactorRequiredResult>(ok.Value);
}
}
[Fact]
public async Task Register_sets_EmailConfirmed_false_and_sends_verification_email_when_flag_on()
{
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
["Auth:AllowRegistration"] = "true",
["Auth:RequireEmailVerification"] = "true",
})
.Build();
var userManager = CreateUserManager();
userManager.Setup(x => x.FindByEmailAsync("new.user@example.com")).ReturnsAsync((ApplicationUser?)null);
ApplicationUser? created = null;
userManager
.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), "password123"))
.Callback<ApplicationUser, string>((u, _) => created = u)
.ReturnsAsync(IdentityResult.Success);
userManager.Setup(x => x.GenerateEmailConfirmationTokenAsync(It.IsAny<ApplicationUser>())).ReturnsAsync("confirm-token");
var tokenService = new Mock<ITokenService>();
tokenService.Setup(x => x.CreateAccessTokenAsync(It.IsAny<ApplicationUser>(), It.IsAny<string?>(), It.IsAny<CancellationToken>())).ReturnsAsync("app-token");
var emailSender = new Mock<IAppEmailSender>();
var controller = new AuthController(config, userManager.Object, tokenService.Object, emailSender.Object, Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(), NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), TestHostFactory.CreateInMemoryDb())
{
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};
var result = await controller.Register(new AuthController.RegisterRequest("new.user@example.com", "password123"), CancellationToken.None);
Assert.IsType<OkObjectResult>(result);
Assert.NotNull(created);
Assert.False(created!.EmailConfirmed);
emailSender.Verify(x => x.SendAsync("new.user@example.com", It.IsAny<string>(), It.Is<string>(b => b.Contains("verify-email")), It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task Register_is_unchanged_when_flag_off()
{
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?> { ["Auth:AllowRegistration"] = "true" })
.Build();
var userManager = CreateUserManager();
userManager.Setup(x => x.FindByEmailAsync("new.user@example.com")).ReturnsAsync((ApplicationUser?)null);
ApplicationUser? created = null;
userManager
.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), "password123"))
.Callback<ApplicationUser, string>((u, _) => created = u)
.ReturnsAsync(IdentityResult.Success);
var tokenService = new Mock<ITokenService>();
tokenService.Setup(x => x.CreateAccessTokenAsync(It.IsAny<ApplicationUser>(), It.IsAny<string?>(), It.IsAny<CancellationToken>())).ReturnsAsync("app-token");
var emailSender = new Mock<IAppEmailSender>();
var controller = new AuthController(config, userManager.Object, tokenService.Object, emailSender.Object, Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(), NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), TestHostFactory.CreateInMemoryDb())
{
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};
var result = await controller.Register(new AuthController.RegisterRequest("new.user@example.com", "password123"), CancellationToken.None);
Assert.IsType<OkObjectResult>(result);
Assert.NotNull(created);
Assert.True(created!.EmailConfirmed);
emailSender.Verify(x => x.SendAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Never);
}
[Fact]
public async Task Login_rejects_unconfirmed_local_account_when_flag_on()
{
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?> { ["Auth:RequireEmailVerification"] = "true" })
.Build();
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com", EmailConfirmed = false };
var userManager = CreateUserManager();
userManager.Setup(x => x.FindByEmailAsync("person@example.com")).ReturnsAsync(user);
userManager.Setup(x => x.FindByNameAsync("person@example.com")).ReturnsAsync((ApplicationUser?)null);
userManager.Setup(x => x.IsLockedOutAsync(user)).ReturnsAsync(false);
userManager.Setup(x => x.CheckPasswordAsync(user, "correct-password")).ReturnsAsync(true);
userManager.Setup(x => x.ResetAccessFailedCountAsync(user)).ReturnsAsync(IdentityResult.Success);
var controller = new AuthController(config, userManager.Object, Mock.Of<ITokenService>(), Mock.Of<IAppEmailSender>(), Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(), NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), TestHostFactory.CreateInMemoryDb())
{
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};
var result = await controller.Login(new AuthController.LoginRequest("person@example.com", "correct-password"), CancellationToken.None);
var obj = Assert.IsType<ObjectResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, obj.StatusCode);
}
[Fact]
public async Task Login_allows_unconfirmed_local_account_when_flag_off()
{
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com", EmailConfirmed = false };
var userManager = CreateUserManager();
userManager.Setup(x => x.FindByEmailAsync("person@example.com")).ReturnsAsync(user);
userManager.Setup(x => x.FindByNameAsync("person@example.com")).ReturnsAsync((ApplicationUser?)null);
userManager.Setup(x => x.IsLockedOutAsync(user)).ReturnsAsync(false);
userManager.Setup(x => x.CheckPasswordAsync(user, "correct-password")).ReturnsAsync(true);
userManager.Setup(x => x.ResetAccessFailedCountAsync(user)).ReturnsAsync(IdentityResult.Success);
var tokenService = new Mock<ITokenService>();
tokenService.Setup(x => x.CreateAccessTokenAsync(user, It.IsAny<string?>(), It.IsAny<CancellationToken>())).ReturnsAsync("app-token");
var controller = new AuthController(BuildConfig(), userManager.Object, tokenService.Object, Mock.Of<IAppEmailSender>(), Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(), NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), TestHostFactory.CreateInMemoryDb())
{
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};
var result = await controller.Login(new AuthController.LoginRequest("person@example.com", "correct-password"), CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result);
var session = Assert.IsType<AuthController.AuthSessionResult>(ok.Value);
Assert.True(session.Authenticated);
}
[Fact]
public async Task VerifyEmail_confirms_account_on_valid_token()
{
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com", EmailConfirmed = false };
var userManager = CreateUserManager();
userManager.Setup(x => x.FindByIdAsync("user-1")).ReturnsAsync(user);
userManager.Setup(x => x.ConfirmEmailAsync(user, "good-token")).ReturnsAsync(IdentityResult.Success);
var controller = new AuthController(BuildConfig(), userManager.Object, Mock.Of<ITokenService>(), Mock.Of<IAppEmailSender>(), Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(), NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), TestHostFactory.CreateInMemoryDb());
var result = await controller.VerifyEmail(new AuthController.VerifyEmailRequest("user-1", "good-token"));
Assert.IsType<NoContentResult>(result);
}
[Fact]
public async Task ResendVerificationEmail_returns_identical_response_for_real_and_fake_accounts()
{
var user = new ApplicationUser { Id = "user-1", Email = "real@example.com", UserName = "real@example.com", EmailConfirmed = false };
var userManager = CreateUserManager();
userManager.Setup(x => x.FindByEmailAsync("real@example.com")).ReturnsAsync(user);
userManager.Setup(x => x.FindByEmailAsync("fake@example.com")).ReturnsAsync((ApplicationUser?)null);
userManager.Setup(x => x.HasPasswordAsync(user)).ReturnsAsync(true);
userManager.Setup(x => x.GenerateEmailConfirmationTokenAsync(user)).ReturnsAsync("confirm-token");
var emailSender = new Mock<IAppEmailSender>();
var controller = new AuthController(BuildConfig(), userManager.Object, Mock.Of<ITokenService>(), emailSender.Object, Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(), NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), TestHostFactory.CreateInMemoryDb())
{
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};
var realResult = await controller.ResendVerificationEmail(new AuthController.ResendVerificationEmailRequest("real@example.com"), CancellationToken.None);
var fakeResult = await controller.ResendVerificationEmail(new AuthController.ResendVerificationEmailRequest("fake@example.com"), CancellationToken.None);
Assert.IsType<NoContentResult>(realResult);
Assert.IsType<NoContentResult>(fakeResult);
emailSender.Verify(x => x.SendAsync("real@example.com", It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task Exchange_google_token_new_user_stays_EmailConfirmed_true_even_when_verification_flag_is_on()
{
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
["Auth:AllowRegistration"] = "true",
["Auth:RequireEmailVerification"] = "true",
})
.Build();
var userManager = CreateUserManager();
userManager.Setup(x => x.Users).Returns(new TestAsyncEnumerable<ApplicationUser>(new List<ApplicationUser>()));
userManager.Setup(x => x.FindByEmailAsync("new.hire@example.com")).ReturnsAsync((ApplicationUser?)null);
ApplicationUser? created = null;
userManager
.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>()))
.Callback<ApplicationUser>(u => created = u)
.ReturnsAsync(IdentityResult.Success);
var tokenService = new Mock<ITokenService>();
tokenService.Setup(x => x.CreateAccessTokenAsync(It.IsAny<ApplicationUser>(), It.IsAny<string?>(), It.IsAny<CancellationToken>())).ReturnsAsync("app-token");
var googleValidator = new Mock<IGoogleTokenValidator>();
googleValidator
.Setup(x => x.ValidateAsync("google-token", It.IsAny<CancellationToken>()))
.ReturnsAsync(new GoogleTokenPrincipal("google-subject", "new.hire@example.com", true, "New", "Hire", "New Hire"));
var controller = new AuthController(config, userManager.Object, tokenService.Object, Mock.Of<IAppEmailSender>(), googleValidator.Object, Mock.Of<IMicrosoftTokenValidator>(), NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), TestHostFactory.CreateInMemoryDb())
{
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};
var result = await controller.ExchangeGoogleToken(new AuthController.GoogleTokenRequest("google-token"), CancellationToken.None);
Assert.IsType<OkObjectResult>(result);
Assert.NotNull(created);
Assert.True(created!.EmailConfirmed);
}
private static JobTrackerContext BuildDb(string dbName, string? currentUserId)
{
var options = new DbContextOptionsBuilder<JobTrackerContext>().UseInMemoryDatabase(dbName).Options;
var currentUser = new Mock<ICurrentUserService>();
currentUser.SetupGet(x => x.UserId).Returns(currentUserId);
return new JobTrackerContext(options, currentUser.Object);
}
private static AuthController BuildLoginController(ApplicationUser user, string password, out JobTrackerContext db, string dbName, string? cookieToken)
{
var userManager = CreateUserManager();
userManager.Setup(x => x.FindByEmailAsync(user.Email!)).ReturnsAsync(user);
userManager.Setup(x => x.FindByNameAsync(user.Email!)).ReturnsAsync((ApplicationUser?)null);
userManager.Setup(x => x.IsLockedOutAsync(user)).ReturnsAsync(false);
userManager.Setup(x => x.CheckPasswordAsync(user, password)).ReturnsAsync(true);
userManager.Setup(x => x.ResetAccessFailedCountAsync(user)).ReturnsAsync(IdentityResult.Success);
var tokenService = new Mock<ITokenService>();
tokenService.Setup(x => x.CreateAccessTokenAsync(user, It.IsAny<string?>(), It.IsAny<CancellationToken>())).ReturnsAsync("app-token");
db = BuildDb(dbName, null);
var controller = new AuthController(BuildConfig(), userManager.Object, tokenService.Object, Mock.Of<IAppEmailSender>(), Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(), NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), db)
{
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};
if (cookieToken is not null)
{
controller.Request.Headers["Cookie"] = $"{AuthSessionOptions.TrustedDeviceCookieName}={cookieToken}";
}
return controller;
}
[Fact]
public async Task Update_profile_applies_trimmed_profile_fields()
{
@@ -409,7 +25,7 @@ public sealed class AuthAndSystemControllerTests
userManager.Setup(x => x.GetUserAsync(It.IsAny<System.Security.Claims.ClaimsPrincipal>())).ReturnsAsync(user);
userManager.Setup(x => x.UpdateAsync(user)).ReturnsAsync(IdentityResult.Success);
var controller = new AuthController(BuildConfig(), userManager.Object, Mock.Of<ITokenService>(), Mock.Of<IAppEmailSender>(), Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(), NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), TestHostFactory.CreateInMemoryDb());
var controller = new AuthController(BuildConfig(), userManager.Object, Mock.Of<ITokenService>(), Mock.Of<IAppEmailSender>(), Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(), NullLogger<AuthController>.Instance);
var result = await controller.UpdateProfile(new AuthController.UpdateProfileRequest(" new@example.com ", " newuser ", " Ada ", " Lovelace ", " Ada L. ", null, null));
@@ -434,7 +50,7 @@ public sealed class AuthAndSystemControllerTests
.Setup(x => x.SendAsync(user.Email!, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new InvalidOperationException("SMTP unavailable"));
var controller = new AuthController(BuildConfig(), userManager.Object, Mock.Of<ITokenService>(), emailSender.Object, Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(), NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), TestHostFactory.CreateInMemoryDb())
var controller = new AuthController(BuildConfig(), userManager.Object, Mock.Of<ITokenService>(), emailSender.Object, Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(), NullLogger<AuthController>.Instance)
{
ControllerContext = new ControllerContext
{
@@ -468,14 +84,14 @@ public sealed class AuthAndSystemControllerTests
userManager.Setup(x => x.UpdateAsync(user)).ReturnsAsync(IdentityResult.Success);
var tokenService = new Mock<ITokenService>();
tokenService.Setup(x => x.CreateAccessTokenAsync(user, It.IsAny<string?>(), It.IsAny<CancellationToken>())).ReturnsAsync("app-token");
tokenService.Setup(x => x.CreateAccessTokenAsync(user, It.IsAny<CancellationToken>())).ReturnsAsync("app-token");
var googleValidator = new Mock<IGoogleTokenValidator>();
googleValidator
.Setup(x => x.ValidateAsync("google-token", It.IsAny<CancellationToken>()))
.ReturnsAsync(new GoogleTokenPrincipal("google-subject", "dj@cesnimda.co.uk", true, "Dan", "Jones", "Dan Jones"));
var controller = new AuthController(BuildConfig(), userManager.Object, tokenService.Object, Mock.Of<IAppEmailSender>(), googleValidator.Object, Mock.Of<IMicrosoftTokenValidator>(), NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), TestHostFactory.CreateInMemoryDb())
var controller = new AuthController(BuildConfig(), userManager.Object, tokenService.Object, Mock.Of<IAppEmailSender>(), googleValidator.Object, Mock.Of<IMicrosoftTokenValidator>(), NullLogger<AuthController>.Instance)
{
ControllerContext = new ControllerContext
{
@@ -485,7 +101,7 @@ public sealed class AuthAndSystemControllerTests
var result = await controller.ExchangeGoogleToken(new AuthController.GoogleTokenRequest("google-token"), CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result);
var ok = Assert.IsType<OkObjectResult>(result.Result);
var payload = Assert.IsType<AuthController.AuthSessionResult>(ok.Value);
Assert.True(payload.Authenticated);
Assert.Equal("google", payload.Provider);
@@ -508,7 +124,7 @@ public sealed class AuthAndSystemControllerTests
userManager.Setup(x => x.UpdateAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(IdentityResult.Success);
var tokenService = new Mock<ITokenService>();
tokenService.Setup(x => x.CreateAccessTokenAsync(It.IsAny<ApplicationUser>(), It.IsAny<string?>(), It.IsAny<CancellationToken>())).ReturnsAsync("app-token");
tokenService.Setup(x => x.CreateAccessTokenAsync(It.IsAny<ApplicationUser>(), It.IsAny<CancellationToken>())).ReturnsAsync("app-token");
var microsoftValidator = new Mock<IMicrosoftTokenValidator>();
microsoftValidator
@@ -519,7 +135,7 @@ public sealed class AuthAndSystemControllerTests
.AddInMemoryCollection(new Dictionary<string, string?> { ["Auth:AllowRegistration"] = "true" })
.Build();
var controller = new AuthController(config, userManager.Object, tokenService.Object, Mock.Of<IAppEmailSender>(), Mock.Of<IGoogleTokenValidator>(), microsoftValidator.Object, NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), TestHostFactory.CreateInMemoryDb())
var controller = new AuthController(config, userManager.Object, tokenService.Object, Mock.Of<IAppEmailSender>(), Mock.Of<IGoogleTokenValidator>(), microsoftValidator.Object, NullLogger<AuthController>.Instance)
{
ControllerContext = new ControllerContext
{
@@ -529,7 +145,7 @@ public sealed class AuthAndSystemControllerTests
var result = await controller.ExchangeMicrosoftToken(new AuthController.MicrosoftTokenRequest("microsoft-token"), CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result);
var ok = Assert.IsType<OkObjectResult>(result.Result);
var payload = Assert.IsType<AuthController.AuthSessionResult>(ok.Value);
Assert.True(payload.Authenticated);
Assert.Equal("microsoft", payload.Provider);
@@ -550,7 +166,7 @@ public sealed class AuthAndSystemControllerTests
.Setup(x => x.ValidateAsync("microsoft-token", It.IsAny<CancellationToken>()))
.ReturnsAsync(new MicrosoftTokenPrincipal("ms-subject", "nobody@example.com", true, null, null, null));
var controller = new AuthController(BuildConfig(), userManager.Object, Mock.Of<ITokenService>(), Mock.Of<IAppEmailSender>(), Mock.Of<IGoogleTokenValidator>(), microsoftValidator.Object, NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), TestHostFactory.CreateInMemoryDb())
var controller = new AuthController(BuildConfig(), userManager.Object, Mock.Of<ITokenService>(), Mock.Of<IAppEmailSender>(), Mock.Of<IGoogleTokenValidator>(), microsoftValidator.Object, NullLogger<AuthController>.Instance)
{
ControllerContext = new ControllerContext
{
@@ -560,7 +176,7 @@ public sealed class AuthAndSystemControllerTests
var result = await controller.ExchangeMicrosoftToken(new AuthController.MicrosoftTokenRequest("microsoft-token"), CancellationToken.None);
Assert.IsType<UnauthorizedObjectResult>(result);
Assert.IsType<UnauthorizedObjectResult>(result.Result);
userManager.Verify(x => x.CreateAsync(It.IsAny<ApplicationUser>()), Times.Never);
}
@@ -51,7 +51,7 @@ public sealed class ClientErrorsControllerTests
var userManager = TestHostFactory.CreateUserManager();
userManager.Setup(x => x.GetUserAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(user);
var controller = new AuthController(BuildConfig(), userManager.Object, Mock.Of<ITokenService>(), Mock.Of<IAppEmailSender>(), Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(), Mock.Of<ILogger<AuthController>>(), Mock.Of<ITwoFactorPendingTokenService>(), TestHostFactory.CreateInMemoryDb())
var controller = new AuthController(BuildConfig(), userManager.Object, Mock.Of<ITokenService>(), Mock.Of<IAppEmailSender>(), Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(), Mock.Of<ILogger<AuthController>>())
{
ControllerContext = new ControllerContext
{
+34 -34
View File
@@ -39,7 +39,7 @@ public sealed class GmailControllerTests
var result = await controller.Status(CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result.Result);
var payload = Assert.IsType<GmailController.GmailConnectionStatusDto>(ok.Value);
var payload = Assert.IsType<GmailConnectionStatusDto>(ok.Value);
Assert.True(payload.Connected);
Assert.Equal("user@example.test", payload.GmailAddress);
Assert.Equal("list-messages", payload.LastSyncMode);
@@ -54,7 +54,7 @@ public sealed class GmailControllerTests
await using var db = CreateDb();
var controller = CreateController(db, Mock.Of<IGmailOAuthService>(), "user-1");
var result = await controller.ImportThread(new GmailController.ImportGmailThreadRequest(1, "thread-1", Array.Empty<string>()), CancellationToken.None);
var result = await controller.ImportThread(new ImportGmailThreadRequest(1, "thread-1", Array.Empty<string>()), CancellationToken.None);
var badRequest = Assert.IsType<BadRequestObjectResult>(result.Result);
Assert.Equal("At least one messageId is required.", badRequest.Value);
@@ -159,7 +159,7 @@ public sealed class GmailControllerTests
var result = await controller.JobCandidates(job.Id, overrideQuery, 6, CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result.Result);
var payload = Assert.IsType<GmailController.GmailJobMatchesResponseDto>(ok.Value);
var payload = Assert.IsType<GmailJobMatchesResponseDto>(ok.Value);
Assert.Equal(job.Id, payload.JobApplicationId);
Assert.Contains(overrideQuery, payload.Queries);
@@ -221,7 +221,7 @@ public sealed class GmailControllerTests
var result = await controller.JobCandidates(job.Id, null, 6, CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result.Result);
var payload = Assert.IsType<GmailController.GmailJobMatchesResponseDto>(ok.Value);
var payload = Assert.IsType<GmailJobMatchesResponseDto>(ok.Value);
Assert.NotEmpty(payload.Queries);
Assert.Equal(0, payload.CandidateMessageCount);
Assert.Equal(0, payload.CandidateThreadCount);
@@ -264,9 +264,9 @@ public sealed class GmailControllerTests
var controller = CreateController(db, gmail.Object, "user-1");
var first = await controller.Import(new GmailController.ImportGmailMessageRequest(job.Id, "msg-1"), CancellationToken.None);
var first = await controller.Import(new ImportGmailMessageRequest(job.Id, "msg-1"), CancellationToken.None);
var firstOk = Assert.IsType<OkObjectResult>(first.Result);
var firstPayload = Assert.IsType<GmailController.GmailImportMessageResultDto>(firstOk.Value);
var firstPayload = Assert.IsType<GmailImportMessageResultDto>(firstOk.Value);
Assert.Equal(1, firstPayload.Imported);
Assert.Equal(0, firstPayload.Skipped);
Assert.Equal("thread-1", firstPayload.ThreadId);
@@ -279,9 +279,9 @@ public sealed class GmailControllerTests
Assert.Single(firstPayload.Message.AttachmentMetadata);
Assert.Equal("cv.pdf", firstPayload.Message.AttachmentMetadata[0].FileName);
var second = await controller.Import(new GmailController.ImportGmailMessageRequest(job.Id, "msg-1"), CancellationToken.None);
var second = await controller.Import(new ImportGmailMessageRequest(job.Id, "msg-1"), CancellationToken.None);
var secondOk = Assert.IsType<OkObjectResult>(second.Result);
var secondPayload = Assert.IsType<GmailController.GmailImportMessageResultDto>(secondOk.Value);
var secondPayload = Assert.IsType<GmailImportMessageResultDto>(secondOk.Value);
Assert.Equal(0, secondPayload.Imported);
Assert.Equal(1, secondPayload.Skipped);
Assert.Equal("thread-1", secondPayload.ThreadId);
@@ -340,18 +340,18 @@ public sealed class GmailControllerTests
Array.Empty<GmailMessageAttachment>()));
var controller = CreateController(db, gmail.Object, "user-1");
var request = new GmailController.ImportGmailThreadRequest(job.Id, "thread-1", new[] { "msg-1", "msg-2" });
var request = new ImportGmailThreadRequest(job.Id, "thread-1", new[] { "msg-1", "msg-2" });
var first = await controller.ImportThread(request, CancellationToken.None);
var firstOk = Assert.IsType<OkObjectResult>(first.Result);
var firstPayload = Assert.IsType<GmailController.GmailImportResultDto>(firstOk.Value);
var firstPayload = Assert.IsType<GmailImportResultDto>(firstOk.Value);
Assert.Equal(2, firstPayload.Imported);
Assert.Equal(0, firstPayload.Skipped);
Assert.Equal("thread-1", firstPayload.ThreadId);
var second = await controller.ImportThread(request, CancellationToken.None);
var secondOk = Assert.IsType<OkObjectResult>(second.Result);
var secondPayload = Assert.IsType<GmailController.GmailImportResultDto>(secondOk.Value);
var secondPayload = Assert.IsType<GmailImportResultDto>(secondOk.Value);
Assert.Equal(0, secondPayload.Imported);
Assert.Equal(2, secondPayload.Skipped);
@@ -414,10 +414,10 @@ public sealed class GmailControllerTests
Array.Empty<GmailMessageAttachment>()));
var controller = CreateController(db, gmail.Object, "user-1");
var result = await controller.RefreshLinkedThreads(new GmailController.RefreshLinkedThreadsRequest(job.Id), CancellationToken.None);
var result = await controller.RefreshLinkedThreads(new RefreshLinkedThreadsRequest(job.Id), CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result.Result);
var payload = Assert.IsType<GmailController.GmailThreadRefreshResultDto>(ok.Value);
var payload = Assert.IsType<GmailThreadRefreshResultDto>(ok.Value);
Assert.Equal(job.Id, payload.JobApplicationId);
Assert.Equal(1, payload.ThreadsChecked);
Assert.Equal(1, payload.Imported);
@@ -461,7 +461,7 @@ public sealed class GmailControllerTests
var disconnectedGmail = new Mock<IGmailOAuthService>(MockBehavior.Strict);
disconnectedGmail.Setup(service => service.GetConnectionAsync("user-1", It.IsAny<CancellationToken>())).ReturnsAsync((GmailConnection?)null);
var disconnectedController = CreateController(db, disconnectedGmail.Object, "user-1");
var disconnectedResult = await disconnectedController.RefreshLinkedThreads(new GmailController.RefreshLinkedThreadsRequest(linkedJob.Id), CancellationToken.None);
var disconnectedResult = await disconnectedController.RefreshLinkedThreads(new RefreshLinkedThreadsRequest(linkedJob.Id), CancellationToken.None);
var conflict = Assert.IsType<ConflictObjectResult>(disconnectedResult.Result);
Assert.Equal("Connect Gmail before refreshing linked threads.", conflict.Value);
@@ -469,10 +469,10 @@ public sealed class GmailControllerTests
gmail.Setup(service => service.GetConnectionAsync("user-1", It.IsAny<CancellationToken>()))
.ReturnsAsync(new GmailConnection { OwnerUserId = "user-1", GmailAddress = "user@example.test", EncryptedRefreshToken = "ignored", Scope = "scope", ConnectedAt = DateTimeOffset.UtcNow });
var controller = CreateController(db, gmail.Object, "user-1");
var emptyResult = await controller.RefreshLinkedThreads(new GmailController.RefreshLinkedThreadsRequest(emptyJob.Id), CancellationToken.None);
var emptyResult = await controller.RefreshLinkedThreads(new RefreshLinkedThreadsRequest(emptyJob.Id), CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(emptyResult.Result);
var payload = Assert.IsType<GmailController.GmailThreadRefreshResultDto>(ok.Value);
var payload = Assert.IsType<GmailThreadRefreshResultDto>(ok.Value);
Assert.Equal(0, payload.ThreadsChecked);
Assert.Equal(0, payload.Imported);
Assert.Equal(0, payload.Skipped);
@@ -526,7 +526,7 @@ public sealed class GmailControllerTests
var result = await controller.ReviewCandidates(null, 6, CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result.Result);
var payload = Assert.IsType<GmailController.GmailReviewQueueResponseDto>(ok.Value);
var payload = Assert.IsType<GmailReviewQueueResponseDto>(ok.Value);
Assert.Equal(1, payload.CandidateThreadCount);
Assert.Single(payload.Threads);
Assert.Equal("thread-top", payload.Threads[0].ThreadId);
@@ -541,7 +541,7 @@ public sealed class GmailControllerTests
var gmail = new Mock<IGmailOAuthService>(MockBehavior.Strict);
var controller = CreateController(db, gmail.Object, "user-1");
var result = await controller.RefreshLinkedThreads(new GmailController.RefreshLinkedThreadsRequest(0), CancellationToken.None);
var result = await controller.RefreshLinkedThreads(new RefreshLinkedThreadsRequest(0), CancellationToken.None);
var badRequest = Assert.IsType<BadRequestObjectResult>(result.Result);
Assert.Equal("Valid jobApplicationId is required.", badRequest.Value);
@@ -566,7 +566,7 @@ public sealed class GmailControllerTests
var gmail = new Mock<IGmailOAuthService>(MockBehavior.Strict);
var controller = CreateController(db, gmail.Object, "user-1");
var result = await controller.RefreshLinkedThreads(new GmailController.RefreshLinkedThreadsRequest(foreignJob.Id), CancellationToken.None);
var result = await controller.RefreshLinkedThreads(new RefreshLinkedThreadsRequest(foreignJob.Id), CancellationToken.None);
var notFound = Assert.IsType<NotFoundObjectResult>(result.Result);
Assert.Equal("Job application not found.", notFound.Value);
@@ -639,7 +639,7 @@ public sealed class GmailControllerTests
Array.Empty<GmailMessageAttachment>()));
var controller = CreateController(db, gmail.Object, "user-1");
var result = await controller.SaveReviewDecision(new GmailController.SaveGmailReviewDecisionRequest("thread-1", "linked", job.Id, "Strong recruiter match"), CancellationToken.None);
var result = await controller.SaveReviewDecision(new SaveGmailReviewDecisionRequest("thread-1", "linked", job.Id, "Strong recruiter match"), CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result);
var decision = await db.GmailReviewDecisions.SingleAsync();
@@ -719,10 +719,10 @@ public sealed class GmailControllerTests
Array.Empty<GmailMessageAttachment>()));
var controller = CreateController(db, gmail.Object, "user-1");
var result = await controller.ManualSync(new GmailController.GmailManualSyncRequest(365, 8, true, false), CancellationToken.None);
var result = await controller.ManualSync(new GmailManualSyncRequest(365, 8, true, false), CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result.Result);
var payload = Assert.IsType<GmailController.GmailManualSyncResultDto>(ok.Value);
var payload = Assert.IsType<GmailManualSyncResultDto>(ok.Value);
Assert.Equal(1, payload.AutoLinkedThreadCount);
Assert.Equal(1, payload.ImportedThreads);
Assert.Equal(1, payload.ImportedMessages);
@@ -770,7 +770,7 @@ public sealed class GmailControllerTests
var controller = CreateController(db, gmail.Object, "user-1");
var reviewQueue = new GmailController.GmailReviewQueueResponseDto(
var reviewQueue = new GmailReviewQueueResponseDto(
Array.Empty<string>(),
1,
0,
@@ -778,7 +778,7 @@ public sealed class GmailControllerTests
1,
new[]
{
new GmailController.GmailReviewThreadDto(
new GmailReviewThreadDto(
"thread-suggested",
"Platform Engineer interview",
DateTimeOffset.UtcNow.AddDays(-1),
@@ -787,10 +787,10 @@ public sealed class GmailControllerTests
false,
null,
Array.Empty<string>(),
Array.Empty<GmailController.GmailReviewJobCandidateDto>(),
Array.Empty<GmailReviewJobCandidateDto>(),
new[]
{
new GmailController.GmailJobMatchedMessageDto(
new GmailJobMatchedMessageDto(
"msg-s1",
"thread-suggested",
"Platform Engineer interview",
@@ -802,16 +802,16 @@ public sealed class GmailControllerTests
"low",
false,
Array.Empty<string>(),
Array.Empty<GmailController.GmailJobMatchReasonDto>())
Array.Empty<GmailJobMatchReasonDto>())
})
});
var suggested = Assert.IsType<OkObjectResult>((await controller.SuggestedJobs(CancellationToken.None)).Result);
Assert.IsType<GmailController.GmailSuggestedJobsResponseDto>(suggested.Value);
Assert.IsType<GmailSuggestedJobsResponseDto>(suggested.Value);
var create = await controller.CreateSuggestedJob(new GmailController.CreateSuggestedGmailJobRequest("thread-suggested", "Beta", "Platform Engineer", "Nina Recruiter", "nina@beta.test", "Create from Gmail suggestion", "Applied"), CancellationToken.None);
var create = await controller.CreateSuggestedJob(new CreateSuggestedGmailJobRequest("thread-suggested", "Beta", "Platform Engineer", "Nina Recruiter", "nina@beta.test", "Create from Gmail suggestion", "Applied"), CancellationToken.None);
var createOk = Assert.IsType<OkObjectResult>(create.Result);
var created = Assert.IsType<GmailController.CreatedSuggestedGmailJobDto>(createOk.Value);
var created = Assert.IsType<CreatedSuggestedGmailJobDto>(createOk.Value);
Assert.True(created.JobApplicationId > 0);
Assert.Equal(1, created.Imported);
Assert.Equal("thread-suggested", created.ThreadId);
@@ -837,10 +837,10 @@ public sealed class GmailControllerTests
await db.SaveChangesAsync();
var controller = CreateController(db, Mock.Of<IGmailOAuthService>(), "user-1");
var result = await controller.UnlinkThread(new GmailController.UnlinkGmailThreadRequest(job.Id, "thread-1", "Need manual review", "review"), CancellationToken.None);
var result = await controller.UnlinkThread(new UnlinkGmailThreadRequest(job.Id, "thread-1", "Need manual review", "review"), CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result.Result);
var payload = Assert.IsType<GmailController.GmailUnlinkResultDto>(ok.Value);
var payload = Assert.IsType<GmailUnlinkResultDto>(ok.Value);
Assert.Equal(2, payload.RemovedMessages);
Assert.Equal("review", payload.Decision);
Assert.Empty(await db.Correspondences.ToListAsync());
@@ -895,10 +895,10 @@ public sealed class GmailControllerTests
Array.Empty<GmailMessageAttachment>()));
var controller = CreateController(db, gmail.Object, "user-1");
var result = await controller.RelinkThread(new GmailController.RelinkGmailThreadRequest(targetJob.Id, "thread-1", true, "Move to target"), CancellationToken.None);
var result = await controller.RelinkThread(new RelinkGmailThreadRequest(targetJob.Id, "thread-1", true, "Move to target"), CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result.Result);
var payload = Assert.IsType<GmailController.GmailRelinkResultDto>(ok.Value);
var payload = Assert.IsType<GmailRelinkResultDto>(ok.Value);
Assert.Equal(1, payload.UnlinkedMessages);
Assert.Equal(1, payload.Imported);
var stored = await db.Correspondences.SingleAsync();
@@ -39,7 +39,7 @@ public sealed class JobApplicationsApplicationPackageTests
await db.SaveChangesAsync();
var controller = CreateController(db, Mock.Of<ISummarizerService>(), "user-1");
var result = await controller.SaveApplicationDrafts(job.Id, new JobApplicationsController.SaveApplicationDraftsRequest(null, "Updated notes block", null), CancellationToken.None);
var result = await controller.SaveApplicationDrafts(job.Id, new SaveApplicationDraftsRequest(null, "Updated notes block", null), CancellationToken.None);
Assert.IsType<NoContentResult>(result);
var saved = await db.JobApplications.FirstAsync();
@@ -135,7 +135,7 @@ public sealed class JobApplicationsApplicationPackageTests
var result = await controller.GenerateApplicationPackage(job.Id, null, null, null, CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result.Result);
var payload = Assert.IsType<JobApplicationsController.GenerateApplicationPackageDto>(ok.Value);
var payload = Assert.IsType<GenerateApplicationPackageDto>(ok.Value);
Assert.Contains("Tailored CV", payload.TailoredCvText);
Assert.Equal("Cover letter tailored with recruiter context and imported correspondence.", payload.CoverLetterDraft);
@@ -261,7 +261,7 @@ public sealed class JobApplicationsApplicationPackageTests
var result = await controller.GetTailoredCvDraft(job.Id, CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result.Result);
var payload = Assert.IsType<JobApplicationsController.TailoredCvDraftDto>(ok.Value);
var payload = Assert.IsType<TailoredCvDraftDto>(ok.Value);
Assert.True(payload.IsLegacyFallback);
Assert.Equal("legacy-text", payload.TemplateId);
Assert.Contains("Existing tailored CV text", payload.RenderedText);
@@ -337,14 +337,14 @@ public sealed class JobApplicationsApplicationPackageTests
var controller = CreateController(db, summarizer.Object, "user-1");
var generateResult = await controller.GenerateTailoredCvDraft(job.Id, "ats", CancellationToken.None);
var generateOk = Assert.IsType<OkObjectResult>(generateResult.Result);
var generated = Assert.IsType<JobApplicationsController.TailoredCvDraftDto>(generateOk.Value);
var generated = Assert.IsType<TailoredCvDraftDto>(generateOk.Value);
Assert.False(generated.IsLegacyFallback);
Assert.Equal(7, generated.CanonicalProfileVersion);
Assert.Equal("Senior Backend Engineer", generated.Headline);
Assert.Contains("Led backend API delivery.", generated.RenderedText);
var saveResult = await controller.SaveTailoredCvDraft(job.Id, new JobApplicationsController.SaveTailoredCvDraftRequest(
var saveResult = await controller.SaveTailoredCvDraft(job.Id, new SaveTailoredCvDraftRequest(
generated.TemplateId,
"Principal Backend Engineer",
new List<string> { "Own backend delivery for critical APIs." },
@@ -395,7 +395,7 @@ public sealed class JobApplicationsApplicationPackageTests
var renderer = new TestCvTemplateRenderer();
var exporter = new TestCvPdfExporter();
var controller = CreateController(db, Mock.Of<ISummarizerService>(), "user-1", renderer, exporter);
var request = new JobApplicationsController.TailoredCvRenderRequest(
var request = new TailoredCvRenderRequest(
"ats-minimal",
"Backend Engineer",
new List<string> { "Built APIs" },
@@ -409,7 +409,7 @@ public sealed class JobApplicationsApplicationPackageTests
var previewResult = await controller.PreviewTailoredCv(job.Id, request, CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(previewResult.Result);
var preview = Assert.IsType<JobApplicationsController.TailoredCvPreviewDto>(ok.Value);
var preview = Assert.IsType<TailoredCvPreviewDto>(ok.Value);
Assert.Equal("ats-minimal", preview.TemplateId);
Assert.Equal("preview.pdf", preview.SuggestedFileName);
Assert.Equal("data:image/png;base64,abc123", renderer.LastPhotoDataUrl);
@@ -9,7 +9,7 @@ public sealed class JobApplicationsControllerTests
[Fact]
public void Application_package_record_exposes_expected_fields()
{
var type = typeof(JobApplicationsController).GetNestedType("GenerateApplicationPackageDto", BindingFlags.Public | BindingFlags.NonPublic);
var type = typeof(GenerateApplicationPackageDto);
Assert.NotNull(type);
var props = type!.GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(x => x.Name).ToHashSet();
@@ -23,7 +23,7 @@ public sealed class JobApplicationsControllerTests
[Fact]
public void Save_application_drafts_request_supports_cover_letter_and_notes()
{
var type = typeof(JobApplicationsController).GetNestedType("SaveApplicationDraftsRequest", BindingFlags.Public | BindingFlags.NonPublic);
var type = typeof(SaveApplicationDraftsRequest);
Assert.NotNull(type);
var ctor = type!.GetConstructors().Single();
@@ -28,7 +28,7 @@ public sealed class JobApplicationsEndpointBehaviorTests
await db.SaveChangesAsync();
var controller = CreateController(db, "user-1");
var result = await controller.SaveApplicationDrafts(job.Id, new JobApplicationsController.SaveApplicationDraftsRequest(" Cover letter body ", " Notes body ", null), CancellationToken.None);
var result = await controller.SaveApplicationDrafts(job.Id, new SaveApplicationDraftsRequest(" Cover letter body ", " Notes body ", null), CancellationToken.None);
Assert.IsType<NoContentResult>(result);
var saved = await db.JobApplications.FirstAsync();
@@ -83,7 +83,7 @@ public sealed class JobApplicationsEndpointBehaviorTests
var result = await controller.GetStatusSuggestion(job.Id, CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result.Result);
var dto = Assert.IsType<JobApplicationsController.StatusSuggestionDto>(ok.Value);
var dto = Assert.IsType<StatusSuggestionDto>(ok.Value);
Assert.True(dto.HasSuggestion);
Assert.Equal("Rejected", dto.SuggestedStatus);
}
@@ -114,7 +114,7 @@ public sealed class JobApplicationsEndpointBehaviorTests
var result = await controller.GetStatusSuggestion(job.Id, CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result.Result);
var dto = Assert.IsType<JobApplicationsController.StatusSuggestionDto>(ok.Value);
var dto = Assert.IsType<StatusSuggestionDto>(ok.Value);
Assert.False(dto.HasSuggestion);
}
@@ -147,7 +147,7 @@ public sealed class JobApplicationsEndpointBehaviorTests
var result = await controller.GetMatchScore(job.Id, CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result.Result);
var dto = Assert.IsType<JobApplicationsController.MatchScoreDto>(ok.Value);
var dto = Assert.IsType<MatchScoreDto>(ok.Value);
Assert.True(dto.HasEnoughSignal);
Assert.True(dto.Score >= 75, $"expected strong score, got {dto.Score}");
Assert.Contains("C#", dto.MatchedKeywords);
@@ -181,7 +181,7 @@ public sealed class JobApplicationsEndpointBehaviorTests
await db.SaveChangesAsync();
var controller = CreateController(db, "user-1");
var request = new JobApplicationsController.CreateJobApplicationRequest(
var request = new CreateJobApplicationRequest(
JobTitle: "Backend Dev",
CompanyId: company.Id,
Status: null,
@@ -237,7 +237,7 @@ public sealed class JobApplicationsEndpointBehaviorTests
await db.SaveChangesAsync();
var controller = CreateController(db, "user-1");
var request = new JobApplicationsController.UpdateJobApplicationRequest(
var request = new UpdateJobApplicationRequest(
JobTitle: "Backend Dev",
CompanyId: company.Id,
Status: "Applied",
@@ -92,7 +92,7 @@ public sealed class JobApplicationsFollowUpDraftTests
var result = await controller.GetFollowUpDraft(job.Id, "waiting-update", null, CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result.Result);
var payload = Assert.IsType<JobApplicationsController.FollowUpDraftDto>(ok.Value);
var payload = Assert.IsType<FollowUpDraftDto>(ok.Value);
Assert.Equal("Re: Backend Developer application update", payload.Subject);
Assert.Contains("Maria", payload.Body);
@@ -28,7 +28,7 @@ public sealed class JobApplicationsMariaDraftTests
await db.SaveChangesAsync();
var controller = CreateController(db, "user-1");
var result = await controller.SaveApplicationDrafts(job.Id, new JobApplicationsController.SaveApplicationDraftsRequest(null, null, " Recruiter hello "), CancellationToken.None);
var result = await controller.SaveApplicationDrafts(job.Id, new SaveApplicationDraftsRequest(null, null, " Recruiter hello "), CancellationToken.None);
Assert.IsType<NoContentResult>(result);
var saved = await db.JobApplications.FirstAsync();
@@ -43,7 +43,7 @@ public sealed class JobApplicationsWorkflowSignalsTests
var result = await controller.GetReadiness(job.Id, CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result.Result);
var payload = Assert.IsType<JobApplicationsController.ReadinessDto>(ok.Value);
var payload = Assert.IsType<ReadinessDto>(ok.Value);
Assert.Equal("package-work", payload.WorkflowSignal.ActionKey);
Assert.True(payload.WorkflowSignal.HasPackageGap);
@@ -92,7 +92,7 @@ public sealed class JobApplicationsWorkflowSignalsTests
var result = await controller.GetReminders(14, CancellationToken.None);
var ok = Assert.IsType<OkObjectResult>(result.Result);
var payload = Assert.IsType<List<JobApplicationsController.JobApplicationDto>>(ok.Value);
var payload = Assert.IsType<List<JobApplicationDto>>(ok.Value);
var packageReminder = Assert.Single(payload, item => item.Id == packageGapJob.Id);
Assert.Equal("package-work", packageReminder.WorkflowSignal.ActionKey);
+14 -14
View File
@@ -123,7 +123,7 @@ public sealed class ProfileCvControllerTests
var result = await controller.GetRuns();
var ok = Assert.IsType<OkObjectResult>(result.Result);
var runs = Assert.IsAssignableFrom<IEnumerable<ProfileCvController.CvExtractionRunListItem>>(ok.Value);
var runs = Assert.IsAssignableFrom<IEnumerable<CvExtractionRunListItem>>(ok.Value);
var single = Assert.Single(runs);
Assert.Equal("upload", single.Trigger);
Assert.Equal("applied", single.Status);
@@ -611,7 +611,7 @@ public sealed class ProfileCvControllerTests
var objectResult = Assert.IsType<ObjectResult>(result);
Assert.Equal(StatusCodes.Status502BadGateway, objectResult.StatusCode);
var payload = Assert.IsType<ProfileCvController.CvRewriteFailureDto>(objectResult.Value);
var payload = Assert.IsType<CvRewriteFailureDto>(objectResult.Value);
Assert.Equal("ai-service-unavailable", payload.Code);
Assert.Contains("could not rewrite", payload.Message, StringComparison.OrdinalIgnoreCase);
Assert.Contains("unavailable", payload.Detail ?? string.Empty, StringComparison.OrdinalIgnoreCase);
@@ -673,7 +673,7 @@ public sealed class ProfileCvControllerTests
var objectResult = Assert.IsType<ObjectResult>(result);
Assert.Equal(StatusCodes.Status502BadGateway, objectResult.StatusCode);
var payload = Assert.IsType<ProfileCvController.CvRewriteFailureDto>(objectResult.Value);
var payload = Assert.IsType<CvRewriteFailureDto>(objectResult.Value);
Assert.Equal("rewrite-empty", payload.Code);
Assert.Contains("empty", payload.Message, StringComparison.OrdinalIgnoreCase);
Assert.Contains("no usable text", payload.Detail ?? string.Empty, StringComparison.OrdinalIgnoreCase);
@@ -766,7 +766,7 @@ public sealed class ProfileCvControllerTests
var paths = CreatePaths();
var controller = CreateController(userManager.Object, aiService.Object, db, paths);
var result = await controller.Parse(new ProfileCvController.ParseCvRequest(user.ProfileCvText));
var result = await controller.Parse(new ParseCvRequest(user.ProfileCvText));
var ok = Assert.IsType<OkObjectResult>(result.Result);
var json = JsonSerializer.Serialize(ok.Value);
@@ -800,7 +800,7 @@ public sealed class ProfileCvControllerTests
var paths = CreatePaths();
var controller = CreateController(userManager.Object, aiService.Object, db, paths);
var result = await controller.Parse(new ProfileCvController.ParseCvRequest(user.ProfileCvText));
var result = await controller.Parse(new ParseCvRequest(user.ProfileCvText));
var ok = Assert.IsType<OkObjectResult>(result.Result);
var json = JsonSerializer.Serialize(ok.Value);
@@ -838,7 +838,7 @@ public sealed class ProfileCvControllerTests
var paths = CreatePaths();
var controller = CreateController(userManager.Object, aiService.Object, db, paths, classifier.Object);
var result = await controller.Parse(new ProfileCvController.ParseCvRequest(source));
var result = await controller.Parse(new ParseCvRequest(source));
var ok = Assert.IsType<OkObjectResult>(result.Result);
var json = JsonSerializer.Serialize(ok.Value);
@@ -878,7 +878,7 @@ public sealed class ProfileCvControllerTests
var paths = CreatePaths();
var controller = CreateController(userManager.Object, aiService.Object, db, paths, classifier.Object);
var result = await controller.Parse(new ProfileCvController.ParseCvRequest(source));
var result = await controller.Parse(new ParseCvRequest(source));
var ok = Assert.IsType<OkObjectResult>(result.Result);
var json = JsonSerializer.Serialize(ok.Value);
@@ -914,7 +914,7 @@ public sealed class ProfileCvControllerTests
var paths = CreatePaths();
var controller = CreateController(userManager.Object, aiService.Object, db, paths, classifier.Object);
var result = await controller.Parse(new ProfileCvController.ParseCvRequest(source));
var result = await controller.Parse(new ParseCvRequest(source));
var ok = Assert.IsType<OkObjectResult>(result.Result);
var json = JsonSerializer.Serialize(ok.Value);
@@ -1030,7 +1030,7 @@ public sealed class ProfileCvControllerTests
await using var db = CreateDb();
var controller = CreateController(userManager.Object, aiService.Object, db, CreatePaths(), null, normalizer.Object);
var result = await controller.Parse(new ProfileCvController.ParseCvRequest(source));
var result = await controller.Parse(new ParseCvRequest(source));
Assert.IsType<OkObjectResult>(result.Result);
var actual = StructuredCvProfileJson.Deserialize(user.ProfileCvStructureJson);
@@ -1069,7 +1069,7 @@ public sealed class ProfileCvControllerTests
var paths = CreatePaths();
var controller = CreateController(userManager.Object, aiService.Object, db, paths);
var result = await controller.Parse(new ProfileCvController.ParseCvRequest(rawSource));
var result = await controller.Parse(new ParseCvRequest(rawSource));
var ok = Assert.IsType<OkObjectResult>(result.Result);
Assert.NotNull(ok.Value);
@@ -1098,7 +1098,7 @@ public sealed class ProfileCvControllerTests
await using var db = CreateDb();
var controller = CreateController(userManager.Object, aiService.Object, db, CreatePaths());
var result = await controller.Parse(new ProfileCvController.ParseCvRequest(source));
var result = await controller.Parse(new ParseCvRequest(source));
Assert.IsType<OkObjectResult>(result.Result);
var actual = StructuredCvProfileJson.Deserialize(user.ProfileCvStructureJson);
@@ -1129,7 +1129,7 @@ public sealed class ProfileCvControllerTests
await using var db = CreateDb();
var controller = CreateController(userManager.Object, aiService.Object, db, CreatePaths());
var result = await controller.Parse(new ProfileCvController.ParseCvRequest(source));
var result = await controller.Parse(new ParseCvRequest(source));
Assert.IsType<OkObjectResult>(result.Result);
var actual = StructuredCvProfileJson.Deserialize(user.ProfileCvStructureJson);
@@ -1158,7 +1158,7 @@ public sealed class ProfileCvControllerTests
await using var db = CreateDb();
var controller = CreateController(userManager.Object, aiService.Object, db, CreatePaths());
var result = await controller.Parse(new ProfileCvController.ParseCvRequest(source));
var result = await controller.Parse(new ParseCvRequest(source));
Assert.IsType<OkObjectResult>(result.Result);
var actual = StructuredCvProfileJson.Deserialize(user.ProfileCvStructureJson);
@@ -1186,7 +1186,7 @@ public sealed class ProfileCvControllerTests
await using var db = CreateDb();
var controller = CreateController(userManager.Object, aiService.Object, db, CreatePaths());
var result = await controller.Parse(new ProfileCvController.ParseCvRequest(source));
var result = await controller.Parse(new ParseCvRequest(source));
Assert.IsType<OkObjectResult>(result.Result);
var actual = StructuredCvProfileJson.Deserialize(user.ProfileCvStructureJson);
@@ -1,242 +0,0 @@
using System.Security.Claims;
using JobTrackerApi.Controllers;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using JobTrackerApi.Tests.TestSupport;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using OtpNet;
using Xunit;
namespace JobTrackerApi.Tests;
public sealed class SessionsControllerTests
{
private static IConfiguration BuildConfig() =>
new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>()).Build();
private static SessionsController BuildController(JobTrackerContext db, ApplicationUser user, string? currentSid = null)
{
var userManager = TestHostFactory.CreateUserManager();
userManager.Setup(x => x.GetUserAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(user);
var claims = new List<Claim> { new(ClaimTypes.NameIdentifier, user.Id) };
if (currentSid is not null) claims.Add(new Claim("sid", currentSid));
return new SessionsController(userManager.Object, db)
{
ControllerContext = new ControllerContext
{
HttpContext = new DefaultHttpContext { User = new ClaimsPrincipal(new ClaimsIdentity(claims, "local")) }
}
};
}
private static UserSession NewSession(string id, string userId, DateTimeOffset? expiresAtUtc = null, DateTimeOffset? revokedAtUtc = null, DateTimeOffset? lastSeenAtUtc = null)
{
var now = DateTimeOffset.UtcNow;
return new UserSession
{
Id = id,
UserId = userId,
DeviceLabel = "Chrome on Windows",
CreatedAtUtc = now,
LastSeenAtUtc = lastSeenAtUtc ?? now,
ExpiresAtUtc = expiresAtUtc ?? now.AddHours(12),
RevokedAtUtc = revokedAtUtc,
};
}
// --- Session creation on every sign-in path -----------------------------------------------
[Fact]
public async Task Login_creates_a_user_session_row_and_threads_its_id_into_the_token()
{
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com" };
var userManager = TestHostFactory.CreateUserManager();
userManager.Setup(x => x.FindByEmailAsync("person@example.com")).ReturnsAsync(user);
userManager.Setup(x => x.FindByNameAsync("person@example.com")).ReturnsAsync((ApplicationUser?)null);
userManager.Setup(x => x.IsLockedOutAsync(user)).ReturnsAsync(false);
userManager.Setup(x => x.CheckPasswordAsync(user, "correct-password")).ReturnsAsync(true);
userManager.Setup(x => x.ResetAccessFailedCountAsync(user)).ReturnsAsync(IdentityResult.Success);
string? sessionIdPassedToToken = null;
var tokenService = new Mock<ITokenService>();
tokenService
.Setup(x => x.CreateAccessTokenAsync(user, It.IsAny<string?>(), It.IsAny<CancellationToken>()))
.Callback<ApplicationUser, string?, CancellationToken>((_, sid, _) => sessionIdPassedToToken = sid)
.ReturnsAsync("app-token");
using var db = TestHostFactory.CreateInMemoryDb(null);
var controller = new AuthController(BuildConfig(), userManager.Object, tokenService.Object, Mock.Of<IAppEmailSender>(), Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(), NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), db)
{
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};
await controller.Login(new AuthController.LoginRequest("person@example.com", "correct-password"), CancellationToken.None);
var sessions = await db.UserSessions.IgnoreQueryFilters().Where(x => x.UserId == "user-1").ToListAsync();
var created = Assert.Single(sessions);
Assert.False(string.IsNullOrWhiteSpace(created.Id));
Assert.Equal(created.Id, sessionIdPassedToToken);
Assert.Null(created.RevokedAtUtc);
Assert.True(created.ExpiresAtUtc > DateTimeOffset.UtcNow);
}
[Fact]
public async Task Register_creates_a_user_session_row_when_it_completes_sign_in()
{
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?> { ["Auth:AllowRegistration"] = "true" })
.Build();
var userManager = TestHostFactory.CreateUserManager();
userManager.Setup(x => x.FindByEmailAsync("new.user@example.com")).ReturnsAsync((ApplicationUser?)null);
ApplicationUser? created = null;
userManager
.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), "password123"))
.Callback<ApplicationUser, string>((u, _) => { u.Id = "new-user-1"; created = u; })
.ReturnsAsync(IdentityResult.Success);
var tokenService = new Mock<ITokenService>();
tokenService.Setup(x => x.CreateAccessTokenAsync(It.IsAny<ApplicationUser>(), It.IsAny<string?>(), It.IsAny<CancellationToken>())).ReturnsAsync("app-token");
using var db = TestHostFactory.CreateInMemoryDb(null);
var controller = new AuthController(config, userManager.Object, tokenService.Object, Mock.Of<IAppEmailSender>(), Mock.Of<IGoogleTokenValidator>(), Mock.Of<IMicrosoftTokenValidator>(), NullLogger<AuthController>.Instance, Mock.Of<ITwoFactorPendingTokenService>(), db)
{
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};
await controller.Register(new AuthController.RegisterRequest("new.user@example.com", "password123"), CancellationToken.None);
Assert.NotNull(created);
var sessions = await db.UserSessions.IgnoreQueryFilters().Where(x => x.UserId == created!.Id).ToListAsync();
Assert.Single(sessions);
}
[Fact]
public async Task TwoFactor_challenge_creates_a_user_session_row_on_completion()
{
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com" };
var userManager = TestHostFactory.CreateUserManager();
userManager.Setup(x => x.CheckPasswordAsync(user, "correct-password")).ReturnsAsync(true);
userManager.Setup(x => x.UpdateAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(IdentityResult.Success);
userManager.Setup(x => x.FindByIdAsync("user-1")).ReturnsAsync(user);
userManager.Setup(x => x.GetUserAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(user);
var pending = new TwoFactorPendingTokenService(new Microsoft.Extensions.Caching.Memory.MemoryCache(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions()));
var protector = new EphemeralDataProtectionProvider();
var tokenService = new Mock<ITokenService>();
tokenService.Setup(x => x.CreateAccessTokenAsync(It.IsAny<ApplicationUser>(), It.IsAny<string?>(), It.IsAny<CancellationToken>())).ReturnsAsync("app-token");
using var db = TestHostFactory.CreateInMemoryDb("user-1");
var controller = new TwoFactorController(userManager.Object, tokenService.Object, db, pending, protector, BuildConfig())
{
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};
var setupResult = Assert.IsType<OkObjectResult>(await controller.Setup(new TwoFactorController.PasswordConfirmRequest("correct-password"), CancellationToken.None));
var setup = Assert.IsType<TwoFactorController.SetupResult>(setupResult.Value);
var setupCode = new Totp(Base32Encoding.ToBytes(setup.ManualEntryKey)).ComputeTotp();
await controller.VerifySetup(new TwoFactorController.VerifySetupRequest(setupCode), CancellationToken.None);
var pendingToken = pending.IssuePendingToken("user-1", rememberMe: false);
var challengeCode = new Totp(Base32Encoding.ToBytes(setup.ManualEntryKey)).ComputeTotp();
Assert.IsType<OkObjectResult>(await controller.Challenge(new TwoFactorController.ChallengeRequest(pendingToken, challengeCode), CancellationToken.None));
var sessions = await db.UserSessions.IgnoreQueryFilters().Where(x => x.UserId == "user-1").ToListAsync();
Assert.Single(sessions);
}
// --- List/revoke ----------------------------------------------------------------------------
[Fact]
public async Task List_returns_only_the_callers_own_active_sessions()
{
using var db = TestHostFactory.CreateInMemoryDb("user-1");
db.UserSessions.Add(NewSession("sid-mine", "user-1"));
db.UserSessions.Add(NewSession("sid-other-user", "user-2"));
db.UserSessions.Add(NewSession("sid-mine-expired", "user-1", expiresAtUtc: DateTimeOffset.UtcNow.AddHours(-1)));
db.UserSessions.Add(NewSession("sid-mine-revoked", "user-1", revokedAtUtc: DateTimeOffset.UtcNow.AddMinutes(-1)));
await db.SaveChangesAsync();
var controller = BuildController(db, new ApplicationUser { Id = "user-1" }, currentSid: "sid-mine");
var ok = Assert.IsType<OkObjectResult>(await controller.List(CancellationToken.None));
var list = Assert.IsType<List<SessionsController.SessionDto>>(ok.Value);
var only = Assert.Single(list);
Assert.Equal("sid-mine", only.Id);
Assert.True(only.IsCurrentSession);
}
[Fact]
public async Task Revoke_enforces_ownership_and_blocks_a_subsequent_request_using_that_sessions_token()
{
using var db = TestHostFactory.CreateInMemoryDb("user-1");
db.UserSessions.Add(NewSession("sid-mine", "user-1"));
db.UserSessions.Add(NewSession("sid-not-mine", "user-2"));
await db.SaveChangesAsync();
var controller = BuildController(db, new ApplicationUser { Id = "user-1" }, currentSid: "sid-mine");
// Can't revoke someone else's session.
var forbidden = await controller.Revoke("sid-not-mine", CancellationToken.None);
Assert.IsType<NotFoundResult>(forbidden);
Assert.True(await LocalSessionValidator.IsValidAsync(db, PrincipalWithSid("sid-not-mine"), DateTimeOffset.UtcNow));
// Revoking your own session actually blocks it going forward.
Assert.True(await LocalSessionValidator.IsValidAsync(db, PrincipalWithSid("sid-mine"), DateTimeOffset.UtcNow));
var ownResult = await controller.Revoke("sid-mine", CancellationToken.None);
Assert.IsType<NoContentResult>(ownResult);
Assert.False(await LocalSessionValidator.IsValidAsync(db, PrincipalWithSid("sid-mine"), DateTimeOffset.UtcNow));
}
[Fact]
public async Task RevokeOthers_revokes_every_other_session_but_leaves_the_current_one_usable()
{
using var db = TestHostFactory.CreateInMemoryDb("user-1");
db.UserSessions.Add(NewSession("sid-current", "user-1"));
db.UserSessions.Add(NewSession("sid-other-device", "user-1"));
db.UserSessions.Add(NewSession("sid-not-mine", "user-2"));
await db.SaveChangesAsync();
var controller = BuildController(db, new ApplicationUser { Id = "user-1" }, currentSid: "sid-current");
Assert.IsType<NoContentResult>(await controller.RevokeOthers(CancellationToken.None));
Assert.True(await LocalSessionValidator.IsValidAsync(db, PrincipalWithSid("sid-current"), DateTimeOffset.UtcNow));
Assert.False(await LocalSessionValidator.IsValidAsync(db, PrincipalWithSid("sid-other-device"), DateTimeOffset.UtcNow));
// Untouched: revoke-others must never reach across users.
Assert.True(await LocalSessionValidator.IsValidAsync(db, PrincipalWithSid("sid-not-mine"), DateTimeOffset.UtcNow));
}
[Fact]
public async Task LocalSessionValidator_rejects_an_expired_session()
{
using var db = TestHostFactory.CreateInMemoryDb("user-1");
db.UserSessions.Add(NewSession("sid-expired", "user-1", expiresAtUtc: DateTimeOffset.UtcNow.AddSeconds(-1)));
await db.SaveChangesAsync();
Assert.False(await LocalSessionValidator.IsValidAsync(db, PrincipalWithSid("sid-expired"), DateTimeOffset.UtcNow));
}
[Fact]
public async Task LocalSessionValidator_rejects_a_token_with_no_sid_claim()
{
using var db = TestHostFactory.CreateInMemoryDb("user-1");
var principal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "user-1") }, "local"));
Assert.False(await LocalSessionValidator.IsValidAsync(db, principal, DateTimeOffset.UtcNow));
}
private static ClaimsPrincipal PrincipalWithSid(string sid) =>
new(new ClaimsIdentity(new[] { new Claim("sid", sid) }, "local"));
}
@@ -1,280 +0,0 @@
using JobTrackerApi.Controllers;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using JobTrackerApi.Tests.TestSupport;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Moq;
using OtpNet;
using Xunit;
namespace JobTrackerApi.Tests;
public sealed class TwoFactorControllerTests
{
private static TwoFactorController BuildController(Mock<UserManager<ApplicationUser>> userManager, JobTrackerApi.Data.JobTrackerContext db, ITwoFactorPendingTokenService? pending = null, ApplicationUser? currentUser = null)
{
if (currentUser is not null)
{
userManager.Setup(x => x.GetUserAsync(It.IsAny<System.Security.Claims.ClaimsPrincipal>())).ReturnsAsync(currentUser);
}
var tokenService = new Mock<ITokenService>();
tokenService.Setup(x => x.CreateAccessTokenAsync(It.IsAny<ApplicationUser>(), It.IsAny<string?>(), It.IsAny<CancellationToken>())).ReturnsAsync("app-token");
var controller = new TwoFactorController(
userManager.Object,
tokenService.Object,
db,
pending ?? new TwoFactorPendingTokenService(new Microsoft.Extensions.Caching.Memory.MemoryCache(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions())),
new EphemeralDataProtectionProvider(),
new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>()).Build())
{
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};
return controller;
}
[Fact]
public async Task Setup_then_verify_with_correct_code_enables_2fa_and_returns_recovery_codes()
{
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com" };
var userManager = TestHostFactory.CreateUserManager();
userManager.Setup(x => x.CheckPasswordAsync(user, "correct-password")).ReturnsAsync(true);
userManager.Setup(x => x.UpdateAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(IdentityResult.Success);
using var db = TestHostFactory.CreateInMemoryDb("user-1");
var controller = BuildController(userManager, db, currentUser: user);
var setupResult = Assert.IsType<OkObjectResult>(await controller.Setup(new TwoFactorController.PasswordConfirmRequest("correct-password"), CancellationToken.None));
var setup = Assert.IsType<TwoFactorController.SetupResult>(setupResult.Value);
Assert.NotNull(user.TotpPendingSecretEncrypted);
Assert.False(user.TwoFactorEnabled);
var code = new Totp(Base32Encoding.ToBytes(setup.ManualEntryKey)).ComputeTotp();
var verifyResult = Assert.IsType<OkObjectResult>(await controller.VerifySetup(new TwoFactorController.VerifySetupRequest(code), CancellationToken.None));
var verify = Assert.IsType<TwoFactorController.VerifySetupResult>(verifyResult.Value);
Assert.True(verify.Enabled);
Assert.Equal(10, verify.RecoveryCodes.Count);
Assert.True(user.TwoFactorEnabled);
Assert.Null(user.TotpPendingSecretEncrypted);
Assert.NotNull(user.TotpSecretEncrypted);
Assert.NotNull(user.TotpEnabledAtUtc);
}
[Fact]
public async Task Verify_setup_with_wrong_code_is_rejected_and_does_not_enable_2fa()
{
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com" };
var userManager = TestHostFactory.CreateUserManager();
userManager.Setup(x => x.CheckPasswordAsync(user, "correct-password")).ReturnsAsync(true);
userManager.Setup(x => x.UpdateAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(IdentityResult.Success);
using var db = TestHostFactory.CreateInMemoryDb("user-1");
var controller = BuildController(userManager, db, currentUser: user);
await controller.Setup(new TwoFactorController.PasswordConfirmRequest("correct-password"), CancellationToken.None);
var result = await controller.VerifySetup(new TwoFactorController.VerifySetupRequest("000000"), CancellationToken.None);
Assert.IsType<UnauthorizedResult>(result);
Assert.False(user.TwoFactorEnabled);
}
[Fact]
public async Task Disable_with_wrong_password_is_rejected()
{
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com", TwoFactorEnabled = true, TotpSecretEncrypted = "irrelevant" };
var userManager = TestHostFactory.CreateUserManager();
userManager.Setup(x => x.CheckPasswordAsync(user, "wrong-password")).ReturnsAsync(false);
using var db = TestHostFactory.CreateInMemoryDb("user-1");
var controller = BuildController(userManager, db, currentUser: user);
var result = await controller.Disable(new TwoFactorController.PasswordConfirmRequest("wrong-password"), CancellationToken.None);
Assert.IsType<BadRequestObjectResult>(result);
Assert.True(user.TwoFactorEnabled);
Assert.NotNull(user.TotpSecretEncrypted);
}
[Fact]
public async Task Challenge_with_valid_totp_code_completes_sign_in()
{
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com" };
var userManager = TestHostFactory.CreateUserManager();
userManager.Setup(x => x.CheckPasswordAsync(user, "correct-password")).ReturnsAsync(true);
userManager.Setup(x => x.UpdateAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(IdentityResult.Success);
userManager.Setup(x => x.FindByIdAsync("user-1")).ReturnsAsync(user);
var pending = new TwoFactorPendingTokenService(new Microsoft.Extensions.Caching.Memory.MemoryCache(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions()));
using var db = TestHostFactory.CreateInMemoryDb("user-1");
var controller = BuildController(userManager, db, pending, currentUser: user);
var setupResult = Assert.IsType<OkObjectResult>(await controller.Setup(new TwoFactorController.PasswordConfirmRequest("correct-password"), CancellationToken.None));
var setup = Assert.IsType<TwoFactorController.SetupResult>(setupResult.Value);
var code = new Totp(Base32Encoding.ToBytes(setup.ManualEntryKey)).ComputeTotp();
await controller.VerifySetup(new TwoFactorController.VerifySetupRequest(code), CancellationToken.None);
var pendingToken = pending.IssuePendingToken("user-1", rememberMe: false);
var challengeCode = new Totp(Base32Encoding.ToBytes(setup.ManualEntryKey)).ComputeTotp();
var challengeResult = Assert.IsType<OkObjectResult>(await controller.Challenge(new TwoFactorController.ChallengeRequest(pendingToken, challengeCode), CancellationToken.None));
var session = Assert.IsType<AuthController.AuthSessionResult>(challengeResult.Value);
Assert.True(session.Authenticated);
// The pending token is single-use.
var reuse = await controller.Challenge(new TwoFactorController.ChallengeRequest(pendingToken, challengeCode), CancellationToken.None);
Assert.IsType<UnauthorizedResult>(reuse);
}
[Fact]
public async Task Challenge_with_recovery_code_consumes_it_and_rejects_reuse()
{
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com" };
var userManager = TestHostFactory.CreateUserManager();
userManager.Setup(x => x.CheckPasswordAsync(user, "correct-password")).ReturnsAsync(true);
userManager.Setup(x => x.UpdateAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(IdentityResult.Success);
userManager.Setup(x => x.FindByIdAsync("user-1")).ReturnsAsync(user);
var pending = new TwoFactorPendingTokenService(new Microsoft.Extensions.Caching.Memory.MemoryCache(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions()));
using var db = TestHostFactory.CreateInMemoryDb("user-1");
var controller = BuildController(userManager, db, pending, currentUser: user);
var setupResult = Assert.IsType<OkObjectResult>(await controller.Setup(new TwoFactorController.PasswordConfirmRequest("correct-password"), CancellationToken.None));
var setup = Assert.IsType<TwoFactorController.SetupResult>(setupResult.Value);
var code = new Totp(Base32Encoding.ToBytes(setup.ManualEntryKey)).ComputeTotp();
var verifyResult = Assert.IsType<OkObjectResult>(await controller.VerifySetup(new TwoFactorController.VerifySetupRequest(code), CancellationToken.None));
var verify = Assert.IsType<TwoFactorController.VerifySetupResult>(verifyResult.Value);
var recoveryCode = verify.RecoveryCodes[0];
var pendingToken1 = pending.IssuePendingToken("user-1", rememberMe: false);
var challengeResult = Assert.IsType<OkObjectResult>(await controller.Challenge(new TwoFactorController.ChallengeRequest(pendingToken1, recoveryCode), CancellationToken.None));
Assert.True(Assert.IsType<AuthController.AuthSessionResult>(challengeResult.Value).Authenticated);
// Same recovery code can't be used a second time, even against a fresh pending token.
var pendingToken2 = pending.IssuePendingToken("user-1", rememberMe: false);
var reuse = await controller.Challenge(new TwoFactorController.ChallengeRequest(pendingToken2, recoveryCode), CancellationToken.None);
Assert.IsType<UnauthorizedResult>(reuse);
}
[Fact]
public async Task Challenge_with_trust_device_true_creates_trusted_device_and_sets_cookie()
{
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com" };
var userManager = TestHostFactory.CreateUserManager();
userManager.Setup(x => x.CheckPasswordAsync(user, "correct-password")).ReturnsAsync(true);
userManager.Setup(x => x.UpdateAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(IdentityResult.Success);
userManager.Setup(x => x.FindByIdAsync("user-1")).ReturnsAsync(user);
var pending = new TwoFactorPendingTokenService(new Microsoft.Extensions.Caching.Memory.MemoryCache(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions()));
using var db = TestHostFactory.CreateInMemoryDb("user-1");
var controller = BuildController(userManager, db, pending, currentUser: user);
var setupResult = Assert.IsType<OkObjectResult>(await controller.Setup(new TwoFactorController.PasswordConfirmRequest("correct-password"), CancellationToken.None));
var setup = Assert.IsType<TwoFactorController.SetupResult>(setupResult.Value);
var code = new Totp(Base32Encoding.ToBytes(setup.ManualEntryKey)).ComputeTotp();
await controller.VerifySetup(new TwoFactorController.VerifySetupRequest(code), CancellationToken.None);
var pendingToken = pending.IssuePendingToken("user-1", rememberMe: false);
var challengeCode = new Totp(Base32Encoding.ToBytes(setup.ManualEntryKey)).ComputeTotp();
var challengeResult = Assert.IsType<OkObjectResult>(await controller.Challenge(new TwoFactorController.ChallengeRequest(pendingToken, challengeCode, TrustDevice: true), CancellationToken.None));
Assert.True(Assert.IsType<AuthController.AuthSessionResult>(challengeResult.Value).Authenticated);
var device = Assert.Single(db.TrustedDevices.IgnoreQueryFilters().Where(x => x.UserId == "user-1"));
Assert.NotNull(device.TokenHash);
var setCookieHeaders = controller.Response.Headers["Set-Cookie"];
var trustedDeviceCookie = Assert.Single(setCookieHeaders, h => h!.StartsWith($"{AuthSessionOptions.TrustedDeviceCookieName}=", StringComparison.Ordinal))!;
Assert.Contains("httponly", trustedDeviceCookie, StringComparison.OrdinalIgnoreCase);
Assert.Contains("samesite=strict", trustedDeviceCookie, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task Challenge_without_trust_device_does_not_create_trusted_device()
{
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com" };
var userManager = TestHostFactory.CreateUserManager();
userManager.Setup(x => x.CheckPasswordAsync(user, "correct-password")).ReturnsAsync(true);
userManager.Setup(x => x.UpdateAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(IdentityResult.Success);
userManager.Setup(x => x.FindByIdAsync("user-1")).ReturnsAsync(user);
var pending = new TwoFactorPendingTokenService(new Microsoft.Extensions.Caching.Memory.MemoryCache(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions()));
using var db = TestHostFactory.CreateInMemoryDb("user-1");
var controller = BuildController(userManager, db, pending, currentUser: user);
var setupResult = Assert.IsType<OkObjectResult>(await controller.Setup(new TwoFactorController.PasswordConfirmRequest("correct-password"), CancellationToken.None));
var setup = Assert.IsType<TwoFactorController.SetupResult>(setupResult.Value);
var code = new Totp(Base32Encoding.ToBytes(setup.ManualEntryKey)).ComputeTotp();
await controller.VerifySetup(new TwoFactorController.VerifySetupRequest(code), CancellationToken.None);
var pendingToken = pending.IssuePendingToken("user-1", rememberMe: false);
var challengeCode = new Totp(Base32Encoding.ToBytes(setup.ManualEntryKey)).ComputeTotp();
await controller.Challenge(new TwoFactorController.ChallengeRequest(pendingToken, challengeCode), CancellationToken.None);
Assert.Empty(db.TrustedDevices.IgnoreQueryFilters().Where(x => x.UserId == "user-1"));
}
[Fact]
public async Task Trusted_devices_can_be_listed_revoked_and_revoked_in_bulk_scoped_to_owner()
{
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com" };
var otherUser = new ApplicationUser { Id = "user-2", Email = "other@example.com", UserName = "other@example.com" };
var userManager = TestHostFactory.CreateUserManager();
using var db = TestHostFactory.CreateInMemoryDb("user-1");
db.TrustedDevices.Add(new TrustedDevice { UserId = "user-1", TokenHash = "hash-1", DeviceLabel = "Chrome on Windows", CreatedAtUtc = DateTimeOffset.UtcNow, LastSeenAtUtc = DateTimeOffset.UtcNow, ExpiresAtUtc = DateTimeOffset.UtcNow.AddDays(30) });
db.TrustedDevices.Add(new TrustedDevice { UserId = "user-1", TokenHash = "hash-2", DeviceLabel = "Safari on Mac", CreatedAtUtc = DateTimeOffset.UtcNow, LastSeenAtUtc = DateTimeOffset.UtcNow, ExpiresAtUtc = DateTimeOffset.UtcNow.AddDays(30) });
db.TrustedDevices.Add(new TrustedDevice { UserId = "user-2", TokenHash = "hash-3", DeviceLabel = "Someone else's device", CreatedAtUtc = DateTimeOffset.UtcNow, LastSeenAtUtc = DateTimeOffset.UtcNow, ExpiresAtUtc = DateTimeOffset.UtcNow.AddDays(30) });
db.SaveChanges();
var otherDeviceId = db.TrustedDevices.IgnoreQueryFilters().Single(x => x.UserId == "user-2").Id;
var controller = BuildController(userManager, db, currentUser: user);
var listResult = Assert.IsType<OkObjectResult>(await controller.ListTrustedDevices(CancellationToken.None));
var list = Assert.IsType<List<TwoFactorController.TrustedDeviceDto>>(listResult.Value);
Assert.Equal(2, list.Count);
// Can't revoke another user's device, even by guessing its id.
var revokeOther = await controller.RevokeTrustedDevice(otherDeviceId, CancellationToken.None);
Assert.IsType<NotFoundResult>(revokeOther);
Assert.NotNull(db.TrustedDevices.IgnoreQueryFilters().SingleOrDefault(x => x.Id == otherDeviceId));
var ownDeviceId = list[0].Id;
var revokeOwn = await controller.RevokeTrustedDevice(ownDeviceId, CancellationToken.None);
Assert.IsType<NoContentResult>(revokeOwn);
Assert.Null(db.TrustedDevices.IgnoreQueryFilters().SingleOrDefault(x => x.Id == ownDeviceId));
var revokeAll = await controller.RevokeAllTrustedDevices(CancellationToken.None);
Assert.IsType<NoContentResult>(revokeAll);
Assert.Empty(db.TrustedDevices.IgnoreQueryFilters().Where(x => x.UserId == "user-1"));
Assert.NotNull(db.TrustedDevices.IgnoreQueryFilters().SingleOrDefault(x => x.UserId == "user-2"));
}
[Fact]
public async Task Challenge_with_unknown_pending_token_is_rejected()
{
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com" };
var userManager = TestHostFactory.CreateUserManager();
using var db = TestHostFactory.CreateInMemoryDb("user-1");
var controller = BuildController(userManager, db, currentUser: user);
var result = await controller.Challenge(new TwoFactorController.ChallengeRequest("not-a-real-token", "123456"), CancellationToken.None);
Assert.IsType<UnauthorizedResult>(result);
}
}
+20 -152
View File
@@ -1,6 +1,5 @@
using System.Text.Json;
using System.Security.Claims;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using Microsoft.AspNetCore.Authorization;
@@ -22,10 +21,8 @@ public sealed class AuthController : ControllerBase
private readonly IGoogleTokenValidator _googleTokens;
private readonly IMicrosoftTokenValidator _microsoftTokens;
private readonly ILogger<AuthController> _logger;
private readonly ITwoFactorPendingTokenService _twoFactorPending;
private readonly JobTrackerContext _db;
public AuthController(IConfiguration cfg, UserManager<ApplicationUser> users, ITokenService tokens, IAppEmailSender email, IGoogleTokenValidator googleTokens, IMicrosoftTokenValidator microsoftTokens, ILogger<AuthController> logger, ITwoFactorPendingTokenService twoFactorPending, JobTrackerContext db)
public AuthController(IConfiguration cfg, UserManager<ApplicationUser> users, ITokenService tokens, IAppEmailSender email, IGoogleTokenValidator googleTokens, IMicrosoftTokenValidator microsoftTokens, ILogger<AuthController> logger)
{
_cfg = cfg;
_users = users;
@@ -34,8 +31,6 @@ public sealed class AuthController : ControllerBase
_googleTokens = googleTokens;
_microsoftTokens = microsoftTokens;
_logger = logger;
_twoFactorPending = twoFactorPending;
_db = db;
}
[HttpGet("config")]
@@ -46,7 +41,6 @@ public sealed class AuthController : ControllerBase
var googleEnabled = !string.IsNullOrWhiteSpace((_cfg["Auth:GoogleClientId"] ?? string.Empty).Trim());
var microsoftEnabled = !string.IsNullOrWhiteSpace((_cfg["Auth:MicrosoftClientId"] ?? string.Empty).Trim());
var allowRegistration = _cfg.GetValue("Auth:AllowRegistration", false);
var requireEmailVerification = _cfg.GetValue("Auth:RequireEmailVerification", false);
return Ok(new
{
@@ -55,14 +49,12 @@ public sealed class AuthController : ControllerBase
microsoftEnabled,
localEnabled = true,
allowRegistration,
requireEmailVerification,
});
}
public sealed record LoginRequest(string Email, string Password, bool RememberMe = true);
public sealed record RegisterRequest(string Email, string Password, bool RememberMe = true);
public sealed record AuthSessionResult(bool Authenticated, string Provider);
public sealed record TwoFactorRequiredResult(bool RequiresTwoFactor, string PendingToken);
public sealed record GoogleLinkDto(bool Linked, string? Email, DateTimeOffset? LinkedAt);
public sealed record MicrosoftLinkDto(bool Linked, string? Email, DateTimeOffset? LinkedAt);
public sealed record MeResult(
@@ -91,7 +83,7 @@ public sealed class AuthController : ControllerBase
[HttpPost("login")]
[AllowAnonymous]
[EnableRateLimiting("auth-login")]
public async Task<IActionResult> Login([FromBody] LoginRequest request, CancellationToken cancellationToken)
public async Task<ActionResult<AuthSessionResult>> Login([FromBody] LoginRequest request, CancellationToken cancellationToken)
{
var email = (request.Email ?? string.Empty).Trim();
var password = request.Password ?? string.Empty;
@@ -102,34 +94,17 @@ public sealed class AuthController : ControllerBase
var user = await _users.FindByEmailAsync(email) ?? await _users.FindByNameAsync(email);
if (user is null) return Unauthorized();
// Same generic 401 whether the account doesn't exist, is locked out, or the password is
// wrong -- don't let a client distinguish "locked" from "wrong password" (enumeration).
if (await _users.IsLockedOutAsync(user)) return Unauthorized();
var ok = await _users.CheckPasswordAsync(user, password);
if (!ok)
{
await _users.AccessFailedAsync(user);
return Unauthorized();
}
if (!ok) return Unauthorized();
await _users.ResetAccessFailedCountAsync(user);
// Same enumeration-avoidance discipline as the password-check branch above: this only
// runs once the password is already confirmed correct, so it can never be used to probe
// whether an email is registered.
if (_cfg.GetValue("Auth:RequireEmailVerification", false) && !user.EmailConfirmed)
{
return StatusCode(StatusCodes.Status403Forbidden, new { error = "email_not_verified" });
}
return await CompleteSignInAsync(user, request.RememberMe, "local", cancellationToken);
await SignInWithAppSessionAsync(user, request.RememberMe, cancellationToken);
return Ok(new AuthSessionResult(true, "local"));
}
[HttpPost("register")]
[AllowAnonymous]
[EnableRateLimiting("auth-login")]
public async Task<IActionResult> Register([FromBody] RegisterRequest request, CancellationToken cancellationToken)
public async Task<ActionResult<AuthSessionResult>> Register([FromBody] RegisterRequest request, CancellationToken cancellationToken)
{
var allow = _cfg.GetValue("Auth:AllowRegistration", false);
if (!allow) return StatusCode(403, "Registration is disabled.");
@@ -143,35 +118,21 @@ public sealed class AuthController : ControllerBase
var existing = await _users.FindByEmailAsync(email);
if (existing is not null) return BadRequest("User already exists.");
var requireEmailVerification = _cfg.GetValue("Auth:RequireEmailVerification", false);
var user = new ApplicationUser { UserName = email, Email = email, EmailConfirmed = !requireEmailVerification };
var user = new ApplicationUser { UserName = email, Email = email, EmailConfirmed = true };
var res = await _users.CreateAsync(user, password);
if (!res.Succeeded)
{
return BadRequest(string.Join("; ", res.Errors.Select(e => e.Description)));
}
if (requireEmailVerification)
{
try
{
await SendVerificationEmailAsync(user, cancellationToken);
}
catch (Exception ex)
{
// ponytail: don't fail registration over a flaky email send -- the account is
// created either way, the user can request a fresh link via resend-verification-email.
_logger.LogError(ex, "Failed to send verification email to {Email}", user.Email);
}
}
return await CompleteSignInAsync(user, request.RememberMe, "local", cancellationToken);
await SignInWithAppSessionAsync(user, request.RememberMe, cancellationToken);
return Ok(new AuthSessionResult(true, "local"));
}
[HttpPost("google/exchange")]
[AllowAnonymous]
[EnableRateLimiting("auth-login")]
public async Task<IActionResult> ExchangeGoogleToken([FromBody] GoogleTokenRequest request, CancellationToken cancellationToken)
public async Task<ActionResult<AuthSessionResult>> ExchangeGoogleToken([FromBody] GoogleTokenRequest request, CancellationToken cancellationToken)
{
var token = (request.Token ?? string.Empty).Trim();
if (token.Length == 0) return BadRequest("Google token is required.");
@@ -232,13 +193,14 @@ public sealed class AuthController : ControllerBase
await _users.UpdateAsync(user);
}
return await CompleteSignInAsync(user, request.RememberMe, "google", cancellationToken);
await SignInWithAppSessionAsync(user, request.RememberMe, cancellationToken);
return Ok(new AuthSessionResult(true, "google"));
}
[HttpPost("microsoft/exchange")]
[AllowAnonymous]
[EnableRateLimiting("auth-login")]
public async Task<IActionResult> ExchangeMicrosoftToken([FromBody] MicrosoftTokenRequest request, CancellationToken cancellationToken)
public async Task<ActionResult<AuthSessionResult>> ExchangeMicrosoftToken([FromBody] MicrosoftTokenRequest request, CancellationToken cancellationToken)
{
var token = (request.Token ?? string.Empty).Trim();
if (token.Length == 0) return BadRequest("Microsoft token is required.");
@@ -299,7 +261,8 @@ public sealed class AuthController : ControllerBase
await _users.UpdateAsync(user);
}
return await CompleteSignInAsync(user, request.RememberMe, "microsoft", cancellationToken);
await SignInWithAppSessionAsync(user, request.RememberMe, cancellationToken);
return Ok(new AuthSessionResult(true, "microsoft"));
}
[HttpPost("logout")]
@@ -687,112 +650,17 @@ public sealed class AuthController : ControllerBase
return NoContent();
}
public sealed record VerifyEmailRequest(string UserId, string Token);
[HttpPost("verify-email")]
[AllowAnonymous]
[EnableRateLimiting("auth-email")]
public async Task<IActionResult> VerifyEmail([FromBody] VerifyEmailRequest request)
{
var userId = (request.UserId ?? string.Empty).Trim();
var token = request.Token ?? string.Empty;
if (userId.Length == 0) return BadRequest("UserId is required.");
if (token.Length == 0) return BadRequest("Token is required.");
var user = await _users.FindByIdAsync(userId);
if (user is null) return BadRequest("Invalid or expired link.");
var res = await _users.ConfirmEmailAsync(user, token);
if (!res.Succeeded)
{
return BadRequest("Invalid or expired link.");
}
return NoContent();
}
public sealed record ResendVerificationEmailRequest(string Email);
[HttpPost("resend-verification-email")]
[AllowAnonymous]
[EnableRateLimiting("auth-email")]
public async Task<IActionResult> ResendVerificationEmail([FromBody] ResendVerificationEmailRequest request, CancellationToken cancellationToken)
{
var email = (request.Email ?? string.Empty).Trim();
if (email.Length == 0) return NoContent();
// Mirrors request-password-reset's enumeration-avoidance: always NoContent, only actually
// send when there's a matching local account that still needs verifying.
var user = await _users.FindByEmailAsync(email);
if (user is null || user.EmailConfirmed || string.IsNullOrWhiteSpace(user.Email) || !await _users.HasPasswordAsync(user))
{
return NoContent();
}
try
{
await SendVerificationEmailAsync(user, cancellationToken);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send verification email to {Email}", user.Email);
return EmailDeliveryUnavailable("Verification email could not be sent right now. Please try again later.");
}
return NoContent();
}
private async Task SendVerificationEmailAsync(ApplicationUser user, CancellationToken cancellationToken)
{
var token = await _users.GenerateEmailConfirmationTokenAsync(user);
var baseUrl = (_cfg["App:PublicBaseUrl"] ?? string.Empty).Trim().TrimEnd('/');
if (string.IsNullOrWhiteSpace(baseUrl))
{
baseUrl = $"{Request.Scheme}://{Request.Host}";
}
var link = $"{baseUrl}/verify-email?userId={Uri.EscapeDataString(user.Id)}&token={Uri.EscapeDataString(token)}";
await _email.SendAsync(
user.Email!,
"Verify your email",
$"Welcome to Jobbjakt! Please verify your email address to finish setting up your account.\n\nVerification link:\n{link}\n\nIf you did not create this account, you can ignore this email.",
cancellationToken
);
}
private IActionResult EmailDeliveryUnavailable(string detail)
{
return Problem(statusCode: StatusCodes.Status503ServiceUnavailable, title: "Email delivery unavailable", detail: detail);
}
// Shared by local/Google/Microsoft sign-in. If the account has TOTP 2FA enabled, this does
// NOT issue the real session -- it hands back a short-lived opaque pending token that only
// POST /api/auth/2fa/challenge can redeem, after the caller proves they hold the TOTP device
// (or a recovery code). This is the gate that makes 2FA actually mandatory rather than
// decorative: skipping straight to AppSessionIssuer here would defeat the whole feature.
private async Task<IActionResult> CompleteSignInAsync(ApplicationUser user, bool rememberMe, string provider, CancellationToken cancellationToken)
private async Task SignInWithAppSessionAsync(ApplicationUser user, bool rememberMe, CancellationToken cancellationToken)
{
// "Trust this device" cookie check happens BEFORE the 2FA gate: if it matches a
// non-expired row for this exact user, skip straight to a real session, same as if 2FA
// weren't required at all. Falls through to the normal gate for any other outcome
// (no cookie, wrong user, expired, revoked) -- never errors, just doesn't skip.
if (user.TwoFactorEnabled && await TrustedDeviceService.IsDeviceTrustedAsync(_db, Request, user.Id, cancellationToken))
{
await AppSessionIssuer.IssueAsync(Request, Response, _tokens, _db, _cfg, user, rememberMe, cancellationToken);
return Ok(new AuthSessionResult(true, provider));
}
if (user.TwoFactorEnabled)
{
var pendingToken = _twoFactorPending.IssuePendingToken(user.Id, rememberMe);
return Ok(new TwoFactorRequiredResult(true, pendingToken));
}
await AppSessionIssuer.IssueAsync(Request, Response, _tokens, _db, _cfg, user, rememberMe, cancellationToken);
return Ok(new AuthSessionResult(true, provider));
var token = await _tokens.CreateAccessTokenAsync(user, cancellationToken);
var secure = Request.IsHttps || string.Equals(Request.Headers["X-Forwarded-Proto"], "https", StringComparison.OrdinalIgnoreCase);
Response.Cookies.Append(AuthSessionOptions.SessionCookieName, token, AuthSessionOptions.BuildSessionCookie(rememberMe, secure));
EnsureCsrfCookie(rememberMe, secure);
}
private void EnsureCsrfCookie(bool persistent, bool? secureOverride = null)
+2 -1
View File
@@ -7,13 +7,14 @@ using JobTrackerApi.Services.EmailProviders;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using static JobTrackerApi.Services.GmailParsing;
namespace JobTrackerApi.Controllers;
[ApiController]
[Route("api/gmail")]
[Authorize]
public sealed partial class GmailController : ControllerBase
public sealed class GmailController : ControllerBase
{
private readonly IGmailOAuthService _gmail;
private readonly IGmailJobMatchingService _matching;
+70 -73
View File
@@ -2,78 +2,75 @@ using JobTrackerApi.Models;
namespace JobTrackerApi.Controllers;
// DTOs for GmailController, split out for readability (Wave 2 safe refactor -- no behaviour
// change; these were previously nested inline in the controller file).
public partial class GmailController
{
public sealed record GmailImportResultDto(int Imported, int Skipped, string? ThreadId);
public sealed record GmailImportMessageResultDto(int Imported, int Skipped, string MessageId, string? ThreadId, Correspondence? Message);
public sealed record ImportGmailMessageRequest(int JobApplicationId, string MessageId);
public sealed record ImportGmailThreadRequest(int JobApplicationId, string ThreadId, string[] MessageIds);
public sealed record RefreshLinkedThreadsRequest(int JobApplicationId);
public sealed record GmailThreadRefreshThreadDto(string ThreadId, int Imported, int Skipped, int TotalMessages, string Status, DateTimeOffset? LatestMessageDate);
public sealed record GmailThreadRefreshResultDto(int JobApplicationId, int ThreadsChecked, int Imported, int Skipped, bool HasLinkedThreads, DateTimeOffset RefreshedAt, IReadOnlyList<GmailThreadRefreshThreadDto> Threads);
public sealed record GmailJobMatchReasonDto(string Label, string Value, int Points);
public sealed record GmailJobMatchedMessageDto(
string Id,
string ThreadId,
string Subject,
string From,
string To,
DateTimeOffset? Date,
string Snippet,
int Score,
string Confidence,
bool AlreadyImported,
IReadOnlyList<string> MatchedQueries,
IReadOnlyList<GmailJobMatchReasonDto> MatchReasons);
public sealed record GmailJobMatchedThreadDto(
string ThreadId,
string Subject,
int Score,
string Confidence,
bool HasImportedMessages,
int ImportedMessageCount,
int MessageCount,
DateTimeOffset? LatestDate,
IReadOnlyList<string> MatchedQueries,
IReadOnlyList<GmailJobMatchReasonDto> MatchReasons,
IReadOnlyList<GmailJobMatchedMessageDto> Messages);
public sealed record GmailJobMatchesResponseDto(
int JobApplicationId,
string JobTitle,
string CompanyName,
string? RecruiterName,
string? RecruiterEmail,
IReadOnlyList<string> Queries,
int CandidateMessageCount,
int CandidateThreadCount,
IReadOnlyList<GmailJobMatchedThreadDto> Threads);
// DTOs for GmailController, split out for readability (no behaviour change; these were
// previously nested inside the controller class).
public sealed record GmailImportResultDto(int Imported, int Skipped, string? ThreadId);
public sealed record GmailImportMessageResultDto(int Imported, int Skipped, string MessageId, string? ThreadId, Correspondence? Message);
public sealed record ImportGmailMessageRequest(int JobApplicationId, string MessageId);
public sealed record ImportGmailThreadRequest(int JobApplicationId, string ThreadId, string[] MessageIds);
public sealed record RefreshLinkedThreadsRequest(int JobApplicationId);
public sealed record GmailThreadRefreshThreadDto(string ThreadId, int Imported, int Skipped, int TotalMessages, string Status, DateTimeOffset? LatestMessageDate);
public sealed record GmailThreadRefreshResultDto(int JobApplicationId, int ThreadsChecked, int Imported, int Skipped, bool HasLinkedThreads, DateTimeOffset RefreshedAt, IReadOnlyList<GmailThreadRefreshThreadDto> Threads);
public sealed record GmailJobMatchReasonDto(string Label, string Value, int Points);
public sealed record GmailJobMatchedMessageDto(
string Id,
string ThreadId,
string Subject,
string From,
string To,
DateTimeOffset? Date,
string Snippet,
int Score,
string Confidence,
bool AlreadyImported,
IReadOnlyList<string> MatchedQueries,
IReadOnlyList<GmailJobMatchReasonDto> MatchReasons);
public sealed record GmailJobMatchedThreadDto(
string ThreadId,
string Subject,
int Score,
string Confidence,
bool HasImportedMessages,
int ImportedMessageCount,
int MessageCount,
DateTimeOffset? LatestDate,
IReadOnlyList<string> MatchedQueries,
IReadOnlyList<GmailJobMatchReasonDto> MatchReasons,
IReadOnlyList<GmailJobMatchedMessageDto> Messages);
public sealed record GmailJobMatchesResponseDto(
int JobApplicationId,
string JobTitle,
string CompanyName,
string? RecruiterName,
string? RecruiterEmail,
IReadOnlyList<string> Queries,
int CandidateMessageCount,
int CandidateThreadCount,
IReadOnlyList<GmailJobMatchedThreadDto> Threads);
public sealed record GmailReviewJobCandidateDto(int JobApplicationId, string JobTitle, string CompanyName, int Score, string Confidence, IReadOnlyList<GmailJobMatchReasonDto> Reasons);
public sealed record GmailReviewThreadDto(string ThreadId, string Subject, DateTimeOffset? LatestDate, int MessageCount, string Routing, bool HasImportedMessages, string? DecisionNote, IReadOnlyList<string> MatchedQueries, IReadOnlyList<GmailReviewJobCandidateDto> JobCandidates, IReadOnlyList<GmailJobMatchedMessageDto> Messages);
public sealed record GmailReviewQueueResponseDto(IReadOnlyList<string> Queries, int CandidateThreadCount, int AutoLinkThreadCount, int ReviewThreadCount, int UnmatchedThreadCount, IReadOnlyList<GmailReviewThreadDto> Threads);
public sealed record SaveGmailReviewDecisionRequest(string ThreadId, string Decision, int? JobApplicationId, string? Note);
public sealed record GmailManualSyncRequest(int? LookbackDays, int? MaxResultsPerQuery, bool? AutoImportHighConfidence, bool? IncludeSpamTrash);
public sealed record GmailManualSyncResultDto(int QueriesRun, int CandidateThreadCount, int AutoLinkedThreadCount, int ReviewThreadCount, int UnmatchedThreadCount, int ImportedMessages, int ImportedThreads, int SkippedMessages, int LookbackDays, bool IncludeSpamTrash, DateTimeOffset SyncedAt);
public sealed record GmailSuggestedJobCandidateDto(string ThreadId, string Subject, DateTimeOffset? LatestDate, string? CompanyName, string? RecruiterName, string? RecruiterEmail, string? SuggestedJobTitle, string Routing, IReadOnlyList<string> MatchedQueries, string Preview);
public sealed record GmailSuggestedJobsResponseDto(int Count, IReadOnlyList<GmailSuggestedJobCandidateDto> Items);
public sealed record CreateSuggestedGmailJobRequest(string ThreadId, string CompanyName, string JobTitle, string? RecruiterName, string? RecruiterEmail, string? Notes, string? Status);
public sealed record CreatedSuggestedGmailJobDto(int JobApplicationId, int CompanyId, string ThreadId, int Imported, int Skipped);
public sealed record RelinkGmailThreadRequest(int JobApplicationId, string ThreadId, bool RemoveFromOtherJobs, string? Note);
public sealed record GmailRelinkResultDto(string ThreadId, int JobApplicationId, int Imported, int Skipped, int UnlinkedMessages);
public sealed record UnlinkGmailThreadRequest(int JobApplicationId, string ThreadId, string? Note, string? NextDecision);
public sealed record GmailUnlinkResultDto(string ThreadId, int JobApplicationId, int RemovedMessages, string Decision);
public sealed record GmailReviewJobCandidateDto(int JobApplicationId, string JobTitle, string CompanyName, int Score, string Confidence, IReadOnlyList<GmailJobMatchReasonDto> Reasons);
public sealed record GmailReviewThreadDto(string ThreadId, string Subject, DateTimeOffset? LatestDate, int MessageCount, string Routing, bool HasImportedMessages, string? DecisionNote, IReadOnlyList<string> MatchedQueries, IReadOnlyList<GmailReviewJobCandidateDto> JobCandidates, IReadOnlyList<GmailJobMatchedMessageDto> Messages);
public sealed record GmailReviewQueueResponseDto(IReadOnlyList<string> Queries, int CandidateThreadCount, int AutoLinkThreadCount, int ReviewThreadCount, int UnmatchedThreadCount, IReadOnlyList<GmailReviewThreadDto> Threads);
public sealed record SaveGmailReviewDecisionRequest(string ThreadId, string Decision, int? JobApplicationId, string? Note);
public sealed record GmailManualSyncRequest(int? LookbackDays, int? MaxResultsPerQuery, bool? AutoImportHighConfidence, bool? IncludeSpamTrash);
public sealed record GmailManualSyncResultDto(int QueriesRun, int CandidateThreadCount, int AutoLinkedThreadCount, int ReviewThreadCount, int UnmatchedThreadCount, int ImportedMessages, int ImportedThreads, int SkippedMessages, int LookbackDays, bool IncludeSpamTrash, DateTimeOffset SyncedAt);
public sealed record GmailSuggestedJobCandidateDto(string ThreadId, string Subject, DateTimeOffset? LatestDate, string? CompanyName, string? RecruiterName, string? RecruiterEmail, string? SuggestedJobTitle, string Routing, IReadOnlyList<string> MatchedQueries, string Preview);
public sealed record GmailSuggestedJobsResponseDto(int Count, IReadOnlyList<GmailSuggestedJobCandidateDto> Items);
public sealed record CreateSuggestedGmailJobRequest(string ThreadId, string CompanyName, string JobTitle, string? RecruiterName, string? RecruiterEmail, string? Notes, string? Status);
public sealed record CreatedSuggestedGmailJobDto(int JobApplicationId, int CompanyId, string ThreadId, int Imported, int Skipped);
public sealed record RelinkGmailThreadRequest(int JobApplicationId, string ThreadId, bool RemoveFromOtherJobs, string? Note);
public sealed record GmailRelinkResultDto(string ThreadId, int JobApplicationId, int Imported, int Skipped, int UnlinkedMessages);
public sealed record UnlinkGmailThreadRequest(int JobApplicationId, string ThreadId, string? Note, string? NextDecision);
public sealed record GmailUnlinkResultDto(string ThreadId, int JobApplicationId, int RemovedMessages, string Decision);
public sealed record GmailConnectionStatusDto(
bool Connected,
string? GmailAddress,
DateTimeOffset? ConnectedAt,
DateTimeOffset? LastSyncedAt,
DateTimeOffset? LastSyncAttemptedAt,
DateTimeOffset? LastSyncSucceededAt,
string? LastSyncMode,
string? LastSyncSource,
string? LastSyncStatus,
string? LastSyncError);
}
public sealed record GmailConnectionStatusDto(
bool Connected,
string? GmailAddress,
DateTimeOffset? ConnectedAt,
DateTimeOffset? LastSyncedAt,
DateTimeOffset? LastSyncAttemptedAt,
DateTimeOffset? LastSyncSucceededAt,
string? LastSyncMode,
string? LastSyncSource,
string? LastSyncStatus,
string? LastSyncError);
@@ -0,0 +1,228 @@
using JobTrackerApi.Models;
namespace JobTrackerApi.Controllers
{
public sealed record TailoredCvPreviewDto(string TemplateId, string Html, string SuggestedFileName);
public sealed record TailoredCvRenderRequest(
string? TemplateId,
string? Headline,
List<string>? Summary,
List<string>? SelectedSkills,
List<TailoredCvExperienceItem>? Experience,
List<TailoredCvEducationItem>? Education,
List<TailoredCvCustomSection>? CustomSections,
TailoredCvRenderOptions? RenderOptions,
string? PhotoDataUrl,
bool? UseProfileAvatar);
public sealed record AttachmentContextResult(string Context, List<string> Signals, List<string> UsedFiles);
public sealed record CorrespondenceContextResult(string Context, List<string> Signals, List<string> Participants, List<string> ThreadIds);
public sealed record WorkflowSignalDto(
string ActionKey,
string Reason,
string WorkspaceTab,
string? FollowMode,
bool NeedsAttention,
bool HasPackageGap,
bool NeedsInterviewPrep,
bool NeedsFollowUpAction,
bool HasTailoredCv,
bool HasSavedApplicationAnswerDraft,
bool HasInterviewPrepNotes
);
public sealed record PagedResult<T>(List<T> Items, int Total, int Page, int PageSize);
public sealed record JobApplicationDto(
int Id,
int CompanyId,
Company Company,
string JobTitle,
string Status,
DateTime DateApplied,
bool ResponseReceived,
DateTime? ResponseDate,
string? Notes,
string? CoverLetterText,
string? JobUrl,
string? Description,
string? TranslatedDescription,
string? DescriptionLanguage,
string? Tags,
DateTime? Deadline,
string? Location,
string? Salary,
decimal? SalaryMin,
decimal? SalaryMax,
string? SalaryCurrency,
string? SalaryPeriod,
string? NextAction,
DateTime? FollowUpAt,
DateTime? FeedbackRequestedAt,
bool HasResume,
bool HasCoverLetter,
bool HasPortfolio,
bool HasOtherAttachment,
bool IsDeleted,
DateTime? DeletedAt,
int DaysSince,
bool NeedsFollowUp,
string? FollowUpReason,
string? TailoredCvText,
WorkflowSignalDto WorkflowSignal,
string? ShortSummary,
string? FullSummary
);
public sealed record CreateJobApplicationRequest(
string JobTitle,
int CompanyId,
string? Status,
string? Location,
string? Salary,
decimal? SalaryMin,
decimal? SalaryMax,
string? SalaryCurrency,
string? SalaryPeriod,
string? NextAction,
DateTime? FollowUpAt,
string? Notes,
string? Description,
string? TranslatedDescription,
string? DescriptionLanguage,
string? Tags,
DateTime? Deadline,
string? CoverLetterText,
string? JobUrl,
DateTime? DateApplied,
DateTime? FeedbackRequestedAt
);
public sealed record UpdateJobApplicationRequest(
string JobTitle,
int CompanyId,
string Status,
bool ResponseReceived,
DateTime? ResponseDate,
string? Location,
string? Salary,
decimal? SalaryMin,
decimal? SalaryMax,
string? SalaryCurrency,
string? SalaryPeriod,
string? NextAction,
DateTime? FollowUpAt,
string? Notes,
string? Description,
string? TranslatedDescription,
string? DescriptionLanguage,
string? Tags,
DateTime? Deadline,
string? CoverLetterText,
string? JobUrl,
DateTime? DateApplied,
DateTime? FeedbackRequestedAt,
DateTime? StatusChangedAt
);
public sealed record UpdateStatusRequest(string Status);
public sealed record PipelineStageDto(string Key, int Order, string Category);
public sealed record StatusSuggestionDto(
bool HasSuggestion,
string? SuggestedStatus,
string? CurrentStatus,
string? Signal,
string? Confidence,
DateTime? MessageDate,
string? MessageSubject);
public sealed record FollowUpRequest(DateTime? FollowUpAt);
public sealed record JobEventDto(int Id, string Type, string? OldValue, string? NewValue, string? Note, DateTime At);
public sealed record TimelineItemDto(string Kind, DateTime At, object Data);
public sealed record AnalyticsPoint(string Month, int Applied, int Responses);
public sealed record TagPoint(string Tag, int Count);
public sealed record TagTrendSeries(string Tag, List<int> Counts);
public sealed record TagTrendPoint(string Month, List<int> Counts);
public sealed record DuplicateCandidateDto(int Id, string JobTitle, string Company, string? JobUrl, string Status, DateTime DateApplied, string Reason);
public sealed record DuplicateCheckResult(bool HasDuplicates, List<DuplicateCandidateDto> Matches);
public sealed record FollowUpDraftDto(string Subject, string Body, string Reason, DateTime SuggestedSendOn, string ContextSummary, List<string> ContextSignals, string? ThreadSubject, string? LastCorrespondenceFrom, DateTime? LastCorrespondenceAt);
public sealed record FocusPlanDto(
List<string> ImmediatePriorities,
List<string> CvBulletIdeas,
List<string> ProofPointsToLeadWith,
List<string> CoverLetterAngles,
List<string> FollowUpApproach,
string StrategicSummary);
public sealed record SendFollowUpRequest(string? ToEmail, string Subject, string Body, DateTime? NextFollowUpAt);
public sealed record TagTrendResponse(List<string> Months, List<TagTrendSeries> Series);
public sealed record CandidateFitChannelGuidanceDto(List<string> Cv, List<string> CoverLetter, List<string> Interview, List<string> RecruiterMessage);
public sealed record CandidateFitDto(
string MatchSummary,
string FitLevel,
int MatchScore,
List<string> Strengths,
List<string> Gaps,
List<string> Mention,
List<string> Avoid,
List<string> CvImprovements,
List<string> MissingKeywords,
List<string> InterviewPrep,
string TailoredPitch,
CandidateFitChannelGuidanceDto Guidance,
string? CoverLetterDraft,
string? RecruiterMessageDraft);
public sealed record SaveTailoredCvRequest(string? TailoredCvText);
public sealed record TailoredCvDraftDto(
int? Id,
int? CanonicalProfileVersion,
string TemplateId,
string? Headline,
List<string> Summary,
List<string> SelectedSkills,
List<TailoredCvExperienceItem> Experience,
List<TailoredCvEducationItem> Education,
List<TailoredCvCustomSection> CustomSections,
TailoredCvRenderOptions RenderOptions,
string? GenerationContextHash,
DateTimeOffset? LastGeneratedAtUtc,
DateTimeOffset? LastEditedAtUtc,
string Status,
string RenderedText,
bool IsLegacyFallback);
public sealed record SaveTailoredCvDraftRequest(
string? TemplateId,
string? Headline,
List<string>? Summary,
List<string>? SelectedSkills,
List<TailoredCvExperienceItem>? Experience,
List<TailoredCvEducationItem>? Education,
List<TailoredCvCustomSection>? CustomSections,
TailoredCvRenderOptions? RenderOptions,
string? Status);
public sealed record GenerateApplicationPackageDto(string TailoredCvText, string? CoverLetterDraft, string? ApplicationAnswerDraft, string? RecruiterMessageDraft, List<string> KeyPoints, List<string> AttachmentSignals, List<string> AttachmentFilesUsed, List<string> CoverLetterVariants, List<string> RecruiterMessageVariants);
public sealed record SaveApplicationDraftsRequest(string? CoverLetterText, string? Notes, string? RecruiterMessageDraft);
public sealed record SavedPackageMaterial(string? TailoredCvText, string? CoverLetterText, string? RecruiterMessageDraft, string? Notes);
public sealed record InterviewPrepDto(string Summary, List<string> TalkingPoints, List<string> LikelyQuestions, List<string> WeakSpots);
public sealed record ReadinessDto(int Score, string Level, List<string> Completed, List<string> Missing, List<string> Reminders, WorkflowSignalDto WorkflowSignal);
public sealed record MatchScoreDto(
int Score,
string Band,
int MatchedCount,
int TotalKeywords,
List<string> MatchedKeywords,
List<string> MissingKeywords,
List<MatchSectionCoverageDto> SectionCoverage,
bool HasEnoughSignal);
public sealed record MatchSectionCoverageDto(string Section, int Matched, int Total);
}
File diff suppressed because it is too large Load Diff
@@ -113,25 +113,8 @@ public sealed class ProfileCvController : ControllerBase
public string? Tone { get; set; }
public string? Language { get; set; }
}
public sealed record ParseCvRequest(string? Text);
public sealed record CvTemplateDescriptor(string Id, string Title, string Tone, string AccentColor, string PreviewTagline, string PreviewSummary, List<string> PreviewBullets);
public sealed record ProfileCvPreviewDto(string TemplateId, string Html, string SuggestedFileName, string FullText, string RewrittenText, string? SectionName, StructuredCvProfile StructuredCv, TailoredCvDocument Document, string? TargetRole, int? JobApplicationId);
public sealed record CvRewriteFailureDto(string Code, string Message, string? Detail = null, string? LastAiError = null);
private sealed record ExtractionPipelineResult(string RawText, string NormalizedText, StructuredCvProfile StructuredCv);
private sealed record ClassifiedCvBlock(int Index, string OriginalBlock, string SectionName, string Content, CvBlockClassificationResult? Classification);
public sealed record CvExtractionRunListItem(
int Id,
string Trigger,
string Status,
string? ArtifactFileName,
DateTimeOffset StartedAtUtc,
DateTimeOffset? CompletedAtUtc,
DateTimeOffset? AppliedAtUtc,
string ParserVersion,
string NormalizerVersion,
string LlmPromptVersion,
string? ErrorMessage);
[HttpPost("upload")]
[RequestSizeLimit(MaxFileSizeBytes)]
@@ -254,6 +237,7 @@ public sealed class ProfileCvController : ControllerBase
if (user is null) return Unauthorized();
var artifact = await _db.CvUploadArtifacts
.AsNoTracking()
.OrderByDescending(x => x.UploadedAtUtc)
.FirstOrDefaultAsync(x => x.OwnerUserId == user.Id, HttpContext.RequestAborted);
@@ -941,7 +925,7 @@ public sealed class ProfileCvController : ControllerBase
}
case "reprocess":
{
var artifact = await _db.CvUploadArtifacts.FirstOrDefaultAsync(x => x.Id == run.ArtifactId && x.OwnerUserId == user.Id, cancellationToken);
var artifact = await _db.CvUploadArtifacts.AsNoTracking().FirstOrDefaultAsync(x => x.Id == run.ArtifactId && x.OwnerUserId == user.Id, cancellationToken);
if (artifact is null) throw new InvalidOperationException("Upload a CV before reprocessing it.");
if (string.IsNullOrWhiteSpace(artifact.StoragePath) || !System.IO.File.Exists(artifact.StoragePath))
{
@@ -0,0 +1,20 @@
using JobTrackerApi.Models;
namespace JobTrackerApi.Controllers;
public sealed record ParseCvRequest(string? Text);
public sealed record CvTemplateDescriptor(string Id, string Title, string Tone, string AccentColor, string PreviewTagline, string PreviewSummary, List<string> PreviewBullets);
public sealed record ProfileCvPreviewDto(string TemplateId, string Html, string SuggestedFileName, string FullText, string RewrittenText, string? SectionName, StructuredCvProfile StructuredCv, TailoredCvDocument Document, string? TargetRole, int? JobApplicationId);
public sealed record CvRewriteFailureDto(string Code, string Message, string? Detail = null, string? LastAiError = null);
public sealed record CvExtractionRunListItem(
int Id,
string Trigger,
string Status,
string? ArtifactFileName,
DateTimeOffset StartedAtUtc,
DateTimeOffset? CompletedAtUtc,
DateTimeOffset? AppliedAtUtc,
string ParserVersion,
string NormalizerVersion,
string LlmPromptVersion,
string? ErrorMessage);
@@ -1,104 +0,0 @@
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace JobTrackerApi.Controllers;
// List/revoke the server-tracked UserSession rows behind the JWTs AppSessionIssuer hands out.
// Not 2FA-specific (any local-auth user has sessions, 2FA or not), hence its own small controller
// rather than folding into TwoFactorController.
[ApiController]
[Route("api/auth/sessions")]
[Authorize(AuthenticationSchemes = "local")]
public sealed class SessionsController : ControllerBase
{
private readonly UserManager<ApplicationUser> _users;
private readonly JobTrackerContext _db;
public SessionsController(UserManager<ApplicationUser> users, JobTrackerContext db)
{
_users = users;
_db = db;
}
public sealed record SessionDto(string Id, string? DeviceLabel, DateTimeOffset CreatedAtUtc, DateTimeOffset LastSeenAtUtc, DateTimeOffset ExpiresAtUtc, bool IsCurrentSession);
private string? CurrentSid => User.FindFirst("sid")?.Value;
[HttpGet]
public async Task<IActionResult> List(CancellationToken cancellationToken)
{
var user = await _users.GetUserAsync(User);
if (user is null) return Unauthorized();
var now = DateTimeOffset.UtcNow;
var currentSid = CurrentSid;
// IgnoreQueryFilters + an explicit UserId filter, same convention as
// TrustedDeviceService/TwoFactorController's device-list queries.
// Equality-only in the DB query, then filter/sort DateTimeOffset client-side: SQLite's EF
// Core provider cannot translate ">" or ORDER BY over DateTimeOffset to SQL ("SQLite does
// not support expressions of type 'DateTimeOffset' in ORDER BY clauses"), so ExpiresAtUtc
// comparison and the LastSeenAtUtc sort have to happen after materializing the (small,
// per-user) row set.
var candidates = await _db.UserSessions.IgnoreQueryFilters()
.Where(x => x.UserId == user.Id && x.RevokedAtUtc == null)
.ToListAsync(cancellationToken);
var sessions = candidates
.Where(x => x.ExpiresAtUtc > now)
.OrderByDescending(x => x.LastSeenAtUtc)
.Select(x => new SessionDto(x.Id, x.DeviceLabel, x.CreatedAtUtc, x.LastSeenAtUtc, x.ExpiresAtUtc, x.Id == currentSid))
.ToList();
return Ok(sessions);
}
[HttpDelete("{id}")]
public async Task<IActionResult> Revoke(string id, CancellationToken cancellationToken)
{
var user = await _users.GetUserAsync(User);
if (user is null) return Unauthorized();
var session = await _db.UserSessions.IgnoreQueryFilters().FirstOrDefaultAsync(x => x.Id == id && x.UserId == user.Id, cancellationToken);
if (session is null) return NotFound();
session.RevokedAtUtc = DateTimeOffset.UtcNow;
await _db.SaveChangesAsync(cancellationToken);
if (string.Equals(id, CurrentSid, StringComparison.Ordinal))
{
var secure = Request.IsHttps || string.Equals(Request.Headers["X-Forwarded-Proto"], "https", StringComparison.OrdinalIgnoreCase);
Response.Cookies.Delete(AuthSessionOptions.SessionCookieName, AuthSessionOptions.BuildExpiredCookie(secure));
}
return NoContent();
}
[HttpPost("revoke-others")]
public async Task<IActionResult> RevokeOthers(CancellationToken cancellationToken)
{
var user = await _users.GetUserAsync(User);
if (user is null) return Unauthorized();
var currentSid = CurrentSid;
var now = DateTimeOffset.UtcNow;
var others = await _db.UserSessions.IgnoreQueryFilters()
.Where(x => x.UserId == user.Id && x.RevokedAtUtc == null && x.Id != currentSid)
.ToListAsync(cancellationToken);
foreach (var session in others)
{
session.RevokedAtUtc = now;
}
if (others.Count > 0)
{
await _db.SaveChangesAsync(cancellationToken);
}
return NoContent();
}
}
@@ -1,341 +0,0 @@
using System.Security.Cryptography;
using System.Text;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using OtpNet;
using QRCoder;
namespace JobTrackerApi.Controllers;
// TOTP 2FA (RFC 6238) + recovery codes. Split out from AuthController (already 700+ lines)
// rather than growing it further; shares the session cookie logic via AppSessionIssuer and the
// pending-token handoff via ITwoFactorPendingTokenService.
[ApiController]
[Route("api/auth/2fa")]
public sealed class TwoFactorController : ControllerBase
{
private const int RecoveryCodeCount = 10;
private readonly UserManager<ApplicationUser> _users;
private readonly ITokenService _tokens;
private readonly JobTrackerContext _db;
private readonly ITwoFactorPendingTokenService _pending;
private readonly IDataProtector _protector;
private readonly IConfiguration _cfg;
public TwoFactorController(UserManager<ApplicationUser> users, ITokenService tokens, JobTrackerContext db, ITwoFactorPendingTokenService pending, IDataProtectionProvider protectionProvider, IConfiguration cfg)
{
_users = users;
_tokens = tokens;
_db = db;
_pending = pending;
_protector = protectionProvider.CreateProtector("totp-secret-v1");
_cfg = cfg;
}
public sealed record PasswordConfirmRequest(string CurrentPassword);
public sealed record SetupResult(string ManualEntryKey, string QrCodeDataUrl);
public sealed record VerifySetupRequest(string Code);
public sealed record VerifySetupResult(bool Enabled, IReadOnlyList<string> RecoveryCodes);
public sealed record StatusResult(bool Enabled, DateTimeOffset? EnabledAtUtc);
public sealed record RecoveryCodesResult(IReadOnlyList<string> RecoveryCodes);
public sealed record ChallengeRequest(string PendingToken, string Code, bool TrustDevice = false);
public sealed record TrustedDeviceDto(int Id, string? DeviceLabel, DateTimeOffset CreatedAtUtc, DateTimeOffset LastSeenAtUtc, DateTimeOffset ExpiresAtUtc, bool IsCurrentDevice);
[HttpPost("setup")]
[Authorize(AuthenticationSchemes = "local")]
[EnableRateLimiting("auth-login")]
public async Task<IActionResult> Setup([FromBody] PasswordConfirmRequest request, CancellationToken cancellationToken)
{
var user = await _users.GetUserAsync(User);
if (user is null) return Unauthorized();
if (!await _users.CheckPasswordAsync(user, request.CurrentPassword ?? string.Empty))
{
return BadRequest("Current password is incorrect.");
}
var secretBytes = KeyGeneration.GenerateRandomKey(20);
var base32Secret = Base32Encoding.ToString(secretBytes);
user.TotpPendingSecretEncrypted = _protector.Protect(base32Secret);
var result = await _users.UpdateAsync(user);
if (!result.Succeeded)
{
return BadRequest(string.Join("; ", result.Errors.Select(e => e.Description)));
}
var issuer = "JobTracker";
var label = Uri.EscapeDataString($"{issuer}:{user.Email}");
var otpauthUri = $"otpauth://totp/{label}?secret={base32Secret}&issuer={Uri.EscapeDataString(issuer)}&digits=6&period=30";
using var qrGenerator = new QRCodeGenerator();
using var qrData = qrGenerator.CreateQrCode(otpauthUri, QRCodeGenerator.ECCLevel.Q);
var pngQr = new PngByteQRCode(qrData);
var qrPngBytes = pngQr.GetGraphic(10);
var qrDataUrl = $"data:image/png;base64,{Convert.ToBase64String(qrPngBytes)}";
return Ok(new SetupResult(base32Secret, qrDataUrl));
}
[HttpPost("verify-setup")]
[Authorize(AuthenticationSchemes = "local")]
[EnableRateLimiting("auth-login")]
public async Task<IActionResult> VerifySetup([FromBody] VerifySetupRequest request, CancellationToken cancellationToken)
{
var user = await _users.GetUserAsync(User);
if (user is null) return Unauthorized();
if (string.IsNullOrWhiteSpace(user.TotpPendingSecretEncrypted))
{
return BadRequest("No pending 2FA setup. Call setup first.");
}
var base32Secret = _protector.Unprotect(user.TotpPendingSecretEncrypted);
if (!VerifyCode(base32Secret, request.Code))
{
return Unauthorized();
}
user.TotpSecretEncrypted = user.TotpPendingSecretEncrypted;
user.TotpPendingSecretEncrypted = null;
user.TwoFactorEnabled = true;
user.TotpEnabledAtUtc = DateTimeOffset.UtcNow;
var result = await _users.UpdateAsync(user);
if (!result.Succeeded)
{
return BadRequest(string.Join("; ", result.Errors.Select(e => e.Description)));
}
var codes = await RegenerateRecoveryCodesAsync(user.Id, cancellationToken);
return Ok(new VerifySetupResult(true, codes));
}
[HttpPost("disable")]
[Authorize(AuthenticationSchemes = "local")]
[EnableRateLimiting("auth-login")]
public async Task<IActionResult> Disable([FromBody] PasswordConfirmRequest request, CancellationToken cancellationToken)
{
var user = await _users.GetUserAsync(User);
if (user is null) return Unauthorized();
if (!await _users.CheckPasswordAsync(user, request.CurrentPassword ?? string.Empty))
{
return BadRequest("Current password is incorrect.");
}
user.TotpSecretEncrypted = null;
user.TotpPendingSecretEncrypted = null;
user.TwoFactorEnabled = false;
user.TotpEnabledAtUtc = null;
var result = await _users.UpdateAsync(user);
if (!result.Succeeded)
{
return BadRequest(string.Join("; ", result.Errors.Select(e => e.Description)));
}
await RemoveAllRecoveryCodesAsync(user.Id, cancellationToken);
return NoContent();
}
[HttpGet("status")]
[Authorize(AuthenticationSchemes = "local")]
public async Task<IActionResult> Status()
{
var user = await _users.GetUserAsync(User);
if (user is null) return Unauthorized();
return Ok(new StatusResult(user.TwoFactorEnabled, user.TotpEnabledAtUtc));
}
[HttpPost("recovery-codes/regenerate")]
[Authorize(AuthenticationSchemes = "local")]
[EnableRateLimiting("auth-login")]
public async Task<IActionResult> RegenerateRecoveryCodes([FromBody] PasswordConfirmRequest request, CancellationToken cancellationToken)
{
var user = await _users.GetUserAsync(User);
if (user is null) return Unauthorized();
if (!user.TwoFactorEnabled)
{
return BadRequest("Two-factor authentication is not enabled.");
}
if (!await _users.CheckPasswordAsync(user, request.CurrentPassword ?? string.Empty))
{
return BadRequest("Current password is incorrect.");
}
var codes = await RegenerateRecoveryCodesAsync(user.Id, cancellationToken);
return Ok(new RecoveryCodesResult(codes));
}
[HttpPost("challenge")]
[AllowAnonymous]
[EnableRateLimiting("auth-2fa-challenge")]
public async Task<IActionResult> Challenge([FromBody] ChallengeRequest request, CancellationToken cancellationToken)
{
var pendingToken = (request.PendingToken ?? string.Empty).Trim();
var code = (request.Code ?? string.Empty).Trim();
if (pendingToken.Length == 0 || code.Length == 0) return Unauthorized();
// Peek without consuming: only burn the pending token once the code actually checks out,
// so a mistyped code doesn't force the user back through password login.
var session = _pending.Resolve(pendingToken, consume: false);
if (session is null) return Unauthorized();
var user = await _users.FindByIdAsync(session.UserId);
if (user is null || !user.TwoFactorEnabled || string.IsNullOrWhiteSpace(user.TotpSecretEncrypted))
{
return Unauthorized();
}
var base32Secret = _protector.Unprotect(user.TotpSecretEncrypted);
var verified = VerifyCode(base32Secret, code) || await TryConsumeRecoveryCodeAsync(user.Id, code, cancellationToken);
if (!verified) return Unauthorized();
_pending.Resolve(pendingToken, consume: true);
await AppSessionIssuer.IssueAsync(Request, Response, _tokens, _db, _cfg, user, session.RememberMe, cancellationToken);
if (request.TrustDevice)
{
await TrustedDeviceService.IssueAsync(_db, Request, Response, user.Id, cancellationToken);
}
return Ok(new AuthController.AuthSessionResult(true, "local"));
}
[HttpGet("trusted-devices")]
[Authorize(AuthenticationSchemes = "local")]
public async Task<IActionResult> ListTrustedDevices(CancellationToken cancellationToken)
{
var user = await _users.GetUserAsync(User);
if (user is null) return Unauthorized();
var currentHash = TrustedDeviceService.CurrentDeviceTokenHash(Request);
// SQLite/Pomelo cannot translate DateTimeOffset ORDER BY to SQL (same issue as the
// expiry check in TrustedDeviceService), so sort after materializing.
var devices = await _db.TrustedDevices
.Where(x => x.UserId == user.Id)
.Select(x => new TrustedDeviceDto(x.Id, x.DeviceLabel, x.CreatedAtUtc, x.LastSeenAtUtc, x.ExpiresAtUtc, currentHash != null && x.TokenHash == currentHash))
.ToListAsync(cancellationToken);
return Ok(devices.OrderByDescending(x => x.LastSeenAtUtc).ToList());
}
[HttpDelete("trusted-devices/{id:int}")]
[Authorize(AuthenticationSchemes = "local")]
public async Task<IActionResult> RevokeTrustedDevice(int id, CancellationToken cancellationToken)
{
var user = await _users.GetUserAsync(User);
if (user is null) return Unauthorized();
var device = await _db.TrustedDevices.FirstOrDefaultAsync(x => x.Id == id && x.UserId == user.Id, cancellationToken);
if (device is null) return NotFound();
var currentHash = TrustedDeviceService.CurrentDeviceTokenHash(Request);
var isCurrentDevice = currentHash != null && string.Equals(device.TokenHash, currentHash, StringComparison.Ordinal);
_db.TrustedDevices.Remove(device);
await _db.SaveChangesAsync(cancellationToken);
if (isCurrentDevice)
{
TrustedDeviceService.ClearCookie(Request, Response);
}
return NoContent();
}
[HttpPost("trusted-devices/revoke-all")]
[Authorize(AuthenticationSchemes = "local")]
public async Task<IActionResult> RevokeAllTrustedDevices(CancellationToken cancellationToken)
{
var user = await _users.GetUserAsync(User);
if (user is null) return Unauthorized();
var devices = await _db.TrustedDevices.Where(x => x.UserId == user.Id).ToListAsync(cancellationToken);
if (devices.Count > 0)
{
_db.TrustedDevices.RemoveRange(devices);
await _db.SaveChangesAsync(cancellationToken);
}
TrustedDeviceService.ClearCookie(Request, Response);
return NoContent();
}
private static bool VerifyCode(string base32Secret, string? code)
{
code = (code ?? string.Empty).Trim();
if (code.Length == 0) return false;
var totp = new Totp(Base32Encoding.ToBytes(base32Secret));
// +-1 step (30s) of drift, the RFC 6238 standard tolerance for clock skew between the
// authenticator app and the server.
return totp.VerifyTotp(code, out _, new VerificationWindow(1, 1));
}
private async Task<bool> TryConsumeRecoveryCodeAsync(string userId, string code, CancellationToken cancellationToken)
{
var hash = HashRecoveryCode(code);
var match = await _db.TwoFactorRecoveryCodes
.IgnoreQueryFilters()
.FirstOrDefaultAsync(x => x.UserId == userId && x.CodeHash == hash && x.UsedAtUtc == null, cancellationToken);
if (match is null) return false;
match.UsedAtUtc = DateTimeOffset.UtcNow;
await _db.SaveChangesAsync(cancellationToken);
return true;
}
private async Task<IReadOnlyList<string>> RegenerateRecoveryCodesAsync(string userId, CancellationToken cancellationToken)
{
await RemoveAllRecoveryCodesAsync(userId, cancellationToken);
var now = DateTimeOffset.UtcNow;
var plainCodes = new List<string>(RecoveryCodeCount);
var rows = new List<TwoFactorRecoveryCode>(RecoveryCodeCount);
for (var i = 0; i < RecoveryCodeCount; i++)
{
var plain = GenerateRecoveryCode();
plainCodes.Add(plain);
rows.Add(new TwoFactorRecoveryCode { UserId = userId, CodeHash = HashRecoveryCode(plain), CreatedAtUtc = now });
}
_db.TwoFactorRecoveryCodes.AddRange(rows);
await _db.SaveChangesAsync(cancellationToken);
return plainCodes;
}
private async Task RemoveAllRecoveryCodesAsync(string userId, CancellationToken cancellationToken)
{
var existing = await _db.TwoFactorRecoveryCodes.IgnoreQueryFilters().Where(x => x.UserId == userId).ToListAsync(cancellationToken);
if (existing.Count == 0) return;
_db.TwoFactorRecoveryCodes.RemoveRange(existing);
await _db.SaveChangesAsync(cancellationToken);
}
private static string GenerateRecoveryCode()
{
var hex = Convert.ToHexString(RandomNumberGenerator.GetBytes(5)).ToLowerInvariant(); // 10 hex chars, 40 bits
return $"{hex[..5]}-{hex[5..]}";
}
// ponytail: recovery codes are already random high-entropy tokens (not user-chosen
// passwords), so a plain SHA-256 hash is sufficient -- no per-code salt or PBKDF2 needed.
private static string HashRecoveryCode(string code)
{
var normalized = code.Trim().ToLowerInvariant();
return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(normalized))).ToLowerInvariant();
}
}
+5 -35
View File
@@ -183,16 +183,12 @@ builder.Services.AddIdentityCore<ApplicationUser>(options =>
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequiredLength = 8;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<JobTrackerContext>()
.AddSignInManager();
builder.Services.AddScoped<ITokenService, TokenService>();
builder.Services.AddSingleton<ITwoFactorPendingTokenService, TwoFactorPendingTokenService>();
builder.Services.AddSingleton<UniversalJobParser>();
builder.Services.AddSingleton<IHostAddressResolver, DnsHostAddressResolver>();
@@ -286,29 +282,16 @@ builder.Services.AddAuthentication(options =>
return Task.CompletedTask;
},
OnTokenValidated = async context =>
OnTokenValidated = context =>
{
var userId = LocalAuthIdentity.GetRequiredUserId(context.Principal);
if (userId is null)
if (userId is not null)
{
context.Fail("Local tokens must include a subject/nameidentifier claim.");
return;
return Task.CompletedTask;
}
// Resolve a fresh scoped JobTrackerContext for this one lookup -- OnTokenValidated
// runs outside the request's normal DI-constructor scope, so RequestServices (the
// per-request scope) must be used directly rather than a captured/singleton one.
// Fail closed if the session row is missing/revoked/expired (including tokens
// with no "sid" claim at all -- see LocalSessionValidator for why: every JWT
// issued going forward carries one, so a token without it is either pre-deploy
// (forces a single re-login for anyone already signed in when this ships --
// acceptable, same additive-forward cost the 2FA/trusted-device features on this
// branch already paid) or forged, and either way isn't proof of a live session.
var db = context.HttpContext.RequestServices.GetRequiredService<JobTrackerContext>();
if (!await LocalSessionValidator.IsValidAsync(db, context.Principal, DateTimeOffset.UtcNow))
{
context.Fail("Session has been revoked or expired.");
}
context.Fail("Local tokens must include a subject/nameidentifier claim.");
return Task.CompletedTask;
}
};
options.TokenValidationParameters = new TokenValidationParameters
@@ -395,19 +378,6 @@ builder.Services.AddRateLimiter(options =>
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0,
}));
// Brute-forcing a 6-digit TOTP code (1e6 space) is far more feasible than a password, so
// this gets a tighter window than auth-login.
options.AddPolicy("auth-2fa-challenge", context =>
RateLimitPartition.GetFixedWindowLimiter(
partitionKey: $"2fa:{context.Connection.RemoteIpAddress?.ToString() ?? "unknown"}",
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 5,
Window = TimeSpan.FromMinutes(5),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0,
}));
});
var app = builder.Build();
+30 -19
View File
@@ -22,34 +22,45 @@ namespace JobTrackerApi.Services
public async Task<JobStats> GetStatsAsync(CancellationToken cancellationToken)
{
var now = DateTime.Now;
var last30 = now.AddDays(-30);
// Project to only the columns the stats need instead of materialising full
// JobApplication rows (which drag large Description/TranslatedDescription/
// TailoredCvText/Notes blobs). Aggregation stays in memory over a small
// per-tenant set.
var all = await _db.JobApplications
// Aggregate server-side (COUNT/GROUP BY) instead of pulling every row into memory.
var total = await _db.JobApplications.AsNoTracking().CountAsync(cancellationToken);
var active = await _db.JobApplications.AsNoTracking().CountAsync(j => !j.IsDeleted, cancellationToken);
var appliedLast30Days = await _db.JobApplications.AsNoTracking()
.CountAsync(j => !j.IsDeleted && j.DateApplied >= last30, cancellationToken);
var byStatus = await _db.JobApplications
.AsNoTracking()
.Select(j => new { j.IsDeleted, j.Status, j.DateApplied })
.Where(j => !j.IsDeleted)
.GroupBy(j => j.Status)
.Select(g => new { Status = g.Key, Count = g.Count() })
.ToListAsync(cancellationToken);
var active = all.Where(j => !j.IsDeleted).ToList();
var byStatusDict = byStatus
.GroupBy(x => string.IsNullOrWhiteSpace(x.Status) ? "Unknown" : x.Status)
.OrderByDescending(g => g.Sum(x => x.Count))
.ToDictionary(g => g.Key, g => g.Sum(x => x.Count));
var byStatus = active
.GroupBy(j => string.IsNullOrWhiteSpace(j.Status) ? "Unknown" : j.Status)
.OrderByDescending(g => g.Count())
.ToDictionary(g => g.Key, g => g.Count());
// ponytail: average age needs a per-row day-diff that doesn't translate identically
// across the SQLite/MySQL providers this app runs on, so pull just the DateApplied
// column (no wide blob columns) for active rows and average client-side.
var activeDates = active == 0
? new List<DateTime>()
: await _db.JobApplications.AsNoTracking()
.Where(j => !j.IsDeleted)
.Select(j => j.DateApplied)
.ToListAsync(cancellationToken);
var appliedLast30Days = active.Count(j => (now - j.DateApplied).TotalDays <= 30);
var avgDays = active.Count == 0
var avgDays = activeDates.Count == 0
? 0
: active.Average(j => Math.Max(0, (now - j.DateApplied).TotalDays));
: activeDates.Average(d => Math.Max(0, (now - d).TotalDays));
return new JobStats(
Total: all.Count,
Active: active.Count,
Deleted: all.Count - active.Count,
ByStatus: byStatus,
Total: total,
Active: active,
Deleted: total - active,
ByStatus: byStatusDict,
AppliedLast30Days: appliedLast30Days,
AverageDaysSinceApplied: Math.Round(avgDays, 1)
);
@@ -1,41 +0,0 @@
using System.Security.Cryptography;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
namespace JobTrackerApi.Services;
// Shared by AuthController (local/Google/Microsoft sign-in) and TwoFactorController (the
// post-challenge sign-in) so the httpOnly session cookie + readable CSRF cookie are always
// issued the same way, from one place. Also the single place a UserSession row is created, so
// every JWT this app ever hands out has a matching server-side row Program.cs can revoke.
public static class AppSessionIssuer
{
public static async Task IssueAsync(HttpRequest request, HttpResponse response, ITokenService tokens, JobTrackerContext db, IConfiguration cfg, ApplicationUser user, bool rememberMe, CancellationToken cancellationToken)
{
var minutes = cfg.GetValue("Auth:JwtExpiresMinutes", 60 * 12);
if (minutes < 5) minutes = 5;
if (minutes > 60 * 24 * 30) minutes = 60 * 24 * 30;
var now = DateTimeOffset.UtcNow;
var session = new UserSession
{
Id = Guid.NewGuid().ToString("N"),
UserId = user.Id,
DeviceLabel = TrustedDeviceService.DescribeUserAgent(request.Headers["User-Agent"].ToString()),
CreatedAtUtc = now,
LastSeenAtUtc = now,
ExpiresAtUtc = now.AddMinutes(minutes),
};
db.UserSessions.Add(session);
await db.SaveChangesAsync(cancellationToken);
var token = await tokens.CreateAccessTokenAsync(user, session.Id, cancellationToken);
var secure = request.IsHttps || string.Equals(request.Headers["X-Forwarded-Proto"], "https", StringComparison.OrdinalIgnoreCase);
response.Cookies.Append(AuthSessionOptions.SessionCookieName, token, AuthSessionOptions.BuildSessionCookie(rememberMe, secure));
var csrf = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
response.Cookies.Append(AuthSessionOptions.CsrfCookieName, csrf, AuthSessionOptions.BuildCsrfCookie(rememberMe, secure));
}
}
@@ -7,7 +7,6 @@ public static class AuthSessionOptions
public const string SessionCookieName = "jobtracker_auth";
public const string CsrfCookieName = "XSRF-TOKEN";
public const string CsrfHeaderName = "X-CSRF-TOKEN";
public const string TrustedDeviceCookieName = "jobtracker_td";
public static CookieOptions BuildSessionCookie(bool persistent, bool secure)
{
@@ -76,35 +75,4 @@ public static class AuthSessionOptions
MaxAge = TimeSpan.Zero,
};
}
// Stricter than the session cookie (SameSite=Strict, never HttpOnly=false): this cookie's
// only job is "skip the 2FA prompt", so it must never be readable by JS and should not even
// be sent on cross-site navigations.
public static CookieOptions BuildTrustedDeviceCookie(bool secure)
{
return new CookieOptions
{
HttpOnly = true,
IsEssential = true,
SameSite = SameSiteMode.Strict,
Secure = secure,
Path = "/",
Expires = DateTimeOffset.UtcNow.AddDays(30),
MaxAge = TimeSpan.FromDays(30),
};
}
public static CookieOptions BuildExpiredTrustedDeviceCookie(bool secure)
{
return new CookieOptions
{
HttpOnly = true,
IsEssential = true,
SameSite = SameSiteMode.Strict,
Secure = secure,
Path = "/",
Expires = DateTimeOffset.UnixEpoch,
MaxAge = TimeSpan.Zero,
};
}
}
@@ -1,12 +1,10 @@
using JobTrackerApi.Services;
namespace JobTrackerApi.Services;
namespace JobTrackerApi.Controllers;
// Pure parsing/formatting helpers for GmailController, split out for readability (Wave 2 safe
// refactor -- no behaviour change). All are static and side-effect free.
public sealed partial class GmailController
// Pure parsing/formatting helpers used by GmailController, split out for readability (no
// behaviour change). All are static and side-effect free.
public static class GmailParsing
{
private static string ApplySyncBoundary(string query, int lookbackDays, bool includeSpamTrash)
public static string ApplySyncBoundary(string query, int lookbackDays, bool includeSpamTrash)
{
var bounded = (query ?? string.Empty).Trim();
if (!bounded.Contains("newer_than:", StringComparison.OrdinalIgnoreCase))
@@ -25,7 +23,7 @@ public sealed partial class GmailController
return bounded.Trim();
}
private static bool LooksLikeJobRelatedThread(IReadOnlyList<GmailQueryMatchedMessage> orderedMessages)
public static bool LooksLikeJobRelatedThread(IReadOnlyList<GmailQueryMatchedMessage> orderedMessages)
{
var sample = string.Join("\n", orderedMessages.Select(item => string.Join(" ", new[] { item.Message.Subject, item.Message.From, item.Message.Snippet }.Where(value => !string.IsNullOrWhiteSpace(value)))));
if (string.IsNullOrWhiteSpace(sample)) return false;
@@ -40,7 +38,7 @@ public sealed partial class GmailController
|| sample.Contains("rejection", StringComparison.OrdinalIgnoreCase);
}
private static string ToConfidence(int score)
public static string ToConfidence(int score)
{
return score switch
{
@@ -50,21 +48,21 @@ public sealed partial class GmailController
};
}
private static string? ExtractFirstEmail(string? value)
public static string? ExtractFirstEmail(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return null;
var match = System.Text.RegularExpressions.Regex.Match(value, @"[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
return match.Success ? match.Value : null;
}
private static string? ExtractRecruiterName(string? value)
public static string? ExtractRecruiterName(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return null;
var trimmed = value.Split('<')[0].Trim().Trim('"');
return string.IsNullOrWhiteSpace(trimmed) || trimmed.Contains('@') ? null : trimmed;
}
private static string? ExtractCompanyName(string? from, string? subject)
public static string? ExtractCompanyName(string? from, string? subject)
{
var subjectText = (subject ?? string.Empty).Trim();
if (!string.IsNullOrWhiteSpace(subjectText))
@@ -77,7 +75,7 @@ public sealed partial class GmailController
return recruiterName is { Length: > 0 } && recruiterName.Contains(' ') ? recruiterName.Split(' ').Last() : null;
}
private static string? ExtractRoleFromSubject(string? subject)
public static string? ExtractRoleFromSubject(string? subject)
{
if (string.IsNullOrWhiteSpace(subject)) return null;
var trimmed = subject.Trim();
@@ -88,7 +86,7 @@ public sealed partial class GmailController
return trimmed.Length <= 120 ? trimmed : trimmed[..120];
}
private static string BuildPopupHtml(bool success, string message)
public static string BuildPopupHtml(bool success, string message)
{
var escaped = System.Net.WebUtility.HtmlEncode(message);
var status = success ? "connected" : "error";
@@ -0,0 +1,622 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using JobTrackerApi.Controllers;
using JobTrackerApi.Models;
using JobTrackerApi.Services.JobImport;
namespace JobTrackerApi.Services
{
/// <summary>
/// Pure, stateless helpers extracted from JobApplicationsController. None of these touch
/// the database, AI services, or other instance state -- same inputs always produce the
/// same outputs, so they are safe to share as static methods.
/// </summary>
public static class JobApplicationHelpers
{
private const string ApplicationAnswerDraftStart = "<<<APPLICATION_ANSWER_DRAFT>>>";
private const string ApplicationAnswerDraftEnd = "<<<END_APPLICATION_ANSWER_DRAFT>>>";
public static string GetPreferredDisplayName(ApplicationUser? user)
{
if (user is null) return "Your Name";
if (!string.IsNullOrWhiteSpace(user.DisplayName)) return user.DisplayName.Trim();
var fullName = string.Join(" ", new[] { user.FirstName?.Trim(), user.LastName?.Trim() }.Where(x => !string.IsNullOrWhiteSpace(x)));
if (!string.IsNullOrWhiteSpace(fullName)) return fullName;
if (!string.IsNullOrWhiteSpace(user.UserName)) return user.UserName.Trim();
if (!string.IsNullOrWhiteSpace(user.Email)) return user.Email.Trim();
return "Your Name";
}
public static string BuildGreeting(JobApplication job)
{
if (!string.IsNullOrWhiteSpace(job.Company?.RecruiterName)) return $"Hi {job.Company.RecruiterName.Trim()},";
if (!string.IsNullOrWhiteSpace(job.Company?.Name)) return $"Hi {job.Company.Name.Trim()} team,";
return "Hi there,";
}
public static string BuildStructuredCvContext(ApplicationUser? user)
{
var structured = StructuredCvProfileJson.Deserialize(user?.ProfileCvStructureJson);
var blocks = new List<string>();
var contactLines = new List<string>();
if (!string.IsNullOrWhiteSpace(structured.Contact.FullName)) contactLines.Add($"Name: {structured.Contact.FullName}");
if (!string.IsNullOrWhiteSpace(structured.Contact.Headline)) contactLines.Add($"Headline: {structured.Contact.Headline}");
if (!string.IsNullOrWhiteSpace(structured.Contact.Email)) contactLines.Add($"Email: {structured.Contact.Email}");
if (!string.IsNullOrWhiteSpace(structured.Contact.Location)) contactLines.Add($"Location: {structured.Contact.Location}");
if (!string.IsNullOrWhiteSpace(structured.Contact.LinkedIn)) contactLines.Add($"LinkedIn: {structured.Contact.LinkedIn}");
if (contactLines.Count > 0) blocks.Add($"Contact:\n{string.Join("\n", contactLines)}");
if (structured.Summary.Count > 0)
{
blocks.Add($"Summary:\n- {string.Join("\n- ", structured.Summary.Take(4))}");
}
if (structured.Skills.Count > 0)
{
blocks.Add($"Skills:\n{string.Join(", ", structured.Skills.Take(16))}");
}
if (structured.Jobs.Count > 0)
{
var jobBlocks = structured.Jobs.Take(3).Select(job =>
{
var header = string.Join(" | ", new[] { job.Title, job.Company, job.Location, FormatStructuredDateRange(job.Start, job.End, job.IsCurrent) }.Where(value => !string.IsNullOrWhiteSpace(value)));
var bullets = job.Bullets.Take(3).Select(bullet => $"- {bullet}");
return string.Join("\n", new[] { header }.Concat(bullets).Where(value => !string.IsNullOrWhiteSpace(value)));
}).Where(value => !string.IsNullOrWhiteSpace(value)).ToList();
if (jobBlocks.Count > 0) blocks.Add($"Work Experience:\n{string.Join("\n\n", jobBlocks)}");
}
if (structured.Education.Count > 0)
{
var items = structured.Education.Take(3).Select(education => string.Join(" | ", new[] { education.Qualification, education.Institution, education.Location, FormatStructuredDateRange(education.Start, education.End, false) }.Where(value => !string.IsNullOrWhiteSpace(value))));
blocks.Add($"Education:\n- {string.Join("\n- ", items)}");
}
if (structured.Languages.Count > 0)
{
var items = structured.Languages.Take(5).Select(language => string.Join(": ", new[] { language.Name, language.Level }.Where(value => !string.IsNullOrWhiteSpace(value))));
blocks.Add($"Languages:\n- {string.Join("\n- ", items)}");
}
if (structured.OtherSections.Count > 0)
{
var items = structured.OtherSections.Take(2)
.Where(section => !string.IsNullOrWhiteSpace(section.Title) && section.Items.Count > 0)
.Select(section => $"{section.Title}: {string.Join("; ", section.Items.Take(4))}")
.ToList();
if (items.Count > 0) blocks.Add($"Other sections:\n- {string.Join("\n- ", items)}");
}
if (blocks.Count == 0 && structured.Sections.Count > 0)
{
blocks.AddRange(structured.Sections.Take(6).Select(section => $"{section.Name}:\n{section.Content}"));
}
return blocks.Count > 0
? $"Structured CV:\n{string.Join("\n\n", blocks)}"
: string.Empty;
}
public static string BuildCvSearchCorpus(ApplicationUser? user)
{
var structured = StructuredCvProfileJson.Deserialize(user?.ProfileCvStructureJson);
var parts = new List<string>();
if (!string.IsNullOrWhiteSpace(user?.ProfileCvText)) parts.Add(user.ProfileCvText!);
if (!string.IsNullOrWhiteSpace(structured.Contact.Headline)) parts.Add(structured.Contact.Headline!);
if (structured.Summary.Count > 0) parts.Add(string.Join("\n", structured.Summary));
if (structured.Skills.Count > 0) parts.Add(string.Join("\n", structured.Skills));
if (structured.Jobs.Count > 0)
{
parts.Add(string.Join("\n", structured.Jobs.SelectMany(job => new[] { job.Title, job.Company, job.Location }.Where(value => !string.IsNullOrWhiteSpace(value)).Concat(job.Bullets).Concat(job.Skills))));
}
if (structured.Education.Count > 0)
{
parts.Add(string.Join("\n", structured.Education.SelectMany(education => new[] { education.Qualification, education.Institution, education.Location }.Where(value => !string.IsNullOrWhiteSpace(value)).Concat(education.Details))));
}
if (structured.Languages.Count > 0)
{
parts.Add(string.Join("\n", structured.Languages.Select(language => string.Join(" ", new[] { language.Name, language.Level, language.Notes }.Where(value => !string.IsNullOrWhiteSpace(value))))));
}
return string.Join("\n", parts.Where(part => !string.IsNullOrWhiteSpace(part)));
}
public static string? FormatStructuredDateRange(string? start, string? end, bool isCurrent)
{
if (string.IsNullOrWhiteSpace(start) && string.IsNullOrWhiteSpace(end)) return null;
if (string.IsNullOrWhiteSpace(start)) return end;
return $"{start} - {(isCurrent ? "Present" : end ?? "Present")}";
}
public static string ComputeGenerationContextHash(string value)
{
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(value ?? string.Empty));
return Convert.ToHexString(bytes).ToLowerInvariant();
}
public static int ScoreTailoredExperience(StructuredCvJob job, IEnumerable<string> matchedTags)
{
var corpus = string.Join("\n", new[] { job.Title, job.Company, job.Location, string.Join("\n", job.Bullets), string.Join("\n", job.Skills) }
.Where(value => !string.IsNullOrWhiteSpace(value)))
.ToLowerInvariant();
var score = 0;
foreach (var tag in matchedTags.Where(tag => !string.IsNullOrWhiteSpace(tag)))
{
if (corpus.Contains(tag.ToLowerInvariant(), StringComparison.Ordinal)) score += 4;
}
score += Math.Min(job.Bullets.Count, 4);
return score;
}
public static List<string> SelectTailoredSkills(StructuredCvProfile structured, string jobText)
{
var jobTags = SkillTagger.Detect(jobText).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
var prioritized = structured.Skills
.Select(skill => new
{
Skill = skill,
Score = jobTags.Any(tag => skill.Contains(tag, StringComparison.OrdinalIgnoreCase) || tag.Contains(skill, StringComparison.OrdinalIgnoreCase)) ? 2 : 0
})
.OrderByDescending(entry => entry.Score)
.ThenBy(entry => entry.Skill, StringComparer.OrdinalIgnoreCase)
.Select(entry => entry.Skill)
.ToList();
if (prioritized.Count == 0)
{
prioritized = structured.Jobs.SelectMany(job => job.Skills).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
}
return prioritized.Take(10).ToList();
}
public static TailoredCvDocument BuildLegacyTailoredCvFallback(JobApplication job)
{
var text = (job.TailoredCvText ?? string.Empty).Trim();
var document = new TailoredCvDocument
{
Headline = job.JobTitle,
CustomSections = string.IsNullOrWhiteSpace(text)
? new List<TailoredCvCustomSection>()
: new List<TailoredCvCustomSection>
{
new TailoredCvCustomSection
{
Title = "Legacy draft text",
Items = text.Split(new[] { "\r\n\r\n", "\n\n" }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList(),
}
}
};
return TailoredCvDraftJson.Normalize(document);
}
public static TailoredCvDraftDto ToTailoredCvDraftDto(TailoredCvDraft draft)
{
var document = TailoredCvDraftJson.FromDraft(draft);
return new TailoredCvDraftDto(
draft.Id,
draft.CanonicalProfileVersion,
draft.TemplateId,
document.Headline,
document.Summary,
document.SelectedSkills,
document.Experience,
document.Education,
document.CustomSections,
document.RenderOptions,
draft.GenerationContextHash,
draft.LastGeneratedAtUtc,
draft.LastEditedAtUtc,
draft.Status,
TailoredCvDraftJson.RenderPlainText(document),
false);
}
public static TailoredCvDraftDto ToLegacyTailoredCvDraftDto(JobApplication job)
{
var document = BuildLegacyTailoredCvFallback(job);
return new TailoredCvDraftDto(
null,
null,
"legacy-text",
document.Headline,
document.Summary,
document.SelectedSkills,
document.Experience,
document.Education,
document.CustomSections,
document.RenderOptions,
null,
null,
job.TailoredCvUpdatedAt,
string.IsNullOrWhiteSpace(job.TailoredCvText) ? "empty" : "legacy-import",
TailoredCvDraftJson.RenderPlainText(document),
true);
}
public static TailoredCvDocument BuildTailoredCvDocumentForRender(SaveTailoredCvDraftRequest? request, TailoredCvDraft? draft, JobApplication job)
{
var baseDocument = draft is not null ? TailoredCvDraftJson.FromDraft(draft) : BuildLegacyTailoredCvFallback(job);
if (request is null)
{
return baseDocument;
}
return TailoredCvDraftJson.Normalize(new TailoredCvDocument
{
TemplateId = request.TemplateId ?? baseDocument.TemplateId ?? "ats-minimal",
Headline = request.Headline ?? baseDocument.Headline,
Summary = request.Summary ?? baseDocument.Summary,
SelectedSkills = request.SelectedSkills ?? baseDocument.SelectedSkills,
Experience = request.Experience ?? baseDocument.Experience,
Education = request.Education ?? baseDocument.Education,
CustomSections = request.CustomSections ?? baseDocument.CustomSections,
RenderOptions = request.RenderOptions ?? baseDocument.RenderOptions,
});
}
public static string? ExtractSavedApplicationAnswerDraft(string? notes)
{
var value = (notes ?? string.Empty).Trim();
if (string.IsNullOrWhiteSpace(value)) return null;
var startIndex = value.IndexOf(ApplicationAnswerDraftStart, StringComparison.Ordinal);
var endIndex = value.IndexOf(ApplicationAnswerDraftEnd, StringComparison.Ordinal);
if (startIndex >= 0 && endIndex > startIndex)
{
var between = value[(startIndex + ApplicationAnswerDraftStart.Length)..endIndex].Trim();
return string.IsNullOrWhiteSpace(between) ? null : between;
}
const string legacyPrefix = "Application answer draft:";
var legacyIndex = value.IndexOf(legacyPrefix, StringComparison.OrdinalIgnoreCase);
if (legacyIndex >= 0)
{
var legacy = value[(legacyIndex + legacyPrefix.Length)..].Trim();
return string.IsNullOrWhiteSpace(legacy) ? null : legacy;
}
return null;
}
public static string BuildFollowUpSubject(JobApplication job, Correspondence? lastMessage)
{
var subject = (lastMessage?.Subject ?? string.Empty).Trim();
if (!string.IsNullOrWhiteSpace(subject))
{
return subject.StartsWith("Re:", StringComparison.OrdinalIgnoreCase)
? subject
: $"Re: {subject}";
}
return $"Following up on {job.JobTitle} application";
}
public static List<string> BuildFollowUpContextSignals(JobApplication job, Correspondence? lastMessage, CorrespondenceContextResult? correspondenceContext, SavedPackageMaterial savedPackageMaterial, string? savedApplicationAnswer)
{
var signals = new List<string>();
if (!string.IsNullOrWhiteSpace(job.Company?.RecruiterName)) signals.Add($"Recruiter contact: {job.Company.RecruiterName.Trim()}");
if (!string.IsNullOrWhiteSpace(job.Company?.RecruiterEmail)) signals.Add($"Recruiter email on file: {job.Company.RecruiterEmail.Trim()}");
if (lastMessage is not null)
{
signals.Add($"Latest correspondence: {lastMessage.Date:yyyy-MM-dd} — {lastMessage.Subject ?? "(no subject)"}");
}
if (correspondenceContext?.Participants.Count > 0)
{
signals.Add($"Thread participants: {string.Join(", ", correspondenceContext.Participants.Take(3))}");
}
if (!string.IsNullOrWhiteSpace(savedPackageMaterial.CoverLetterText)) signals.Add("Saved cover letter available");
if (!string.IsNullOrWhiteSpace(savedPackageMaterial.RecruiterMessageDraft)) signals.Add("Saved recruiter message available");
if (!string.IsNullOrWhiteSpace(savedPackageMaterial.TailoredCvText)) signals.Add("Saved tailored CV available");
if (!string.IsNullOrWhiteSpace(savedApplicationAnswer)) signals.Add("Saved application answer available");
if (correspondenceContext is not null)
{
foreach (var signal in correspondenceContext.Signals)
{
if (!signals.Contains(signal, StringComparer.OrdinalIgnoreCase)) signals.Add(signal);
}
}
return signals.Take(6).ToList();
}
public static bool IsExtractableAttachmentExtension(string? extension)
{
return extension?.Trim().ToLowerInvariant() switch
{
".pdf" => true,
".docx" => true,
".txt" => true,
".md" => true,
".png" => true,
".jpg" => true,
".jpeg" => true,
".webp" => true,
_ => false,
};
}
public static List<string> BuildFollowUpApproach(string status, List<string> matchedTags, List<string> missingTags)
{
var normalized = (status ?? string.Empty).Trim();
var advice = new List<string>();
switch (normalized)
{
case "Applied":
advice.Add("Follow up briefly, reaffirm interest, and reference the date you applied.");
advice.Add("Mention one or two of the strongest overlaps from the posting instead of repeating your whole background.");
break;
case "Waiting":
advice.Add("Acknowledge that you are following up on next steps and keep the message light but specific.");
advice.Add("Use one proof point that shows why you remain a strong fit.");
break;
case "Interview":
case "Interviewing":
advice.Add("Focus on momentum, appreciation, and readiness for the next step.");
advice.Add("Reference a memorable point from the process, discussion, or role priorities if possible.");
break;
case "Offer":
advice.Add("Keep the tone warm and professional, and focus on clarifying next steps or timing.");
advice.Add("Avoid sounding pushy; frame the note around alignment and practical progress.");
break;
case "Rejected":
advice.Add("If appropriate, ask for feedback with a respectful and concise tone.");
advice.Add("Keep the door open for future opportunities instead of arguing the decision.");
break;
default:
advice.Add("Match the tone to the current stage and be specific about why you are following up now.");
advice.Add("Keep it concise, credible, and easy to respond to.");
break;
}
if (matchedTags.Any()) advice.Add($"Lead with relevant overlap such as {string.Join(", ", matchedTags.Take(2))}.");
if (missingTags.Any()) advice.Add($"Do not overstate areas like {string.Join(", ", missingTags.Take(2))}; frame them honestly.");
return advice.Distinct(StringComparer.OrdinalIgnoreCase).Take(5).ToList();
}
public static IEnumerable<string> SplitTags(string? s)
{
if (string.IsNullOrWhiteSpace(s)) yield break;
var trimmed = s.Trim();
List<string>? jsonTags = null;
if (trimmed.StartsWith("[") && trimmed.EndsWith("]"))
{
try
{
jsonTags = JsonSerializer.Deserialize<List<string>>(trimmed);
}
catch
{
jsonTags = null;
}
}
if (jsonTags is not null)
{
foreach (var x in jsonTags)
{
var t = (x ?? string.Empty).Trim();
if (t.Length == 0) continue;
yield return t;
}
yield break;
}
foreach (var raw in trimmed.Split(new[] { ',', ';', '\n', '\r', '\t' }, StringSplitOptions.RemoveEmptyEntries))
{
var t = raw.Trim();
if (t.Length == 0) continue;
yield return t;
}
}
public static string NormalizeForComparison(string value)
{
if (string.IsNullOrWhiteSpace(value)) return string.Empty;
return new string(value.Trim().ToLowerInvariant().Where(char.IsLetterOrDigit).ToArray());
}
public static string BuildSummarySource(JobApplication job)
{
// Prefer translated text for summaries and skill extraction so non-English
// postings become easier to understand while keeping the original text intact.
var parts = new[]
{
job.TranslatedDescription,
job.Description,
job.Notes
};
return string.Join("\n\n", parts.Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x!.Trim()));
}
public static string? NormalizeTags(string? raw)
{
var normalized = SplitTags(raw)
.Select(tag => tag.Trim())
.Where(tag => tag.Length > 0)
.GroupBy(tag => tag, StringComparer.OrdinalIgnoreCase)
.Select(group =>
{
var first = group.First();
return string.Join(" ", first.Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(part => char.ToUpperInvariant(part[0]) + part[1..].ToLowerInvariant()));
})
.OrderBy(tag => tag, StringComparer.OrdinalIgnoreCase)
.ToList();
return normalized.Count == 0 ? null : JsonSerializer.Serialize(normalized);
}
public static string? NormalizeUrl(string? url)
{
if (string.IsNullOrWhiteSpace(url)) return null;
var value = url.Trim();
return Uri.TryCreate(value, UriKind.Absolute, out var uri) ? uri.ToString() : value;
}
public static string RemoveSavedApplicationAnswerDraft(string? notes)
{
var value = notes ?? string.Empty;
if (string.IsNullOrWhiteSpace(value)) return string.Empty;
var startIndex = value.IndexOf(ApplicationAnswerDraftStart, StringComparison.Ordinal);
var endIndex = value.IndexOf(ApplicationAnswerDraftEnd, StringComparison.Ordinal);
if (startIndex >= 0 && endIndex > startIndex)
{
var before = value[..startIndex].Trim();
var after = value[(endIndex + ApplicationAnswerDraftEnd.Length)..].Trim();
return string.Join("\n\n", new[] { before, after }.Where(part => !string.IsNullOrWhiteSpace(part))).Trim();
}
const string legacyPrefix = "Application answer draft:";
var legacyIndex = value.IndexOf(legacyPrefix, StringComparison.OrdinalIgnoreCase);
if (legacyIndex >= 0)
{
return value[..legacyIndex].Trim();
}
return value.Trim();
}
public static bool HasInterviewPrepNotes(string? notes) => !string.IsNullOrWhiteSpace(RemoveSavedApplicationAnswerDraft(notes));
public static bool IsInterviewStage(string status) =>
status.Contains("Interview", StringComparison.OrdinalIgnoreCase);
public static bool IsActiveWorkflowStatus(string status)
{
var normalized = (status ?? string.Empty).Trim();
return normalized switch
{
"Applied" => true,
"Waiting" => true,
"Interview" => true,
"Interviewing" => true,
"Offer" => true,
_ => false,
};
}
public static WorkflowSignalDto BuildWorkflowSignal(JobApplication job, FollowUpDecision followUpDecision)
{
var hasTailoredCv = !string.IsNullOrWhiteSpace(job.TailoredCvText);
var hasSavedApplicationAnswerDraft = !string.IsNullOrWhiteSpace(ExtractSavedApplicationAnswerDraft(job.Notes));
var hasInterviewPrepNotes = HasInterviewPrepNotes(job.Notes);
var needsInterviewPrep = IsInterviewStage(job.Status) && !hasInterviewPrepNotes;
var hasPackageGap = IsActiveWorkflowStatus(job.Status) && (!hasTailoredCv || !hasSavedApplicationAnswerDraft);
var needsFollowUpAction = followUpDecision.NeedsFollowUp || (!job.ResponseReceived && job.FollowUpAt is null);
if (needsInterviewPrep)
{
return new WorkflowSignalDto(
ActionKey: "interview-prep",
Reason: "Interview stage reached but prep notes are still missing.",
WorkspaceTab: "interview-prep",
FollowMode: null,
NeedsAttention: true,
HasPackageGap: hasPackageGap,
NeedsInterviewPrep: true,
NeedsFollowUpAction: needsFollowUpAction,
HasTailoredCv: hasTailoredCv,
HasSavedApplicationAnswerDraft: hasSavedApplicationAnswerDraft,
HasInterviewPrepNotes: hasInterviewPrepNotes);
}
if (hasPackageGap)
{
var reason = !hasTailoredCv && !hasSavedApplicationAnswerDraft
? "Tailored CV and saved application answers still need work."
: !hasTailoredCv
? "Tailored CV missing for this role."
: "Saved application answers still need work.";
return new WorkflowSignalDto(
ActionKey: "package-work",
Reason: reason,
WorkspaceTab: "tailored-cv",
FollowMode: null,
NeedsAttention: true,
HasPackageGap: true,
NeedsInterviewPrep: needsInterviewPrep,
NeedsFollowUpAction: needsFollowUpAction,
HasTailoredCv: hasTailoredCv,
HasSavedApplicationAnswerDraft: hasSavedApplicationAnswerDraft,
HasInterviewPrepNotes: hasInterviewPrepNotes);
}
if (needsFollowUpAction)
{
var reason = !string.IsNullOrWhiteSpace(followUpDecision.Reason)
? followUpDecision.Reason!
: !job.ResponseReceived && job.FollowUpAt is null
? "No response yet and no follow-up is scheduled."
: "Follow-up is due for this role.";
return new WorkflowSignalDto(
ActionKey: "follow-up",
Reason: reason,
WorkspaceTab: "follow-up",
FollowMode: "waiting-update",
NeedsAttention: true,
HasPackageGap: hasPackageGap,
NeedsInterviewPrep: needsInterviewPrep,
NeedsFollowUpAction: true,
HasTailoredCv: hasTailoredCv,
HasSavedApplicationAnswerDraft: hasSavedApplicationAnswerDraft,
HasInterviewPrepNotes: hasInterviewPrepNotes);
}
return new WorkflowSignalDto(
ActionKey: "review-readiness",
Reason: "No urgent workflow gaps are blocking this job right now.",
WorkspaceTab: "readiness",
FollowMode: null,
NeedsAttention: false,
HasPackageGap: hasPackageGap,
NeedsInterviewPrep: needsInterviewPrep,
NeedsFollowUpAction: needsFollowUpAction,
HasTailoredCv: hasTailoredCv,
HasSavedApplicationAnswerDraft: hasSavedApplicationAnswerDraft,
HasInterviewPrepNotes: hasInterviewPrepNotes);
}
public static List<string> BuildReadinessReminders(JobApplication job, WorkflowSignalDto workflowSignal)
{
var reminders = new List<string>();
if (workflowSignal.HasPackageGap)
{
reminders.Add(workflowSignal.HasTailoredCv
? "Saved application answers are still missing from the package."
: workflowSignal.HasSavedApplicationAnswerDraft
? "This role is active but still missing a tailored CV."
: "This role is active but still needs a tailored CV and saved application answers.");
}
if (workflowSignal.NeedsInterviewPrep)
{
reminders.Add("Interview stage reached but prep notes are still missing.");
}
if (workflowSignal.NeedsFollowUpAction)
{
reminders.Add(job.FollowUpAt is null
? "No response yet and no follow-up is scheduled."
: workflowSignal.Reason);
}
return reminders
.Where(reminder => !string.IsNullOrWhiteSpace(reminder))
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
}
}
}
@@ -1,30 +0,0 @@
using System.Security.Claims;
using JobTrackerApi.Data;
using Microsoft.EntityFrameworkCore;
namespace JobTrackerApi.Services;
// The actual revocation check behind Program.cs's "local" JwtBearer OnTokenValidated. Pulled out
// of Program.cs so it's unit-testable without standing up a full TestServer/HTTP pipeline.
public static class LocalSessionValidator
{
public static async Task<bool> IsValidAsync(JobTrackerContext db, ClaimsPrincipal? principal, DateTimeOffset now, CancellationToken cancellationToken = default)
{
var sid = principal?.FindFirst("sid")?.Value;
// Fail closed: see the comment on the OnTokenValidated wiring in Program.cs for why a
// missing sid is rejected rather than grandfathered in.
if (string.IsNullOrWhiteSpace(sid)) return false;
var session = await db.UserSessions.IgnoreQueryFilters()
.FirstOrDefaultAsync(x => x.Id == sid, cancellationToken);
if (session is null || session.RevokedAtUtc is not null || session.ExpiresAtUtc <= now) return false;
if (now - session.LastSeenAtUtc > TimeSpan.FromMinutes(5))
{
session.LastSeenAtUtc = now;
await db.SaveChangesAsync(cancellationToken);
}
return true;
}
}
@@ -244,9 +244,6 @@ public static class StartupInitializationExtensions
`MicrosoftSubject` longtext NULL,
`MicrosoftEmail` longtext NULL,
`MicrosoftLinkedAt` datetime(6) NULL,
`TotpSecretEncrypted` longtext NULL,
`TotpPendingSecretEncrypted` longtext NULL,
`TotpEnabledAtUtc` datetime(6) NULL,
PRIMARY KEY (`Id`)
) CHARACTER SET=utf8mb4;
@@ -362,10 +359,7 @@ public static class StartupInitializationExtensions
"GoogleLinkedAt" TEXT NULL,
"MicrosoftSubject" TEXT NULL,
"MicrosoftEmail" TEXT NULL,
"MicrosoftLinkedAt" TEXT NULL,
"TotpSecretEncrypted" TEXT NULL,
"TotpPendingSecretEncrypted" TEXT NULL,
"TotpEnabledAtUtc" TEXT NULL
"MicrosoftLinkedAt" TEXT NULL
);
""");
@@ -446,9 +440,6 @@ public static class StartupInitializationExtensions
EnsureColumn(conn, "AspNetUsers", "MicrosoftSubject", "ALTER TABLE AspNetUsers ADD COLUMN MicrosoftSubject TEXT NULL;");
EnsureColumn(conn, "AspNetUsers", "MicrosoftEmail", "ALTER TABLE AspNetUsers ADD COLUMN MicrosoftEmail TEXT NULL;");
EnsureColumn(conn, "AspNetUsers", "MicrosoftLinkedAt", "ALTER TABLE AspNetUsers ADD COLUMN MicrosoftLinkedAt TEXT NULL;");
EnsureColumn(conn, "AspNetUsers", "TotpSecretEncrypted", "ALTER TABLE AspNetUsers ADD COLUMN TotpSecretEncrypted TEXT NULL;");
EnsureColumn(conn, "AspNetUsers", "TotpPendingSecretEncrypted", "ALTER TABLE AspNetUsers ADD COLUMN TotpPendingSecretEncrypted TEXT NULL;");
EnsureColumn(conn, "AspNetUsers", "TotpEnabledAtUtc", "ALTER TABLE AspNetUsers ADD COLUMN TotpEnabledAtUtc TEXT NULL;");
static void EnsureUserRuleSettingsTable(DbConnection c)
{
@@ -632,63 +623,10 @@ public static class StartupInitializationExtensions
Exec(c, """CREATE INDEX IF NOT EXISTS "IX_TailoredCvDrafts_JobApplicationId" ON "TailoredCvDrafts" ("JobApplicationId");""");
}
static void EnsureTwoFactorRecoveryCodesTable(DbConnection c)
{
Exec(c, """
CREATE TABLE IF NOT EXISTS "TwoFactorRecoveryCodes" (
"Id" INTEGER NOT NULL CONSTRAINT "PK_TwoFactorRecoveryCodes" PRIMARY KEY AUTOINCREMENT,
"UserId" TEXT NOT NULL,
"CodeHash" TEXT NOT NULL,
"CreatedAtUtc" TEXT NOT NULL,
"UsedAtUtc" TEXT NULL
);
""");
Exec(c, """CREATE INDEX IF NOT EXISTS "IX_TwoFactorRecoveryCodes_UserId_UsedAtUtc" ON "TwoFactorRecoveryCodes" ("UserId", "UsedAtUtc");""");
}
static void EnsureTrustedDevicesTable(DbConnection c)
{
Exec(c, """
CREATE TABLE IF NOT EXISTS "TrustedDevices" (
"Id" INTEGER NOT NULL CONSTRAINT "PK_TrustedDevices" PRIMARY KEY AUTOINCREMENT,
"UserId" TEXT NOT NULL,
"TokenHash" TEXT NOT NULL,
"DeviceLabel" TEXT NULL,
"CreatedAtUtc" TEXT NOT NULL,
"LastSeenAtUtc" TEXT NOT NULL,
"ExpiresAtUtc" TEXT NOT NULL
);
""");
Exec(c, """CREATE INDEX IF NOT EXISTS "IX_TrustedDevices_UserId" ON "TrustedDevices" ("UserId");""");
Exec(c, """CREATE INDEX IF NOT EXISTS "IX_TrustedDevices_TokenHash" ON "TrustedDevices" ("TokenHash");""");
}
static void EnsureUserSessionsTable(DbConnection c)
{
Exec(c, """
CREATE TABLE IF NOT EXISTS "UserSessions" (
"Id" TEXT NOT NULL CONSTRAINT "PK_UserSessions" PRIMARY KEY,
"UserId" TEXT NOT NULL,
"DeviceLabel" TEXT NULL,
"CreatedAtUtc" TEXT NOT NULL,
"LastSeenAtUtc" TEXT NOT NULL,
"ExpiresAtUtc" TEXT NOT NULL,
"RevokedAtUtc" TEXT NULL
);
""");
Exec(c, """CREATE INDEX IF NOT EXISTS "IX_UserSessions_UserId" ON "UserSessions" ("UserId");""");
}
EnsureGmailConnectionsTable(conn);
EnsureMicrosoftGraphConnectionsTable(conn);
EnsureImapConnectionsTable(conn);
EnsureCvTables(conn);
EnsureTwoFactorRecoveryCodesTable(conn);
EnsureTrustedDevicesTable(conn);
EnsureUserSessionsTable(conn);
// Legacy DB signature: migration history exists (AddCorrespondence applied), but 20260310195000 not recorded,
// and at least one of the new columns already exists.
@@ -750,6 +688,17 @@ public static class StartupInitializationExtensions
{
Exec(conn, """CREATE INDEX IF NOT EXISTS "IX_JobApplications_OwnerUserId_IsDeleted" ON "JobApplications" ("OwnerUserId", "IsDeleted");""");
Exec(conn, """CREATE INDEX IF NOT EXISTS "IX_JobApplications_OwnerUserId_FollowUpAt" ON "JobApplications" ("OwnerUserId", "FollowUpAt");""");
Exec(conn, """CREATE INDEX IF NOT EXISTS "IX_JobApplications_OwnerUserId_IsDeleted_Status" ON "JobApplications" ("OwnerUserId", "IsDeleted", "Status");""");
}
if (HasTable(conn, "Correspondences"))
{
Exec(conn, """CREATE INDEX IF NOT EXISTS "IX_Correspondences_JobApplicationId" ON "Correspondences" ("JobApplicationId");""");
}
if (HasTable(conn, "JobEvents"))
{
Exec(conn, """CREATE INDEX IF NOT EXISTS "IX_JobEvents_JobApplicationId" ON "JobEvents" ("JobApplicationId");""");
}
// Ensure data folder exists before creating/opening SQLite files.
@@ -831,9 +780,6 @@ public static class StartupInitializationExtensions
EnsureMySqlColumn(conn, "AspNetUsers", "MicrosoftSubject", "ALTER TABLE `AspNetUsers` ADD COLUMN `MicrosoftSubject` longtext NULL;");
EnsureMySqlColumn(conn, "AspNetUsers", "MicrosoftEmail", "ALTER TABLE `AspNetUsers` ADD COLUMN `MicrosoftEmail` longtext NULL;");
EnsureMySqlColumn(conn, "AspNetUsers", "MicrosoftLinkedAt", "ALTER TABLE `AspNetUsers` ADD COLUMN `MicrosoftLinkedAt` datetime NULL;");
EnsureMySqlColumn(conn, "AspNetUsers", "TotpSecretEncrypted", "ALTER TABLE `AspNetUsers` ADD COLUMN `TotpSecretEncrypted` longtext NULL;");
EnsureMySqlColumn(conn, "AspNetUsers", "TotpPendingSecretEncrypted", "ALTER TABLE `AspNetUsers` ADD COLUMN `TotpPendingSecretEncrypted` longtext NULL;");
EnsureMySqlColumn(conn, "AspNetUsers", "TotpEnabledAtUtc", "ALTER TABLE `AspNetUsers` ADD COLUMN `TotpEnabledAtUtc` datetime NULL;");
if (!HasMySqlTable(conn, "RuleSettings"))
{
@@ -1042,183 +988,66 @@ public static class StartupInitializationExtensions
cmd.ExecuteNonQuery();
}
if (!HasMySqlTable(conn, "TwoFactorRecoveryCodes"))
// Schema reconciliation must never crash app startup: an index that fails
// (e.g. combined key exceeds MySQL's 3072-byte limit because an older
// migration made OwnerUserId wider than the varchar(255) this reconciler
// assumes) is logged and skipped rather than taking prod down. OwnerUserId
// is prefix-indexed at 191 chars (safe under utf8mb4's 767-byte legacy
// per-column key limit, and far longer than the GUID-like Identity ids
// actually stored there) so composite indexes stay well under the cap
// regardless of the column's declared width.
void TryCreateIndex(string table, string indexName, string columnsSql)
{
using var cmd = conn.CreateCommand();
cmd.CommandText = @"CREATE TABLE IF NOT EXISTS `TwoFactorRecoveryCodes` (
`Id` int NOT NULL AUTO_INCREMENT,
`UserId` varchar(255) NOT NULL,
`CodeHash` varchar(255) NOT NULL,
`CreatedAtUtc` datetime(6) NOT NULL,
`UsedAtUtc` datetime(6) NULL,
PRIMARY KEY (`Id`)
);";
cmd.ExecuteNonQuery();
if (MySqlIndexExists(conn, table, indexName)) return;
try
{
using var cmd = conn.CreateCommand();
cmd.CommandText = $"CREATE INDEX `{indexName}` ON `{table}` ({columnsSql});";
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
app.Logger.LogWarning(ex, "Skipping index {Index} on {Table} during startup reconciliation.", indexName, table);
}
}
EnsureMySqlAutoIncrementPrimaryKey(conn, "TwoFactorRecoveryCodes", "Id");
if (!MySqlIndexExists(conn, "TwoFactorRecoveryCodes", "IX_TwoFactorRecoveryCodes_UserId_UsedAtUtc"))
void TryCreateUniqueIndex(string table, string indexName, string columnsSql)
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE INDEX `IX_TwoFactorRecoveryCodes_UserId_UsedAtUtc` ON `TwoFactorRecoveryCodes` (`UserId`, `UsedAtUtc`);";
cmd.ExecuteNonQuery();
if (MySqlIndexExists(conn, table, indexName)) return;
try
{
using var cmd = conn.CreateCommand();
cmd.CommandText = $"CREATE UNIQUE INDEX `{indexName}` ON `{table}` ({columnsSql});";
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
app.Logger.LogWarning(ex, "Skipping unique index {Index} on {Table} during startup reconciliation.", indexName, table);
}
}
if (!HasMySqlTable(conn, "TrustedDevices"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = @"CREATE TABLE IF NOT EXISTS `TrustedDevices` (
`Id` int NOT NULL AUTO_INCREMENT,
`UserId` varchar(255) NOT NULL,
`TokenHash` varchar(255) NOT NULL,
`DeviceLabel` varchar(255) NULL,
`CreatedAtUtc` datetime(6) NOT NULL,
`LastSeenAtUtc` datetime(6) NOT NULL,
`ExpiresAtUtc` datetime(6) NOT NULL,
PRIMARY KEY (`Id`)
);";
cmd.ExecuteNonQuery();
}
EnsureMySqlAutoIncrementPrimaryKey(conn, "TrustedDevices", "Id");
if (!MySqlIndexExists(conn, "TrustedDevices", "IX_TrustedDevices_UserId"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE INDEX `IX_TrustedDevices_UserId` ON `TrustedDevices` (`UserId`);";
cmd.ExecuteNonQuery();
}
if (!MySqlIndexExists(conn, "TrustedDevices", "IX_TrustedDevices_TokenHash"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE INDEX `IX_TrustedDevices_TokenHash` ON `TrustedDevices` (`TokenHash`);";
cmd.ExecuteNonQuery();
}
if (!HasMySqlTable(conn, "UserSessions"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = @"CREATE TABLE IF NOT EXISTS `UserSessions` (
`Id` varchar(64) NOT NULL,
`UserId` varchar(255) NOT NULL,
`DeviceLabel` varchar(255) NULL,
`CreatedAtUtc` datetime(6) NOT NULL,
`LastSeenAtUtc` datetime(6) NOT NULL,
`ExpiresAtUtc` datetime(6) NOT NULL,
`RevokedAtUtc` datetime(6) NULL,
PRIMARY KEY (`Id`)
);";
cmd.ExecuteNonQuery();
}
if (!MySqlIndexExists(conn, "UserSessions", "IX_UserSessions_UserId"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE INDEX `IX_UserSessions_UserId` ON `UserSessions` (`UserId`);";
cmd.ExecuteNonQuery();
}
if (!MySqlIndexExists(conn, "Companies", "IX_Companies_OwnerUserId"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE INDEX `IX_Companies_OwnerUserId` ON `Companies` (`OwnerUserId`);";
cmd.ExecuteNonQuery();
}
if (!MySqlIndexExists(conn, "JobApplications", "IX_JobApplications_OwnerUserId"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE INDEX `IX_JobApplications_OwnerUserId` ON `JobApplications` (`OwnerUserId`);";
cmd.ExecuteNonQuery();
}
TryCreateIndex("Companies", "IX_Companies_OwnerUserId", "`OwnerUserId`(191)");
TryCreateIndex("JobApplications", "IX_JobApplications_OwnerUserId", "`OwnerUserId`(191)");
// Hot-path composite indexes for tenant-scoped list/board/stats/analytics
// (OwnerUserId + IsDeleted) and reminders (OwnerUserId + FollowUpAt).
if (!MySqlIndexExists(conn, "JobApplications", "IX_JobApplications_OwnerUserId_IsDeleted"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE INDEX `IX_JobApplications_OwnerUserId_IsDeleted` ON `JobApplications` (`OwnerUserId`, `IsDeleted`);";
cmd.ExecuteNonQuery();
}
if (!MySqlIndexExists(conn, "JobApplications", "IX_JobApplications_OwnerUserId_FollowUpAt"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE INDEX `IX_JobApplications_OwnerUserId_FollowUpAt` ON `JobApplications` (`OwnerUserId`, `FollowUpAt`);";
cmd.ExecuteNonQuery();
}
if (!MySqlIndexExists(conn, "CvUploadArtifacts", "IX_CvUploadArtifacts_OwnerUserId_UploadedAtUtc"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE INDEX `IX_CvUploadArtifacts_OwnerUserId_UploadedAtUtc` ON `CvUploadArtifacts` (`OwnerUserId`, `UploadedAtUtc`);";
cmd.ExecuteNonQuery();
}
if (!MySqlIndexExists(conn, "CvExtractionRuns", "IX_CvExtractionRuns_OwnerUserId_StartedAtUtc"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE INDEX `IX_CvExtractionRuns_OwnerUserId_StartedAtUtc` ON `CvExtractionRuns` (`OwnerUserId`, `StartedAtUtc`);";
cmd.ExecuteNonQuery();
}
if (!MySqlIndexExists(conn, "CvExtractionRuns", "IX_CvExtractionRuns_ArtifactId"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE INDEX `IX_CvExtractionRuns_ArtifactId` ON `CvExtractionRuns` (`ArtifactId`);";
cmd.ExecuteNonQuery();
}
if (!MySqlIndexExists(conn, "GmailConnections", "IX_GmailConnections_OwnerUserId"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE INDEX `IX_GmailConnections_OwnerUserId` ON `GmailConnections` (`OwnerUserId`);";
cmd.ExecuteNonQuery();
}
if (!MySqlIndexExists(conn, "GmailConnections", "IX_GmailConnections_OwnerUserId_GmailAddress"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE UNIQUE INDEX `IX_GmailConnections_OwnerUserId_GmailAddress` ON `GmailConnections` (`OwnerUserId`, `GmailAddress`);";
cmd.ExecuteNonQuery();
}
if (!MySqlIndexExists(conn, "MicrosoftGraphConnections", "IX_MicrosoftGraphConnections_OwnerUserId"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE INDEX `IX_MicrosoftGraphConnections_OwnerUserId` ON `MicrosoftGraphConnections` (`OwnerUserId`);";
cmd.ExecuteNonQuery();
}
if (!MySqlIndexExists(conn, "MicrosoftGraphConnections", "IX_MicrosoftGraphConnections_OwnerUserId_MailAddress"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE UNIQUE INDEX `IX_MicrosoftGraphConnections_OwnerUserId_MailAddress` ON `MicrosoftGraphConnections` (`OwnerUserId`, `MailAddress`);";
cmd.ExecuteNonQuery();
}
if (!MySqlIndexExists(conn, "ImapConnections", "IX_ImapConnections_OwnerUserId"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE UNIQUE INDEX `IX_ImapConnections_OwnerUserId` ON `ImapConnections` (`OwnerUserId`);";
cmd.ExecuteNonQuery();
}
if (!MySqlIndexExists(conn, "TailoredCvDrafts", "IX_TailoredCvDrafts_OwnerUserId_JobApplicationId"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE UNIQUE INDEX `IX_TailoredCvDrafts_OwnerUserId_JobApplicationId` ON `TailoredCvDrafts` (`OwnerUserId`, `JobApplicationId`);";
cmd.ExecuteNonQuery();
}
if (!MySqlIndexExists(conn, "TailoredCvDrafts", "IX_TailoredCvDrafts_JobApplicationId"))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "CREATE INDEX `IX_TailoredCvDrafts_JobApplicationId` ON `TailoredCvDrafts` (`JobApplicationId`);";
cmd.ExecuteNonQuery();
}
TryCreateIndex("JobApplications", "IX_JobApplications_OwnerUserId_IsDeleted", "`OwnerUserId`(191), `IsDeleted`");
TryCreateIndex("JobApplications", "IX_JobApplications_OwnerUserId_FollowUpAt", "`OwnerUserId`(191), `FollowUpAt`");
// Status is longtext in MySQL (see JobTrackerContext.OnModelCreating), so it
// needs an explicit prefix length to be indexable under MariaDB's key-length rules.
TryCreateIndex("JobApplications", "IX_JobApplications_OwnerUserId_IsDeleted_Status", "`OwnerUserId`(191), `IsDeleted`, `Status`(50)");
TryCreateIndex("Correspondences", "IX_Correspondences_JobApplicationId", "`JobApplicationId`");
TryCreateIndex("JobEvents", "IX_JobEvents_JobApplicationId", "`JobApplicationId`");
TryCreateIndex("CvUploadArtifacts", "IX_CvUploadArtifacts_OwnerUserId_UploadedAtUtc", "`OwnerUserId`(191), `UploadedAtUtc`");
TryCreateIndex("CvExtractionRuns", "IX_CvExtractionRuns_OwnerUserId_StartedAtUtc", "`OwnerUserId`(191), `StartedAtUtc`");
TryCreateIndex("CvExtractionRuns", "IX_CvExtractionRuns_ArtifactId", "`ArtifactId`");
TryCreateIndex("GmailConnections", "IX_GmailConnections_OwnerUserId", "`OwnerUserId`(191)");
TryCreateUniqueIndex("GmailConnections", "IX_GmailConnections_OwnerUserId_GmailAddress", "`OwnerUserId`(191), `GmailAddress`(191)");
TryCreateIndex("MicrosoftGraphConnections", "IX_MicrosoftGraphConnections_OwnerUserId", "`OwnerUserId`(191)");
TryCreateUniqueIndex("MicrosoftGraphConnections", "IX_MicrosoftGraphConnections_OwnerUserId_MailAddress", "`OwnerUserId`(191), `MailAddress`(191)");
TryCreateUniqueIndex("ImapConnections", "IX_ImapConnections_OwnerUserId", "`OwnerUserId`(191)");
TryCreateUniqueIndex("TailoredCvDrafts", "IX_TailoredCvDrafts_OwnerUserId_JobApplicationId", "`OwnerUserId`(191), `JobApplicationId`");
TryCreateIndex("TailoredCvDrafts", "IX_TailoredCvDrafts_JobApplicationId", "`JobApplicationId`");
}
}
+2 -5
View File
@@ -10,7 +10,7 @@ namespace JobTrackerApi.Services;
public interface ITokenService
{
Task<string> CreateAccessTokenAsync(ApplicationUser user, string? sessionId = null, CancellationToken cancellationToken = default);
Task<string> CreateAccessTokenAsync(ApplicationUser user, CancellationToken cancellationToken = default);
}
public sealed class TokenService : ITokenService
@@ -24,7 +24,7 @@ public sealed class TokenService : ITokenService
_users = users;
}
public async Task<string> CreateAccessTokenAsync(ApplicationUser user, string? sessionId = null, CancellationToken cancellationToken = default)
public async Task<string> CreateAccessTokenAsync(ApplicationUser user, CancellationToken cancellationToken = default)
{
var jwtKey = (_cfg["Auth:JwtKey"] ?? "").Trim();
if (string.IsNullOrWhiteSpace(jwtKey))
@@ -57,9 +57,6 @@ public sealed class TokenService : ITokenService
foreach (var r in roles)
claims.Add(new Claim(ClaimTypes.Role, r));
if (!string.IsNullOrWhiteSpace(sessionId))
claims.Add(new Claim("sid", sessionId));
var now = DateTime.UtcNow;
var token = new JwtSecurityToken(
@@ -1,115 +0,0 @@
using System.Security.Cryptography;
using System.Text;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
namespace JobTrackerApi.Services;
// "Trust this device for 30 days" -- lets a 2FA challenge be skipped on the same browser for a
// month. Shared by AuthController (checks the cookie before gating on 2FA) and
// TwoFactorController (issues/lists/revokes the cookie's backing row). Never stores the
// plaintext token, only its SHA-256 hash.
public static class TrustedDeviceService
{
private static readonly TimeSpan Lifetime = TimeSpan.FromDays(30);
// Only returns true (and thus skips 2FA) when the cookie's hash matches a non-expired row
// for THIS SPECIFIC user -- UserId is part of the DB query itself, not a check applied
// after the fact, so a trusted-device cookie minted for user A can never skip 2FA for user
// B even if somehow presented on their request.
public static async Task<bool> IsDeviceTrustedAsync(JobTrackerContext db, HttpRequest request, string userId, CancellationToken cancellationToken)
{
var token = request.Cookies[AuthSessionOptions.TrustedDeviceCookieName];
if (string.IsNullOrWhiteSpace(token)) return false;
var hash = HashToken(token);
var now = DateTimeOffset.UtcNow;
// SQLite/Pomelo cannot translate DateTimeOffset relational comparisons (>) to SQL, so the
// expiry check has to happen after materializing the row -- fine here since the equality
// filters (UserId, TokenHash) already narrow this to at most one row.
var match = await db.TrustedDevices
.IgnoreQueryFilters()
.FirstOrDefaultAsync(x => x.UserId == userId && x.TokenHash == hash, cancellationToken);
if (match is null || match.ExpiresAtUtc <= now) return false;
match.LastSeenAtUtc = now;
await db.SaveChangesAsync(cancellationToken);
return true;
}
public static async Task IssueAsync(JobTrackerContext db, HttpRequest request, HttpResponse response, string userId, CancellationToken cancellationToken)
{
var token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
var now = DateTimeOffset.UtcNow;
db.TrustedDevices.Add(new TrustedDevice
{
UserId = userId,
TokenHash = HashToken(token),
DeviceLabel = DescribeUserAgent(request.Headers["User-Agent"].ToString()),
CreatedAtUtc = now,
LastSeenAtUtc = now,
ExpiresAtUtc = now.Add(Lifetime),
});
await db.SaveChangesAsync(cancellationToken);
var secure = request.IsHttps || string.Equals(request.Headers["X-Forwarded-Proto"], "https", StringComparison.OrdinalIgnoreCase);
response.Cookies.Append(AuthSessionOptions.TrustedDeviceCookieName, token, AuthSessionOptions.BuildTrustedDeviceCookie(secure));
}
public static void ClearCookie(HttpRequest request, HttpResponse response)
{
var secure = request.IsHttps || string.Equals(request.Headers["X-Forwarded-Proto"], "https", StringComparison.OrdinalIgnoreCase);
response.Cookies.Delete(AuthSessionOptions.TrustedDeviceCookieName, AuthSessionOptions.BuildExpiredTrustedDeviceCookie(secure));
}
// Used to flag "this device" in the trusted-devices list without ever sending a token or
// hash to the client -- just a boolean per row.
public static string? CurrentDeviceTokenHash(HttpRequest request)
{
var token = request.Cookies[AuthSessionOptions.TrustedDeviceCookieName];
return string.IsNullOrWhiteSpace(token) ? null : HashToken(token);
}
public static string HashToken(string token)
{
return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token.Trim()))).ToLowerInvariant();
}
private static readonly (string Needle, string Label)[] BrowserMarkers =
{
("Edg/", "Edge"),
("OPR/", "Opera"),
("Chrome/", "Chrome"),
("Firefox/", "Firefox"),
("Safari/", "Safari"),
};
private static readonly (string Needle, string Label)[] OsMarkers =
{
("Windows", "Windows"),
("Mac OS X", "Mac"),
("iPhone", "iOS"),
("iPad", "iOS"),
("Android", "Android"),
("Linux", "Linux"),
};
// ponytail: substring sniffing, not a real UA parser -- this only feeds a display label in
// a security-settings list ("Chrome on Windows"), nothing security-relevant depends on it.
// Public: also reused by AppSessionIssuer for UserSession device labels.
public static string? DescribeUserAgent(string? userAgent)
{
if (string.IsNullOrWhiteSpace(userAgent)) return null;
var browser = BrowserMarkers.FirstOrDefault(m => userAgent.Contains(m.Needle, StringComparison.Ordinal)).Label;
var os = OsMarkers.FirstOrDefault(m => userAgent.Contains(m.Needle, StringComparison.Ordinal)).Label;
if (browser is null && os is null) return userAgent.Length > 80 ? userAgent[..80] : userAgent;
if (browser is null) return os;
if (os is null) return browser;
return $"{browser} on {os}";
}
}
@@ -1,47 +0,0 @@
using System.Security.Cryptography;
using Microsoft.Extensions.Caching.Memory;
namespace JobTrackerApi.Services;
public sealed record PendingTwoFactorSession(string UserId, bool RememberMe);
public interface ITwoFactorPendingTokenService
{
string IssuePendingToken(string userId, bool rememberMe);
PendingTwoFactorSession? Resolve(string pendingToken, bool consume);
}
// ponytail: server-side opaque token in IMemoryCache, deliberately NOT a JWT. A JWT signed
// with the app's normal signing key would be accepted by the "local" JWT bearer auth scheme
// for every other endpoint unless its issuer/audience/claims were carefully kept out of that
// scheme's validation -- an opaque cache-backed token can never be presented as a bearer
// token, so it structurally cannot grant a real session by itself. Single instance is fine:
// this is a short-lived (5 min), single-process dev/prod deployment, same as the rest of this
// app's in-memory state (rate limiter, IMemoryCache already registered in Program.cs).
public sealed class TwoFactorPendingTokenService : ITwoFactorPendingTokenService
{
private static readonly TimeSpan Ttl = TimeSpan.FromMinutes(5);
private readonly IMemoryCache _cache;
public TwoFactorPendingTokenService(IMemoryCache cache)
{
_cache = cache;
}
public string IssuePendingToken(string userId, bool rememberMe)
{
var token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
_cache.Set(CacheKey(token), new PendingTwoFactorSession(userId, rememberMe), Ttl);
return token;
}
public PendingTwoFactorSession? Resolve(string pendingToken, bool consume)
{
var key = CacheKey(pendingToken);
if (!_cache.TryGetValue(key, out PendingTwoFactorSession? session)) return null;
if (consume) _cache.Remove(key);
return session;
}
private static string CacheKey(string token) => $"2fa-pending:{token}";
}
@@ -20,7 +20,6 @@
"Auth": {
"Require": true,
"AllowRegistration": true,
"RequireEmailVerification": false,
"JwtKey": "CHANGE_ME_DEV_ONLY_LONG_RANDOM_SECRET",
"JwtIssuer": "JobTrackerApi",
"JwtAudience": "job-tracker-ui",
@@ -27,8 +27,6 @@
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.14" />
<PackageReference Include="Otp.NET" Version="1.4.1" />
<PackageReference Include="QRCoder" Version="1.8.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.14.0" />
<PackageReference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="8.14.0" />
<PackageReference Include="MailKit" Version="4.17.0" />
-3
View File
@@ -19,7 +19,4 @@ public sealed class ApplicationUser : IdentityUser
public string? MicrosoftSubject { get; set; }
public string? MicrosoftEmail { get; set; }
public DateTimeOffset? MicrosoftLinkedAt { get; set; }
public string? TotpSecretEncrypted { get; set; }
public string? TotpPendingSecretEncrypted { get; set; }
public DateTimeOffset? TotpEnabledAtUtc { get; set; }
}
-16
View File
@@ -1,16 +0,0 @@
namespace JobTrackerApi.Models;
// "Trust this device for 30 days" -- lets a browser skip the 2FA code step after one successful
// challenge. Never store the plaintext token, only its SHA-256 hash, same rationale as
// TwoFactorRecoveryCode.CodeHash: a DB read (backup, replica, leaked snapshot) can't be turned
// into a working cookie.
public sealed class TrustedDevice
{
public int Id { get; set; }
public string UserId { get; set; } = "";
public string TokenHash { get; set; } = "";
public string? DeviceLabel { get; set; }
public DateTimeOffset CreatedAtUtc { get; set; }
public DateTimeOffset LastSeenAtUtc { get; set; }
public DateTimeOffset ExpiresAtUtc { get; set; }
}
-12
View File
@@ -1,12 +0,0 @@
namespace JobTrackerApi.Models;
// One-time-use 2FA recovery codes. Plaintext is shown once at generation time and never
// persisted -- only the SHA-256 hash is stored so a DB read can't recover usable codes.
public sealed class TwoFactorRecoveryCode
{
public int Id { get; set; }
public string UserId { get; set; } = "";
public string CodeHash { get; set; } = "";
public DateTimeOffset CreatedAtUtc { get; set; }
public DateTimeOffset? UsedAtUtc { get; set; }
}
-17
View File
@@ -1,17 +0,0 @@
namespace JobTrackerApi.Models;
// Server-side record of a JWT issued via AppSessionIssuer. The JWT carries this row's Id as its
// "sid" claim; Program.cs's "local" JwtBearer OnTokenValidated looks the row up on every request
// so a session can actually be revoked before its JWT naturally expires (previously the JWT alone
// was the credential -- see AppSessionIssuer). Same shape/rationale as TrustedDevice, but this
// tracks the *session* itself rather than a "skip 2FA" cookie.
public sealed class UserSession
{
public string Id { get; set; } = "";
public string UserId { get; set; } = "";
public string? DeviceLabel { get; set; }
public DateTimeOffset CreatedAtUtc { get; set; }
public DateTimeOffset LastSeenAtUtc { get; set; }
public DateTimeOffset ExpiresAtUtc { get; set; }
public DateTimeOffset? RevokedAtUtc { get; set; }
}
-2
View File
@@ -31,7 +31,6 @@ import LoginPage from "./views/LoginPage";
import LandingPage from "./views/LandingPage";
import ForgotPasswordPage from "./views/ForgotPasswordPage";
import ResetPasswordPage from "./views/ResetPasswordPage";
import VerifyEmailPage from "./views/VerifyEmailPage";
import RouteErrorPage from "./views/RouteErrorPage";
import { api } from "./api";
import { resolveCaptureUrl } from "./captureUrl";
@@ -367,7 +366,6 @@ export default function App() {
{ path: "/login", element: <LoginPage />, errorElement: <RouteErrorPage /> },
{ path: "/forgot-password", element: <ForgotPasswordPage />, errorElement: <RouteErrorPage /> },
{ path: "/reset-password", element: <ResetPasswordPage />, errorElement: <RouteErrorPage /> },
{ path: "/verify-email", element: <VerifyEmailPage />, errorElement: <RouteErrorPage /> },
{ path: "/*", element: <Shell jobPageSize={jobPageSize} setJobPageSize={setJobPageSize} jobColumns={jobColumns} setJobColumns={setJobColumns} themeMode={themeMode} onThemeModeChange={onThemeModeChange} />, errorElement: <RouteErrorPage /> },
], { future: { v7_relativeSplatPath: true } }), [jobColumns, jobPageSize, themeMode]);
@@ -4,7 +4,6 @@ import { Box, Button, Chip, Paper, Typography } from "@mui/material";
import { api, getApiErrorMessage } from "../api";
import { clearAuthClientState, getAuthPersistencePreference } from "../auth";
import TwoFactorChallenge from "./TwoFactorChallenge";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";
@@ -53,7 +52,6 @@ export default function GoogleAuthCard({ onSignedIn }: { onSignedIn?: () => void
const [me, setMe] = useState<MeResponse | null>(null);
const [working, setWorking] = useState(false);
const [allowRegistration, setAllowRegistration] = useState(false);
const [pendingToken, setPendingToken] = useState<string | null>(null);
const hostRef = useRef<HTMLDivElement | null>(null);
const clientId = (process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID || "").trim();
@@ -111,14 +109,10 @@ export default function GoogleAuthCard({ onSignedIn }: { onSignedIn?: () => void
toast(res.data?.email ? t("googleLinkedSuccessWithEmail", { email: res.data.email }) : t("googleLinkedSuccess"), "success");
await refreshMe();
} else {
const res = await api.post<{ requiresTwoFactor?: boolean; pendingToken?: string }>("/auth/google/exchange", { token: credential, rememberMe: getAuthPersistencePreference() === "local" });
if (res.data?.requiresTwoFactor && res.data.pendingToken) {
setPendingToken(res.data.pendingToken);
} else {
window.dispatchEvent(new Event("auth-changed"));
toast(t("googleSignedIn"), "success");
onSignedIn?.();
}
await api.post("/auth/google/exchange", { token: credential, rememberMe: getAuthPersistencePreference() === "local" });
window.dispatchEvent(new Event("auth-changed"));
toast(t("googleSignedIn"), "success");
onSignedIn?.();
}
} catch (e: any) {
toast(getApiErrorMessage(e, t("googleAuthFailed")), "error");
@@ -157,20 +151,7 @@ export default function GoogleAuthCard({ onSignedIn }: { onSignedIn?: () => void
</Typography>
)}
{clientId && pendingToken && (
<TwoFactorChallenge
pendingToken={pendingToken}
onCancel={() => setPendingToken(null)}
onSuccess={() => {
setPendingToken(null);
window.dispatchEvent(new Event("auth-changed"));
toast(t("googleSignedIn"), "success");
onSignedIn?.();
}}
/>
)}
{clientId && !pendingToken && (
{clientId && (
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.25 }}>
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
<Chip size="small" label={me?.googleLink?.linked ? t("googleLinked") : t("googleAvailableToLink")} color={me?.googleLink?.linked ? "success" : "default"} variant={me?.googleLink?.linked ? "filled" : "outlined"} />
@@ -5,7 +5,6 @@ import { PublicClientApplication } from "@azure/msal-browser";
import { api, getApiErrorMessage } from "../api";
import { clearAuthClientState, getAuthPersistencePreference } from "../auth";
import TwoFactorChallenge from "./TwoFactorChallenge";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";
@@ -36,7 +35,6 @@ export default function MicrosoftAuthCard({ onSignedIn }: { onSignedIn?: () => v
const { t } = useI18n();
const [me, setMe] = useState<MeResponse | null>(null);
const [working, setWorking] = useState(false);
const [pendingToken, setPendingToken] = useState<string | null>(null);
const clientId = (process.env.REACT_APP_MICROSOFT_CLIENT_ID || "").trim();
const signedIn = Boolean(me?.provider);
@@ -80,14 +78,10 @@ export default function MicrosoftAuthCard({ onSignedIn }: { onSignedIn?: () => v
toast(res.data?.email ? t("microsoftLinkedSuccessWithEmail", { email: res.data.email }) : t("microsoftLinkedSuccess"), "success");
await refreshMe();
} else {
const res = await api.post<{ requiresTwoFactor?: boolean; pendingToken?: string }>("/auth/microsoft/exchange", { token: idToken, rememberMe: getAuthPersistencePreference() === "local" });
if (res.data?.requiresTwoFactor && res.data.pendingToken) {
setPendingToken(res.data.pendingToken);
} else {
window.dispatchEvent(new Event("auth-changed"));
toast(t("microsoftSignedIn"), "success");
onSignedIn?.();
}
await api.post("/auth/microsoft/exchange", { token: idToken, rememberMe: getAuthPersistencePreference() === "local" });
window.dispatchEvent(new Event("auth-changed"));
toast(t("microsoftSignedIn"), "success");
onSignedIn?.();
}
} catch (e: any) {
toast(getApiErrorMessage(e, t("microsoftAuthFailed")), "error");
@@ -110,20 +104,7 @@ export default function MicrosoftAuthCard({ onSignedIn }: { onSignedIn?: () => v
</Typography>
)}
{clientId && pendingToken && (
<TwoFactorChallenge
pendingToken={pendingToken}
onCancel={() => setPendingToken(null)}
onSuccess={() => {
setPendingToken(null);
window.dispatchEvent(new Event("auth-changed"));
toast(t("microsoftSignedIn"), "success");
onSignedIn?.();
}}
/>
)}
{clientId && !pendingToken && (
{clientId && (
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.25 }}>
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
<Chip size="small" label={me?.microsoftLink?.linked ? t("microsoftLinked") : t("microsoftAvailableToLink")} color={me?.microsoftLink?.linked ? "success" : "default"} variant={me?.microsoftLink?.linked ? "filled" : "outlined"} />
@@ -1,148 +0,0 @@
import React, { useEffect, useState } from "react";
import {
Alert,
Box,
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
IconButton,
List,
ListItem,
ListItemSecondaryAction,
ListItemText,
Paper,
Typography,
} from "@mui/material";
import DeleteIcon from "@mui/icons-material/Delete";
import { api, getApiErrorMessage } from "../api";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";
import { clearAuthClientState } from "../auth";
type Session = {
id: string;
deviceLabel: string | null;
createdAtUtc: string;
lastSeenAtUtc: string;
expiresAtUtc: string;
isCurrentSession: boolean;
};
function apiErrorMessage(e: any, t: (k: any) => string) {
return getApiErrorMessage(e, t("twoFactorGenericError"));
}
export default function SessionsSettingsCard() {
const { toast } = useToast();
const { t } = useI18n();
const [sessions, setSessions] = useState<Session[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [confirmRevokeOthers, setConfirmRevokeOthers] = useState(false);
const loadSessions = () => {
setLoading(true);
setError(null);
api
.get<Session[]>("/auth/sessions")
.then((r) => setSessions(r.data))
.catch((e) => setError(apiErrorMessage(e, t)))
.finally(() => setLoading(false));
};
useEffect(() => { loadSessions(); }, []);
async function revokeSession(id: string, isCurrentSession: boolean) {
try {
await api.delete(`/auth/sessions/${id}`);
if (isCurrentSession) {
// Same pattern as AuthStatusCard's sign-out: clearing local auth state emits
// "auth-changed", which App.tsx's listener picks up to refetch /auth/me (now 401,
// since the server already deleted the session cookie) and redirect to /login.
clearAuthClientState();
return;
}
toast(t("sessionsRevoked"), "success");
loadSessions();
} catch (e: any) {
setError(apiErrorMessage(e, t));
}
}
async function revokeOthers() {
try {
await api.post("/auth/sessions/revoke-others");
toast(t("sessionsRevokedOthers"), "success");
setConfirmRevokeOthers(false);
loadSessions();
} catch (e: any) {
setError(apiErrorMessage(e, t));
}
}
return (
<Paper sx={{ mt: 2, p: 2 }}>
<Typography variant="h6" sx={{ mb: 1 }}>
{t("sessionsSectionTitle")}
</Typography>
{error ? <Alert severity="error" role="alert" sx={{ mb: 1 }}>{error}</Alert> : null}
{!loading && sessions.length === 0 && !error ? (
<Typography sx={{ color: "text.secondary", mb: 1 }}>{t("sessionsEmpty")}</Typography>
) : null}
{sessions.length > 0 ? (
<List dense disablePadding>
{sessions.map((s) => (
<ListItem key={s.id} divider>
<ListItemText
primary={
<>
{s.deviceLabel || t("sessionsUnknownDevice")}
{s.isCurrentSession ? (
<Typography component="span" variant="caption" sx={{ ml: 1, color: "primary.main", fontWeight: 700 }}>
{t("sessionsCurrentDevice")}
</Typography>
) : null}
</>
}
secondary={t("sessionsMeta", {
lastSeen: new Date(s.lastSeenAtUtc).toLocaleString(),
expires: new Date(s.expiresAtUtc).toLocaleDateString(),
})}
/>
<ListItemSecondaryAction>
<IconButton edge="end" aria-label={t("sessionsRevoke")} onClick={() => revokeSession(s.id, s.isCurrentSession)}>
<DeleteIcon fontSize="small" />
</IconButton>
</ListItemSecondaryAction>
</ListItem>
))}
</List>
) : null}
{sessions.length > 1 ? (
<Button variant="text" color="warning" size="small" sx={{ mt: 1 }} onClick={() => setConfirmRevokeOthers(true)}>
{t("sessionsRevokeOthers")}
</Button>
) : null}
<Dialog open={confirmRevokeOthers} onClose={() => setConfirmRevokeOthers(false)} maxWidth="sm" fullWidth>
<DialogTitle>{t("sessionsRevokeOthersConfirmTitle")}</DialogTitle>
<DialogContent>
<Typography>{t("sessionsRevokeOthersConfirmBody")}</Typography>
</DialogContent>
<DialogActions>
<Button type="button" onClick={() => setConfirmRevokeOthers(false)}>{t("cancel")}</Button>
<Button variant="contained" color="warning" onClick={revokeOthers}>
{t("sessionsRevokeOthers")}
</Button>
</DialogActions>
</Dialog>
</Paper>
);
}
@@ -1,83 +0,0 @@
import React, { useState } from "react";
import { Alert, Box, Button, Checkbox, FormControlLabel, TextField, Typography } from "@mui/material";
import { api, getApiErrorMessage } from "../api";
import { useI18n } from "../i18n/I18nProvider";
type ChallengeResponse = { authenticated: true; provider: "local" };
export default function TwoFactorChallenge({
pendingToken,
onSuccess,
onCancel,
}: {
pendingToken: string;
onSuccess: (data: ChallengeResponse) => void;
onCancel: () => void;
}) {
const { t } = useI18n();
const [code, setCode] = useState("");
const [trustDevice, setTrustDevice] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
async function submit() {
setLoading(true);
setError(null);
try {
const res = await api.post<ChallengeResponse>("/auth/2fa/challenge", { pendingToken, code, trustDevice });
onSuccess(res.data);
} catch (e: any) {
if (e?.response?.status === 429) {
setError(t("twoFactorRateLimited"));
} else {
setError(getApiErrorMessage(e, t("twoFactorInvalidCode")));
}
} finally {
setLoading(false);
}
}
return (
<Box
component="form"
onSubmit={(e) => { e.preventDefault(); void submit(); }}
sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}
role="group"
aria-label={t("twoFactorTitle")}
>
<Typography variant="subtitle1" sx={{ fontWeight: 800 }}>
{t("twoFactorTitle")}
</Typography>
<Typography variant="body2" sx={{ color: "text.secondary" }}>
{t("twoFactorHint")}
</Typography>
{error ? <Alert severity="error" role="alert">{error}</Alert> : null}
<TextField
label={t("twoFactorCodeLabel")}
value={code}
onChange={(e) => setCode(e.target.value)}
autoComplete="one-time-code"
autoFocus
fullWidth
/>
<FormControlLabel
control={<Checkbox checked={trustDevice} onChange={(e) => setTrustDevice(e.target.checked)} />}
label={t("twoFactorTrustDevice")}
/>
<Box sx={{ display: "flex", gap: 1, justifyContent: "flex-end" }}>
<Button type="button" variant="text" disabled={loading} onClick={onCancel}>
{t("twoFactorBack")}
</Button>
<Button type="submit" variant="contained" disabled={loading || !code.trim()}>
{loading ? t("twoFactorVerifying") : t("twoFactorVerify")}
</Button>
</Box>
</Box>
);
}
@@ -1,390 +0,0 @@
import React, { useEffect, useState } from "react";
import {
Alert,
Box,
Button,
Checkbox,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
Divider,
FormControlLabel,
IconButton,
List,
ListItem,
ListItemSecondaryAction,
ListItemText,
Paper,
TextField,
Typography,
} from "@mui/material";
import DeleteIcon from "@mui/icons-material/Delete";
import { api, getApiErrorMessage } from "../api";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";
type Status = { enabled: boolean; enabledAtUtc: string | null };
type SetupResponse = { manualEntryKey: string; qrCodeDataUrl: string };
type RecoveryCodesResponse = { recoveryCodes: string[] };
type TrustedDevice = {
id: number;
deviceLabel: string | null;
createdAtUtc: string;
lastSeenAtUtc: string;
expiresAtUtc: string;
isCurrentDevice: boolean;
};
type Flow =
| "closed"
| "enable-password"
| "enable-qr"
| "enable-recovery"
| "disable-password"
| "regenerate-password"
| "regenerate-recovery"
| "revoke-all-confirm";
function apiErrorMessage(e: any, t: (k: any) => string) {
if (e?.response?.status === 429) return t("twoFactorRateLimited");
return getApiErrorMessage(e, t("twoFactorGenericError"));
}
export default function TwoFactorSettingsCard() {
const { toast } = useToast();
const { t } = useI18n();
const [status, setStatus] = useState<Status | null>(null);
const [flow, setFlow] = useState<Flow>("closed");
const [password, setPassword] = useState("");
const [code, setCode] = useState("");
const [setup, setSetup] = useState<SetupResponse | null>(null);
const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
const [savedConfirmed, setSavedConfirmed] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [devices, setDevices] = useState<TrustedDevice[]>([]);
const [devicesLoading, setDevicesLoading] = useState(false);
const [devicesError, setDevicesError] = useState<string | null>(null);
const loadStatus = () => {
api.get<Status>("/auth/2fa/status").then((r) => setStatus(r.data)).catch(() => setStatus(null));
};
const loadDevices = () => {
setDevicesLoading(true);
setDevicesError(null);
api
.get<TrustedDevice[]>("/auth/2fa/trusted-devices")
.then((r) => setDevices(r.data))
.catch((e) => setDevicesError(apiErrorMessage(e, t)))
.finally(() => setDevicesLoading(false));
};
useEffect(() => { loadStatus(); loadDevices(); }, []);
async function revokeDevice(id: number) {
try {
await api.delete(`/auth/2fa/trusted-devices/${id}`);
loadDevices();
} catch (e: any) {
setDevicesError(apiErrorMessage(e, t));
}
}
async function revokeAllDevices() {
try {
await api.post("/auth/2fa/trusted-devices/revoke-all");
toast(t("twoFactorTrustedDevicesRevokedAll"), "success");
closeFlow();
loadDevices();
} catch (e: any) {
setError(apiErrorMessage(e, t));
}
}
function closeFlow() {
setFlow("closed");
setPassword("");
setCode("");
setSetup(null);
setRecoveryCodes([]);
setSavedConfirmed(false);
setError(null);
}
async function submitPassword() {
setLoading(true);
setError(null);
try {
if (flow === "enable-password") {
const res = await api.post<SetupResponse>("/auth/2fa/setup", { currentPassword: password });
setSetup(res.data);
setPassword("");
setFlow("enable-qr");
} else if (flow === "disable-password") {
await api.post("/auth/2fa/disable", { currentPassword: password });
toast(t("twoFactorDisabledSuccess"), "success");
closeFlow();
loadStatus();
} else if (flow === "regenerate-password") {
const res = await api.post<RecoveryCodesResponse>("/auth/2fa/recovery-codes/regenerate", { currentPassword: password });
setRecoveryCodes(res.data.recoveryCodes);
setPassword("");
setFlow("regenerate-recovery");
}
} catch (e: any) {
setError(e?.response?.status === 400 || e?.response?.status === 401 ? t("twoFactorWrongPassword") : apiErrorMessage(e, t));
} finally {
setLoading(false);
}
}
async function submitCode() {
setLoading(true);
setError(null);
try {
const res = await api.post<RecoveryCodesResponse>("/auth/2fa/verify-setup", { code });
setRecoveryCodes(res.data.recoveryCodes);
setCode("");
setFlow("enable-recovery");
} catch (e: any) {
setError(e?.response?.status === 401 ? t("twoFactorInvalidCode") : apiErrorMessage(e, t));
} finally {
setLoading(false);
}
}
function finishRecovery() {
toast(flow === "enable-recovery" ? t("twoFactorEnabledSuccess") : t("twoFactorRegenerateSuccess"), "success");
closeFlow();
loadStatus();
}
function copyRecoveryCodes() {
void navigator.clipboard.writeText(recoveryCodes.join("\n"));
toast(t("twoFactorCodesCopied"), "info");
}
function downloadRecoveryCodes() {
const blob = new Blob([recoveryCodes.join("\n") + "\n"], { type: "text/plain" });
const url = window.URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "jobbjakt-recovery-codes.txt";
document.body.appendChild(link);
link.click();
link.remove();
window.URL.revokeObjectURL(url);
}
const isPasswordStep = flow === "enable-password" || flow === "disable-password" || flow === "regenerate-password";
const isRecoveryStep = flow === "enable-recovery" || flow === "regenerate-recovery";
return (
<Paper sx={{ mt: 2, p: 2 }}>
<Typography variant="h6" sx={{ mb: 1 }}>
{t("twoFactorSectionTitle")}
</Typography>
{status ? (
<Typography sx={{ color: "text.secondary", mb: 1.5 }}>
{status.enabled
? t("twoFactorStatusEnabled", { date: status.enabledAtUtc ? new Date(status.enabledAtUtc).toLocaleDateString() : "" })
: t("twoFactorStatusDisabled")}
</Typography>
) : null}
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
{!status?.enabled ? (
<Button variant="contained" onClick={() => setFlow("enable-password")}>
{t("twoFactorEnableButton")}
</Button>
) : (
<>
<Button variant="outlined" color="warning" onClick={() => setFlow("disable-password")}>
{t("twoFactorDisableButton")}
</Button>
<Button variant="outlined" onClick={() => setFlow("regenerate-password")}>
{t("twoFactorRegenerateButton")}
</Button>
</>
)}
</Box>
{status?.enabled ? (
<Box sx={{ mt: 2 }}>
<Divider sx={{ mb: 1.5 }} />
<Typography variant="subtitle1" sx={{ fontWeight: 700, mb: 0.5 }}>
{t("twoFactorTrustedDevicesTitle")}
</Typography>
{devicesError ? <Alert severity="error" role="alert" sx={{ mb: 1 }}>{devicesError}</Alert> : null}
{!devicesLoading && devices.length === 0 && !devicesError ? (
<Typography sx={{ color: "text.secondary", mb: 1 }}>{t("twoFactorTrustedDevicesEmpty")}</Typography>
) : null}
{devices.length > 0 ? (
<List dense disablePadding>
{devices.map((d) => (
<ListItem key={d.id} divider>
<ListItemText
primary={
<>
{d.deviceLabel || t("twoFactorTrustedDeviceUnknown")}
{d.isCurrentDevice ? (
<Typography component="span" variant="caption" sx={{ ml: 1, color: "primary.main", fontWeight: 700 }}>
{t("twoFactorTrustedDeviceCurrent")}
</Typography>
) : null}
</>
}
secondary={t("twoFactorTrustedDeviceMeta", {
lastSeen: new Date(d.lastSeenAtUtc).toLocaleDateString(),
expires: new Date(d.expiresAtUtc).toLocaleDateString(),
})}
/>
<ListItemSecondaryAction>
<IconButton edge="end" aria-label={t("twoFactorRevokeDevice")} onClick={() => revokeDevice(d.id)}>
<DeleteIcon fontSize="small" />
</IconButton>
</ListItemSecondaryAction>
</ListItem>
))}
</List>
) : null}
{devices.length > 0 ? (
<Button variant="text" color="warning" size="small" sx={{ mt: 1 }} onClick={() => setFlow("revoke-all-confirm")}>
{t("twoFactorRevokeAllDevices")}
</Button>
) : null}
</Box>
) : null}
<Dialog open={flow !== "closed"} onClose={isRecoveryStep ? undefined : closeFlow} maxWidth="sm" fullWidth>
{isPasswordStep && (
<Box component="form" onSubmit={(e) => { e.preventDefault(); void submitPassword(); }}>
<DialogTitle>{t("twoFactorPasswordPrompt")}</DialogTitle>
<DialogContent>
{flow === "disable-password" ? <Alert severity="warning" sx={{ mb: 2 }}>{t("twoFactorDisableWarning")}</Alert> : null}
{flow === "regenerate-password" ? <Alert severity="warning" sx={{ mb: 2 }}>{t("twoFactorRegenerateWarning")}</Alert> : null}
{error ? <Alert severity="error" role="alert" sx={{ mb: 2 }}>{error}</Alert> : null}
<TextField
label={t("twoFactorPasswordLabel")}
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
autoComplete="current-password"
autoFocus
fullWidth
/>
</DialogContent>
<DialogActions>
<Button type="button" onClick={closeFlow} disabled={loading}>{t("cancel")}</Button>
<Button type="submit" variant="contained" disabled={loading || !password}>
{t("twoFactorContinue")}
</Button>
</DialogActions>
</Box>
)}
{flow === "enable-qr" && setup && (
<Box component="form" onSubmit={(e) => { e.preventDefault(); void submitCode(); }}>
<DialogTitle>{t("twoFactorSetupTitle")}</DialogTitle>
<DialogContent>
<Typography variant="body2" sx={{ color: "text.secondary", mb: 2 }}>
{t("twoFactorSetupHint")}
</Typography>
<Box sx={{ display: "flex", justifyContent: "center", mb: 2 }}>
<img src={setup.qrCodeDataUrl} alt={t("twoFactorSetupTitle")} width={200} height={200} />
</Box>
<TextField
label={t("twoFactorManualKeyLabel")}
value={setup.manualEntryKey}
fullWidth
sx={{ mb: 1 }}
InputProps={{
readOnly: true,
endAdornment: (
<Button
size="small"
onClick={() => {
void navigator.clipboard.writeText(setup.manualEntryKey);
toast(t("twoFactorKeyCopied"), "info");
}}
>
{t("twoFactorCopyKey")}
</Button>
),
}}
/>
<Typography variant="body2" sx={{ color: "text.secondary", mt: 2, mb: 1 }}>
{t("twoFactorConfirmCodeHint")}
</Typography>
{error ? <Alert severity="error" role="alert" sx={{ mb: 2 }}>{error}</Alert> : null}
<TextField
label={t("twoFactorConfirmCodeLabel")}
value={code}
onChange={(e) => setCode(e.target.value)}
autoComplete="one-time-code"
fullWidth
/>
</DialogContent>
<DialogActions>
<Button type="button" onClick={closeFlow} disabled={loading}>{t("cancel")}</Button>
<Button type="submit" variant="contained" disabled={loading || !code.trim()}>
{t("twoFactorConfirmButton")}
</Button>
</DialogActions>
</Box>
)}
{isRecoveryStep && (
<>
<DialogTitle role="alert">{t("twoFactorRecoveryTitle")}</DialogTitle>
<DialogContent>
<Alert severity="warning" sx={{ mb: 2 }}>{t("twoFactorRecoveryHint")}</Alert>
<Box
component="ul"
sx={{ fontFamily: "monospace", fontSize: 16, p: 1.5, borderRadius: 2, backgroundColor: "background.default", border: "1px solid", borderColor: "divider", listStyle: "none", m: 0, mb: 2 }}
>
{recoveryCodes.map((rc) => (
<li key={rc}>{rc}</li>
))}
</Box>
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap", mb: 2 }}>
<Button variant="outlined" onClick={copyRecoveryCodes}>{t("twoFactorCopyAll")}</Button>
<Button variant="outlined" onClick={downloadRecoveryCodes}>{t("twoFactorDownload")}</Button>
</Box>
<FormControlLabel
control={<Checkbox checked={savedConfirmed} onChange={(e) => setSavedConfirmed(e.target.checked)} />}
label={t("twoFactorSavedConfirm")}
/>
</DialogContent>
<DialogActions>
<Button variant="contained" disabled={!savedConfirmed} onClick={finishRecovery}>
{t("twoFactorDone")}
</Button>
</DialogActions>
</>
)}
{flow === "revoke-all-confirm" && (
<>
<DialogTitle>{t("twoFactorRevokeAllConfirmTitle")}</DialogTitle>
<DialogContent>
{error ? <Alert severity="error" role="alert" sx={{ mb: 2 }}>{error}</Alert> : null}
<Typography>{t("twoFactorRevokeAllConfirmBody")}</Typography>
</DialogContent>
<DialogActions>
<Button type="button" onClick={closeFlow}>{t("cancel")}</Button>
<Button variant="contained" color="warning" onClick={revokeAllDevices}>
{t("twoFactorRevokeAllDevices")}
</Button>
</DialogActions>
</>
)}
</Dialog>
</Paper>
);
}
-140
View File
@@ -306,67 +306,6 @@ export const translations = {
profileUpdatePassword: "Update password",
profilePasswordUpdated: "Password updated.",
profilePasswordUpdateFailed: "Failed to change password.",
twoFactorTitle: "Two-factor verification",
twoFactorHint: "Enter the 6-digit code from your authenticator app, or a recovery code.",
twoFactorCodeLabel: "Code",
twoFactorVerify: "Verify",
twoFactorVerifying: "Verifying...",
twoFactorBack: "Back",
twoFactorInvalidCode: "Invalid code. Please try again.",
twoFactorRateLimited: "Too many attempts. Please wait a few minutes and try again.",
twoFactorGenericError: "Something went wrong. Please try again.",
twoFactorSectionTitle: "Two-factor authentication",
twoFactorStatusEnabled: "Enabled since {date}",
twoFactorStatusDisabled: "Not enabled",
twoFactorEnableButton: "Enable 2FA",
twoFactorDisableButton: "Disable 2FA",
twoFactorRegenerateButton: "Regenerate recovery codes",
twoFactorPasswordPrompt: "Confirm your password to continue",
twoFactorPasswordLabel: "Current password",
twoFactorContinue: "Continue",
twoFactorWrongPassword: "Incorrect password.",
twoFactorSetupTitle: "Scan this QR code",
twoFactorSetupHint: "Scan with your authenticator app, or enter the key manually.",
twoFactorManualKeyLabel: "Manual entry key",
twoFactorCopyKey: "Copy key",
twoFactorKeyCopied: "Key copied to clipboard.",
twoFactorConfirmCodeLabel: "6-digit code",
twoFactorConfirmCodeHint: "Enter the code shown by your authenticator app to confirm setup.",
twoFactorConfirmButton: "Confirm",
twoFactorRecoveryTitle: "Save your recovery codes",
twoFactorRecoveryHint: "Each code can be used once if you lose access to your authenticator app. This is the only time these codes will be shown.",
twoFactorCopyAll: "Copy all codes",
twoFactorCodesCopied: "Recovery codes copied.",
twoFactorDownload: "Download as .txt",
twoFactorSavedConfirm: "I've saved my recovery codes",
twoFactorDone: "Done",
twoFactorDisableWarning: "Disabling 2FA will also invalidate your recovery codes.",
twoFactorRegenerateWarning: "This will invalidate your existing recovery codes.",
twoFactorEnabledSuccess: "Two-factor authentication enabled.",
twoFactorDisabledSuccess: "Two-factor authentication disabled.",
twoFactorRegenerateSuccess: "Recovery codes regenerated.",
twoFactorTrustDevice: "Trust this device for 30 days",
twoFactorTrustedDevicesTitle: "Trusted devices",
twoFactorTrustedDevicesEmpty: "No trusted devices yet.",
twoFactorTrustedDeviceUnknown: "Unknown device",
twoFactorTrustedDeviceCurrent: "This device",
twoFactorTrustedDeviceMeta: "Last used {lastSeen} · Expires {expires}",
twoFactorRevokeDevice: "Revoke",
twoFactorRevokeAllDevices: "Sign out all other trusted devices",
twoFactorTrustedDevicesRevokedAll: "All trusted devices have been signed out.",
twoFactorRevokeAllConfirmTitle: "Sign out all trusted devices?",
twoFactorRevokeAllConfirmBody: "You'll be asked for a 2FA code the next time you sign in on any device, including this one.",
sessionsSectionTitle: "Sessions",
sessionsEmpty: "No active sessions.",
sessionsUnknownDevice: "Unknown device",
sessionsCurrentDevice: "This device",
sessionsMeta: "Last active {lastSeen} · Expires {expires}",
sessionsRevoke: "Sign out",
sessionsRevoked: "Session signed out.",
sessionsRevokeOthers: "Sign out all other devices",
sessionsRevokedOthers: "All other sessions have been signed out.",
sessionsRevokeOthersConfirmTitle: "Sign out all other devices?",
sessionsRevokeOthersConfirmBody: "Every other session for your account will be signed out immediately. This device stays signed in.",
cropDialogTitle: "Crop profile image",
cropDialogBody: "Position and zoom your image. The saved avatar will be exported as a 512×512 square.",
cropDialogZoom: "Zoom",
@@ -775,15 +714,6 @@ export const translations = {
resetFailed: "Reset failed.",
backToLogin: "Back to login",
updatePassword: "Update password",
emailNotVerified: "Please verify your email address before signing in.",
resendVerificationEmail: "Resend verification email",
verificationEmailResent: "Verification email sent. Check your inbox.",
registerCheckEmailForVerification: "Check your email to verify your account.",
verifyEmailTitle: "Verify your email",
verifyEmailVerifying: "Verifying your email...",
verifyEmailSuccess: "Your email has been verified. You can now sign in.",
verifyEmailFailed: "This verification link is invalid or has expired.",
missingVerifyLinkInfo: "Missing user/token in link.",
jobTableSearch: "Search",
jobTableSearchPlaceholder: "Title, company, notes, messages",
jobTableStatus: "Status",
@@ -1354,67 +1284,6 @@ export const translations = {
profileUpdatePassword: "Oppdater passord",
profilePasswordUpdated: "Passord oppdatert.",
profilePasswordUpdateFailed: "Kunne ikke endre passord.",
twoFactorTitle: "Topunkts bekreftelse",
twoFactorHint: "Skriv inn 6-sifret kode fra autentiseringsappen din, eller en gjenopprettingskode.",
twoFactorCodeLabel: "Kode",
twoFactorVerify: "Bekreft",
twoFactorVerifying: "Bekrefter...",
twoFactorBack: "Tilbake",
twoFactorInvalidCode: "Ugyldig kode. Prøv igjen.",
twoFactorRateLimited: "For mange forsøk. Vent noen minutter og prøv igjen.",
twoFactorGenericError: "Noe gikk galt. Prøv igjen.",
twoFactorSectionTitle: "Topunkts autentisering",
twoFactorStatusEnabled: "Aktivert siden {date}",
twoFactorStatusDisabled: "Ikke aktivert",
twoFactorEnableButton: "Aktiver 2FA",
twoFactorDisableButton: "Deaktiver 2FA",
twoFactorRegenerateButton: "Generer nye gjenopprettingskoder",
twoFactorPasswordPrompt: "Bekreft passordet ditt for å fortsette",
twoFactorPasswordLabel: "Nåværende passord",
twoFactorContinue: "Fortsett",
twoFactorWrongPassword: "Feil passord.",
twoFactorSetupTitle: "Skann denne QR-koden",
twoFactorSetupHint: "Skann med autentiseringsappen din, eller skriv inn nøkkelen manuelt.",
twoFactorManualKeyLabel: "Manuell registreringsnøkkel",
twoFactorCopyKey: "Kopier nøkkel",
twoFactorKeyCopied: "Nøkkel kopiert til utklippstavlen.",
twoFactorConfirmCodeLabel: "6-sifret kode",
twoFactorConfirmCodeHint: "Skriv inn koden som vises i autentiseringsappen din for å bekrefte oppsettet.",
twoFactorConfirmButton: "Bekreft",
twoFactorRecoveryTitle: "Lagre gjenopprettingskodene dine",
twoFactorRecoveryHint: "Hver kode kan brukes én gang hvis du mister tilgang til autentiseringsappen din. Dette er eneste gang disse kodene vises.",
twoFactorCopyAll: "Kopier alle koder",
twoFactorCodesCopied: "Gjenopprettingskoder kopiert.",
twoFactorDownload: "Last ned som .txt",
twoFactorSavedConfirm: "Jeg har lagret gjenopprettingskodene mine",
twoFactorDone: "Ferdig",
twoFactorDisableWarning: "Deaktivering av 2FA vil også ugyldiggjøre gjenopprettingskodene dine.",
twoFactorRegenerateWarning: "Dette vil ugyldiggjøre eksisterende gjenopprettingskoder.",
twoFactorEnabledSuccess: "Topunkts autentisering aktivert.",
twoFactorDisabledSuccess: "Topunkts autentisering deaktivert.",
twoFactorRegenerateSuccess: "Gjenopprettingskoder generert på nytt.",
twoFactorTrustDevice: "Stol på denne enheten i 30 dager",
twoFactorTrustedDevicesTitle: "Betrodde enheter",
twoFactorTrustedDevicesEmpty: "Ingen betrodde enheter ennå.",
twoFactorTrustedDeviceUnknown: "Ukjent enhet",
twoFactorTrustedDeviceCurrent: "Denne enheten",
twoFactorTrustedDeviceMeta: "Sist brukt {lastSeen} · Utløper {expires}",
twoFactorRevokeDevice: "Fjern tilgang",
twoFactorRevokeAllDevices: "Logg ut alle andre betrodde enheter",
twoFactorTrustedDevicesRevokedAll: "Alle betrodde enheter er logget ut.",
twoFactorRevokeAllConfirmTitle: "Logg ut alle betrodde enheter?",
twoFactorRevokeAllConfirmBody: "Du vil bli bedt om en 2FA-kode neste gang du logger inn på en enhet, inkludert denne.",
sessionsSectionTitle: "Økter",
sessionsEmpty: "Ingen aktive økter.",
sessionsUnknownDevice: "Ukjent enhet",
sessionsCurrentDevice: "Denne enheten",
sessionsMeta: "Sist aktiv {lastSeen} · Utløper {expires}",
sessionsRevoke: "Logg ut",
sessionsRevoked: "Økten er logget ut.",
sessionsRevokeOthers: "Logg ut alle andre enheter",
sessionsRevokedOthers: "Alle andre økter er logget ut.",
sessionsRevokeOthersConfirmTitle: "Logg ut alle andre enheter?",
sessionsRevokeOthersConfirmBody: "Alle andre økter for kontoen din blir umiddelbart logget ut. Denne enheten forblir innlogget.",
cropDialogTitle: "Beskjær profilbilde",
cropDialogBody: "Plasser og zoom bildet. Det lagrede avataren eksporteres som en kvadratisk 512×512-fil.",
cropDialogZoom: "Zoom",
@@ -1823,15 +1692,6 @@ export const translations = {
resetFailed: "Tilbakestilling mislyktes.",
backToLogin: "Tilbake til innlogging",
updatePassword: "Oppdater passord",
emailNotVerified: "Vennligst bekreft e-postadressen din før du logger inn.",
resendVerificationEmail: "Send bekreftelses-e-post på nytt",
verificationEmailResent: "Bekreftelses-e-post sendt. Sjekk innboksen din.",
registerCheckEmailForVerification: "Sjekk e-posten din for å bekrefte kontoen.",
verifyEmailTitle: "Bekreft e-posten din",
verifyEmailVerifying: "Bekrefter e-posten din...",
verifyEmailSuccess: "E-posten din er bekreftet. Du kan nå logge inn.",
verifyEmailFailed: "Denne bekreftelseslenken er ugyldig eller har utløpt.",
missingVerifyLinkInfo: "Mangler bruker/token i lenken.",
jobTableSearch: "Søk",
jobTableSearchPlaceholder: "Tittel, selskap, notater, meldinger",
jobTableStatus: "Status",
-85
View File
@@ -1,5 +1,4 @@
import React from 'react';
import '@testing-library/jest-dom';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
@@ -82,88 +81,4 @@ describe('LoginPage', () => {
expect(mockNavigate).toHaveBeenCalledWith('/forgot-password?email=person%40example.com');
});
it('shows the 2FA code step when login requires two-factor, then proceeds like a normal login on success', async () => {
mockedApi.post.mockImplementation((url: string, payload?: any) => {
if (url === '/auth/login') {
return Promise.resolve({ data: { requiresTwoFactor: true, pendingToken: 'pending-abc' } } as any);
}
if (url === '/auth/2fa/challenge') {
expect(payload).toEqual({ pendingToken: 'pending-abc', code: '123456', trustDevice: false });
return Promise.resolve({ data: { authenticated: true, provider: 'local' } } as any);
}
return Promise.resolve({ data: {} } as any);
});
mockedApi.get.mockResolvedValueOnce({ data: { roles: [], email: 'person@example.com', userName: 'person' } } as any);
renderLoginPage();
await screen.findByLabelText('Email');
await userEvent.type(screen.getByLabelText('Email'), 'person@example.com');
await userEvent.type(screen.getByLabelText('Current password'), 'hunter2');
await userEvent.click(screen.getByRole('button', { name: 'Sign in' }));
await screen.findByText('Two-factor verification');
expect(screen.queryByLabelText('Email')).not.toBeInTheDocument();
await userEvent.type(screen.getByLabelText('Code'), '123456');
await userEvent.click(screen.getByRole('button', { name: 'Verify' }));
await waitFor(() => expect(mockedApi.post).toHaveBeenCalledWith('/auth/2fa/challenge', { pendingToken: 'pending-abc', code: '123456', trustDevice: false }));
await waitFor(() => expect(mockedApi.get).toHaveBeenCalledWith('/auth/me'));
await waitFor(() => expect(mockNavigate).toHaveBeenCalledWith('/dashboard', { replace: true }));
});
it('shows a clear message when the 2FA challenge is rate-limited', async () => {
mockedApi.post.mockImplementation((url: string) => {
if (url === '/auth/login') {
return Promise.resolve({ data: { requiresTwoFactor: true, pendingToken: 'pending-abc' } } as any);
}
if (url === '/auth/2fa/challenge') {
return Promise.reject({ response: { status: 429 } });
}
return Promise.resolve({ data: {} } as any);
});
renderLoginPage();
await screen.findByLabelText('Email');
await userEvent.type(screen.getByLabelText('Email'), 'person@example.com');
await userEvent.type(screen.getByLabelText('Current password'), 'hunter2');
await userEvent.click(screen.getByRole('button', { name: 'Sign in' }));
await screen.findByText('Two-factor verification');
await userEvent.type(screen.getByLabelText('Code'), '123456');
await userEvent.click(screen.getByRole('button', { name: 'Verify' }));
expect(await screen.findByRole('alert')).toHaveTextContent('Too many attempts. Please wait a few minutes and try again.');
});
it('offers a resend-verification action when login reports the account is not verified', async () => {
mockedApi.get.mockResolvedValueOnce({
data: { requireAuth: false, googleEnabled: false, microsoftEnabled: false, localEnabled: true, allowRegistration: false, requireEmailVerification: true },
} as any);
mockedApi.post.mockImplementation((url: string) => {
if (url === '/auth/login') {
return Promise.reject({ response: { status: 403, data: { error: 'email_not_verified' } } });
}
if (url === '/auth/resend-verification-email') {
return Promise.resolve({ data: {} } as any);
}
return Promise.resolve({ data: {} } as any);
});
renderLoginPage();
await screen.findByLabelText('Email');
await userEvent.type(screen.getByLabelText('Email'), 'unverified@example.com');
await userEvent.type(screen.getByLabelText('Current password'), 'hunter2');
await userEvent.click(screen.getByRole('button', { name: 'Sign in' }));
expect(await screen.findByText('Please verify your email address before signing in.')).toBeInTheDocument();
await userEvent.click(screen.getByRole('button', { name: 'Resend verification email' }));
await waitFor(() => expect(mockedApi.post).toHaveBeenCalledWith('/auth/resend-verification-email', { email: 'unverified@example.com' }));
await screen.findByText('Verification email sent. Check your inbox.');
});
});
@@ -1,95 +0,0 @@
import React from 'react';
import '@testing-library/jest-dom';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ToastProvider } from './toast';
import { I18nProvider } from './i18n/I18nProvider';
import TwoFactorSettingsCard from './components/TwoFactorSettingsCard';
import { api } from './api';
const mockedApi = api as jest.Mocked<typeof api>;
const writeTextMock = jest.fn(() => Promise.resolve());
Object.assign(navigator, { clipboard: { writeText: writeTextMock } });
Object.defineProperty(window.URL, 'createObjectURL', { writable: true, value: jest.fn(() => 'blob:mock') });
Object.defineProperty(window.URL, 'revokeObjectURL', { writable: true, value: jest.fn() });
function renderCard() {
return render(
<ToastProvider>
<I18nProvider>
<TwoFactorSettingsCard />
</I18nProvider>
</ToastProvider>,
);
}
beforeEach(() => {
jest.clearAllMocks();
mockedApi.get.mockImplementation((url: string) => {
if (url === '/auth/2fa/status') {
return Promise.resolve({ data: { enabled: false, enabledAtUtc: null } } as any);
}
return Promise.resolve({ data: {} } as any);
});
});
test('shows not-enabled status and walks through the full enable flow to recovery codes', async () => {
mockedApi.post.mockImplementation((url: string) => {
if (url === '/auth/2fa/setup') {
return Promise.resolve({ data: { manualEntryKey: 'ABCD1234', qrCodeDataUrl: 'data:image/png;base64,abc' } } as any);
}
if (url === '/auth/2fa/verify-setup') {
return Promise.resolve({ data: { enabled: true, recoveryCodes: ['aaaaa-11111', 'bbbbb-22222'] } } as any);
}
return Promise.resolve({ data: {} } as any);
});
renderCard();
expect(await screen.findByText('Not enabled')).toBeInTheDocument();
await userEvent.click(screen.getByRole('button', { name: 'Enable 2FA' }));
await userEvent.type(await screen.findByLabelText('Current password'), 'hunter2');
await userEvent.click(screen.getByRole('button', { name: 'Continue' }));
await waitFor(() => expect(mockedApi.post).toHaveBeenCalledWith('/auth/2fa/setup', { currentPassword: 'hunter2' }));
expect(await screen.findByAltText('Scan this QR code')).toHaveAttribute('src', 'data:image/png;base64,abc');
expect(screen.getByDisplayValue('ABCD1234')).toBeInTheDocument();
await userEvent.type(screen.getByLabelText('6-digit code'), '654321');
await userEvent.click(screen.getByRole('button', { name: 'Confirm' }));
await waitFor(() => expect(mockedApi.post).toHaveBeenCalledWith('/auth/2fa/verify-setup', { code: '654321' }));
expect(await screen.findByText('Save your recovery codes')).toBeInTheDocument();
expect(screen.getByText('aaaaa-11111')).toBeInTheDocument();
expect(screen.getByText('bbbbb-22222')).toBeInTheDocument();
const doneButton = screen.getByRole('button', { name: 'Done' });
expect(doneButton).toBeDisabled();
await userEvent.click(screen.getByLabelText("I've saved my recovery codes"));
expect(doneButton).toBeEnabled();
await userEvent.click(doneButton);
await waitFor(() => expect(screen.queryByText('Save your recovery codes')).not.toBeInTheDocument());
});
test('shows wrong-password error on disable and lets the user retry', async () => {
mockedApi.get.mockImplementation((url: string) => {
if (url === '/auth/2fa/status') {
return Promise.resolve({ data: { enabled: true, enabledAtUtc: '2026-01-01T00:00:00Z' } } as any);
}
return Promise.resolve({ data: {} } as any);
});
mockedApi.post.mockRejectedValueOnce({ response: { status: 401 } });
renderCard();
expect(await screen.findByText(/enabled since/i)).toBeInTheDocument();
await userEvent.click(screen.getByRole('button', { name: 'Disable 2FA' }));
await userEvent.type(await screen.findByLabelText('Current password'), 'wrong');
await userEvent.click(screen.getByRole('button', { name: 'Continue' }));
expect(await screen.findByText('Incorrect password.')).toBeInTheDocument();
expect(screen.getByLabelText('Current password')).toBeInTheDocument();
});
@@ -1,58 +0,0 @@
import React from 'react';
import '@testing-library/jest-dom';
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import VerifyEmailPage from './views/VerifyEmailPage';
import { I18nProvider } from './i18n/I18nProvider';
import { api, getApiErrorMessage } from './api';
const mockedApi = api as jest.Mocked<typeof api>;
// CRA's jest config sets resetMocks: true, which wipes the initial implementation given to
// jest.fn() in setupTests.ts before every test -- re-arm it here so error-derived text is testable.
const mockedGetApiErrorMessage = getApiErrorMessage as jest.Mock;
function renderVerifyEmailPage(search: string) {
window.history.pushState({}, '', `/verify-email${search}`);
return render(
<MemoryRouter initialEntries={[`/verify-email${search}`]} future={{ v7_startTransition: true, v7_relativeSplatPath: true }}>
<I18nProvider>
<VerifyEmailPage />
</I18nProvider>
</MemoryRouter>,
);
}
describe('VerifyEmailPage', () => {
beforeEach(() => {
mockedApi.post.mockReset();
mockedGetApiErrorMessage.mockImplementation((e: any, fallback?: string) => {
const data = e?.response?.data;
return typeof data === 'string' && data.trim() ? data.trim() : fallback;
});
});
it('confirms the account and shows success when the link is valid', async () => {
mockedApi.post.mockResolvedValueOnce({ data: {} } as any);
renderVerifyEmailPage('?userId=user-1&token=good-token');
expect(await screen.findByText('Your email has been verified. You can now sign in.')).toBeInTheDocument();
expect(mockedApi.post).toHaveBeenCalledWith('/auth/verify-email', { userId: 'user-1', token: 'good-token' });
});
it('shows an error when the link is invalid or expired', async () => {
mockedApi.post.mockRejectedValueOnce({ response: { status: 400, data: 'Invalid or expired link.' } });
renderVerifyEmailPage('?userId=user-1&token=bad-token');
expect(await screen.findByText('Invalid or expired link.')).toBeInTheDocument();
});
it('shows an error without calling the API when the link is missing userId/token', async () => {
renderVerifyEmailPage('');
expect(await screen.findByText('Missing user/token in link.')).toBeInTheDocument();
expect(mockedApi.post).not.toHaveBeenCalled();
});
});
+49 -107
View File
@@ -1,6 +1,6 @@
import React, { useEffect, useState } from "react";
import { Alert, Box, Button, Checkbox, FormControlLabel, Paper, Tab, Tabs, TextField, Typography } from "@mui/material";
import { Box, Button, Checkbox, FormControlLabel, Paper, Tab, Tabs, TextField, Typography } from "@mui/material";
import { useLocation, useNavigate } from "react-router-dom";
@@ -8,7 +8,6 @@ import { api, getApiErrorMessage } from "../api";
import { getRememberMePref, setAuthPersistencePreference } from "../auth";
import GoogleAuthCard from "../components/GoogleAuthCard";
import MicrosoftAuthCard from "../components/MicrosoftAuthCard";
import TwoFactorChallenge from "../components/TwoFactorChallenge";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";
@@ -18,7 +17,6 @@ type AuthConfig = {
microsoftEnabled: boolean;
localEnabled: boolean;
allowRegistration: boolean;
requireEmailVerification: boolean;
};
export default function LoginPage() {
@@ -34,10 +32,6 @@ export default function LoginPage() {
const [password, setPassword] = useState("");
const [rememberMe, setRememberMe] = useState(() => getRememberMePref());
const [loading, setLoading] = useState(false);
const [pendingToken, setPendingToken] = useState<string | null>(null);
const [emailNotVerified, setEmailNotVerified] = useState(false);
const [resendingVerification, setResendingVerification] = useState(false);
const [verificationResent, setVerificationResent] = useState(false);
const nextPath = (location?.state?.from as string | undefined) ?? "/dashboard";
@@ -48,52 +42,22 @@ export default function LoginPage() {
.catch(() => setCfg(null));
}, []);
async function completeLogin() {
setAuthPersistencePreference(rememberMe ? "local" : "session");
await api.get("/auth/me");
toast(t("signedIn"), "success");
navigate(nextPath, { replace: true });
}
async function submit(mode: "login" | "register") {
setLoading(true);
setEmailNotVerified(false);
setVerificationResent(false);
try {
const url = mode === "register" ? "/auth/register" : "/auth/login";
const res = await api.post<{ requiresTwoFactor?: boolean; pendingToken?: string }>(url, { email, password, rememberMe });
if (res.data?.requiresTwoFactor && res.data.pendingToken) {
setPendingToken(res.data.pendingToken);
return;
}
await completeLogin();
if (mode === "register" && cfg?.requireEmailVerification) {
toast(t("registerCheckEmailForVerification"), "info");
}
await api.post(url, { email, password, rememberMe });
setAuthPersistencePreference(rememberMe ? "local" : "session");
await api.get("/auth/me");
toast(t("signedIn"), "success");
navigate(nextPath, { replace: true });
} catch (e: any) {
if (mode === "login" && e?.response?.data?.error === "email_not_verified") {
setEmailNotVerified(true);
} else {
toast(getApiErrorMessage(e, t("loginFailed")), "error");
}
toast(getApiErrorMessage(e, t("loginFailed")), "error");
} finally {
setLoading(false);
}
}
async function resendVerification() {
setResendingVerification(true);
try {
await api.post("/auth/resend-verification-email", { email });
setVerificationResent(true);
toast(t("verificationEmailResent"), "success");
} catch (e: any) {
toast(getApiErrorMessage(e, t("verifyEmailFailed")), "error");
} finally {
setResendingVerification(false);
}
}
const allowReg = cfg?.allowRegistration ?? false;
return (
@@ -116,75 +80,53 @@ export default function LoginPage() {
{cfg?.requireAuth ? t("authRequired") : t("authOptional")}
</Typography>
{pendingToken ? (
<TwoFactorChallenge
pendingToken={pendingToken}
onCancel={() => setPendingToken(null)}
onSuccess={() => { setPendingToken(null); void completeLogin(); }}
/>
) : (
<>
<Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ mb: 2 }}>
<Tab label={t("emailAndPassword")} />
<Tab label={t("google")} />
<Tab label={t("microsoft")} />
</Tabs>
<Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ mb: 2 }}>
<Tab label={t("emailAndPassword")} />
<Tab label={t("google")} />
<Tab label={t("microsoft")} />
</Tabs>
{tab === 0 && (
<Box component="form" onSubmit={(e) => { e.preventDefault(); void submit("login"); }} sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
{cfg?.requireEmailVerification && emailNotVerified && (
<Alert
severity="warning"
action={
<Button color="inherit" size="small" disabled={resendingVerification || verificationResent} onClick={() => void resendVerification()}>
{verificationResent ? t("verificationEmailResent") : t("resendVerificationEmail")}
</Button>
}
>
{t("emailNotVerified")}
</Alert>
)}
<TextField label={t("profileEmail")} value={email} onChange={(e) => setEmail(e.target.value)} autoComplete="email" fullWidth />
<TextField label={t("profileCurrentPassword")} value={password} onChange={(e) => setPassword(e.target.value)} autoComplete={allowReg ? "new-password" : "current-password"} type="password" fullWidth />
{tab === 0 && (
<Box component="form" onSubmit={(e) => { e.preventDefault(); void submit("login"); }} sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
<TextField label={t("profileEmail")} value={email} onChange={(e) => setEmail(e.target.value)} autoComplete="email" fullWidth />
<TextField label={t("profileCurrentPassword")} value={password} onChange={(e) => setPassword(e.target.value)} autoComplete={allowReg ? "new-password" : "current-password"} type="password" fullWidth />
<Box sx={{ display: "flex", alignItems: { xs: "flex-start", sm: "center" }, justifyContent: "space-between", gap: 1, flexWrap: "wrap" }}>
<FormControlLabel
control={<Checkbox disableRipple checked={rememberMe} onChange={(e) => setRememberMe(e.target.checked)} />}
label={t("rememberMe")}
/>
<Button
type="button"
variant="text"
size="small"
disableRipple
onClick={() => navigate(`/forgot-password${email.trim() ? `?email=${encodeURIComponent(email.trim())}` : ""}`)}
sx={{ px: 0, minWidth: 0, fontWeight: 700, alignSelf: { xs: "stretch", sm: "auto" } }}
>
{t("forgotPassword")}
</Button>
</Box>
<Box sx={{ display: "flex", alignItems: { xs: "flex-start", sm: "center" }, justifyContent: "space-between", gap: 1, flexWrap: "wrap" }}>
<FormControlLabel
control={<Checkbox disableRipple checked={rememberMe} onChange={(e) => setRememberMe(e.target.checked)} />}
label={t("rememberMe")}
/>
<Button
type="button"
variant="text"
size="small"
disableRipple
onClick={() => navigate(`/forgot-password${email.trim() ? `?email=${encodeURIComponent(email.trim())}` : ""}`)}
sx={{ px: 0, minWidth: 0, fontWeight: 700, alignSelf: { xs: "stretch", sm: "auto" } }}
>
{t("forgotPassword")}
</Button>
</Box>
<Typography variant="body2" sx={{ color: "text.secondary", mt: -0.5 }}>
{rememberMe ? t("rememberMeHelpPersistent") : t("rememberMeHelpSession")}
</Typography>
<Typography variant="body2" sx={{ color: "text.secondary", mt: -0.5 }}>
{rememberMe ? t("rememberMeHelpPersistent") : t("rememberMeHelpSession")}
</Typography>
<Box sx={{ display: "flex", gap: 1, justifyContent: "flex-end", mt: 1 }}>
{allowReg && (
<Button type="button" variant="outlined" disableRipple disabled={loading} onClick={() => void submit("register")}>
{t("createAccount")}
</Button>
)}
<Button type="submit" variant="contained" disableRipple disabled={loading}>
{t("signInTitle")}
</Button>
</Box>
</Box>
)}
{tab === 1 && <GoogleAuthCard onSignedIn={() => { navigate(nextPath, { replace: true }); }} />}
{tab === 2 && <MicrosoftAuthCard onSignedIn={() => { navigate(nextPath, { replace: true }); }} />}
</>
<Box sx={{ display: "flex", gap: 1, justifyContent: "flex-end", mt: 1 }}>
{allowReg && (
<Button type="button" variant="outlined" disableRipple disabled={loading} onClick={() => void submit("register")}>
{t("createAccount")}
</Button>
)}
<Button type="submit" variant="contained" disableRipple disabled={loading}>
{t("signInTitle")}
</Button>
</Box>
</Box>
)}
{tab === 1 && <GoogleAuthCard onSignedIn={() => { navigate(nextPath, { replace: true }); }} />}
{tab === 2 && <MicrosoftAuthCard onSignedIn={() => { navigate(nextPath, { replace: true }); }} />}
</Paper>
</Box>
);
-5
View File
@@ -11,8 +11,6 @@ import { api, getApiErrorMessage } from "../api";
import GoogleAuthCard from "../components/GoogleAuthCard";
import MicrosoftAuthCard from "../components/MicrosoftAuthCard";
import AuthStatusCard from "../components/AuthStatusCard";
import TwoFactorSettingsCard from "../components/TwoFactorSettingsCard";
import SessionsSettingsCard from "../components/SessionsSettingsCard";
import EmailProviderConnections from "../components/EmailProviderConnections";
import CropImageDialog from "../components/CropImageDialog";
import { useToast } from "../toast";
@@ -1350,9 +1348,6 @@ export default function ProfilePage() {
</Button>
</Box>
</Box>
{isLocal ? <TwoFactorSettingsCard /> : null}
{isLocal ? <SessionsSettingsCard /> : null}
</Paper>
);
}
@@ -1,75 +0,0 @@
import React, { useEffect, useState } from "react";
import { Alert, Box, Button, CircularProgress, Paper, Typography } from "@mui/material";
import { useNavigate } from "react-router-dom";
import { api, getApiErrorMessage } from "../api";
import { useI18n } from "../i18n/I18nProvider";
type Status = "verifying" | "success" | "error";
export default function VerifyEmailPage() {
const { t } = useI18n();
const navigate = useNavigate();
const [status, setStatus] = useState<Status>("verifying");
const [errorMessage, setErrorMessage] = useState<string | null>(null);
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const userId = params.get("userId") || "";
const token = params.get("token") || "";
if (!userId || !token) {
setStatus("error");
setErrorMessage(t("missingVerifyLinkInfo"));
return;
}
api
.post("/auth/verify-email", { userId, token })
.then(() => setStatus("success"))
.catch((e: any) => {
setStatus("error");
setErrorMessage(getApiErrorMessage(e, t("verifyEmailFailed")));
});
}, [t]);
return (
<Box
sx={{
minHeight: "100vh",
display: "flex",
alignItems: "center",
justifyContent: "center",
p: 2,
background:
"radial-gradient(1200px 700px at 20% 0%, rgba(79,140,255,0.14), transparent 55%), radial-gradient(900px 600px at 80% 20%, rgba(245,158,11,0.10), transparent 55%)",
}}
>
<Paper sx={{ width: "min(520px, 100%)", p: 3 }}>
<Typography variant="h5" sx={{ fontWeight: 900, mb: 0.5 }}>
{t("verifyEmailTitle")}
</Typography>
<Box sx={{ display: "flex", flexDirection: "column", gap: 1.5, mt: 2 }}>
{status === "verifying" && (
<Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
<CircularProgress size={20} />
<Typography sx={{ color: "text.secondary" }}>{t("verifyEmailVerifying")}</Typography>
</Box>
)}
{status === "success" && <Alert severity="success">{t("verifyEmailSuccess")}</Alert>}
{status === "error" && <Alert severity="error">{errorMessage}</Alert>}
<Box sx={{ display: "flex", justifyContent: "flex-end", mt: 1 }}>
<Button variant="contained" onClick={() => navigate("/login")}>
{t("backToLogin")}
</Button>
</Box>
</Box>
</Paper>
</Box>
);
}