Files
sor/Server/src/SOR.Website/Pages/Auth/Login.cshtml.cs
T
c972b8687e feat(website): stand up SOR.Website public game site
Adds the complete SOR.Website ASP.NET Core Razor Pages project:

Security architecture:
- SecurityHeadersMiddleware sets strict CSP (script-src/style-src 'self',
  form-action 'self', frame-ancestors 'none', object-src 'none')
  — all XSS injection is dead on arrival
- __Host- cookie prefix on session + CSRF cookies (forces Secure, Path=/,
  no Domain — prevents subdomain-compromise cookie theft)
- Anti-forgery tokens on every POST by default (Razor Pages default)
- AuthorizeFolder("/Account") — unauthenticated access to any /account/*
  redirected to login at the routing layer, no per-page [Authorize] needed
- Rate limiting per-IP: login (10/5min), register (5/hr), reset (3/15min)
- Open redirect prevention: all returnUrl values checked with Url.IsLocalUrl
- Anti-enumeration: ForgotPassword/Register never reveal whether email exists
- Account lockout: 5 failed login attempts → 30min lockout
- ChangePasswordAsync requires current password before accepting new one
- Leaderboard only projects DisplayName + RankScore (email/ID never exposed)
- Data Protection keys in Redis (shared key ring across pods)
- ForwardedHeaders middleware for accurate IP under TLS-terminating ingress

Pages implemented:
- Public: Home, Story, How To Play, Cards (catalog + detail), Leaderboard,
  AI Assets (explanation + report), News, Support, Privacy, Terms, Webclient
- Auth: Login, Register, Logout (POST-only), ForgotPassword, ResetPassword,
  VerifyEmail — all with rate limiting and anti-enumeration controls
- Account (auth-gated): Overview, Profile (display name), Security
  (change password), Game stats

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
2026-04-22 19:51:04 -04:00

112 lines
4.1 KiB
C#

namespace SOR.Website.Pages.Auth;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.RateLimiting;
using SOR.Database.Entities.Identity;
/// <summary>
/// Handles player login via email + password.
///
/// Security controls:
/// - [EnableRateLimiting]: 10 attempts per IP per 5 minutes.
/// - lockoutOnFailure: true in PasswordSignInAsync — Identity locks the account
/// after 5 failures, defeating unlimited brute-force.
/// - ReturnUrl validated with Url.IsLocalUrl before redirect — no open redirect.
/// - Anti-forgery token validated by Razor Pages on every POST (default behavior).
/// - Generic error message: does NOT confirm whether the email exists (no enumeration).
/// - SignInWithClaimsAsync adds the display_name custom claim so the nav bar can
/// show the player's handle without a DB round-trip per request.
/// </summary>
[EnableRateLimiting("auth-login")]
public sealed class LoginModel(
SignInManager<Account> signInManager,
UserManager<Account> userManager) : PageModel
{
[BindProperty]
public InputModel Input { get; set; } = new();
// returnUrl is injected by ASP.NET Core's cookie auth middleware when it
// redirects an unauthenticated request to the login page.
[BindProperty(SupportsGet = true)]
public string? ReturnUrl { get; set; }
public string? ErrorMessage { get; private set; }
public sealed class InputModel
{
[Required(ErrorMessage = "Email is required.")]
[EmailAddress(ErrorMessage = "Enter a valid email address.")]
[MaxLength(254)]
public string Email { get; set; } = string.Empty;
[Required(ErrorMessage = "Password is required.")]
[DataType(DataType.Password)]
[MaxLength(128)]
public string Password { get; set; } = string.Empty;
public bool RememberMe { get; set; }
}
public IActionResult OnGet()
{
// Already signed in — send them where they were going.
if (User.Identity?.IsAuthenticated == true)
return SafeRedirect(ReturnUrl);
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
return Page();
// PasswordSignInAsync with lockoutOnFailure:true — after 5 failures the
// account is locked for 30 minutes (configured in Program.cs).
var result = await signInManager.PasswordSignInAsync(
Input.Email,
Input.Password,
Input.RememberMe,
lockoutOnFailure: true);
if (result.Succeeded)
{
// Add the display_name claim to the cookie so the layout can show
// the player's handle without a DB hit on every request.
var user = await userManager.FindByEmailAsync(Input.Email);
if (user is not null)
{
var extraClaims = new[]
{
new Claim("display_name", user.DisplayName ?? user.Email ?? string.Empty),
};
await signInManager.SignInWithClaimsAsync(user, Input.RememberMe, extraClaims);
}
return SafeRedirect(ReturnUrl);
}
if (result.IsLockedOut)
{
// Generic message — does not reveal whether the email exists.
ErrorMessage = "Too many failed attempts. Please try again later.";
return Page();
}
// Generic: do not confirm whether the email is registered (prevents enumeration).
ErrorMessage = "Invalid email or password.";
return Page();
}
// Ensures the redirect target is local to this application.
// Url.IsLocalUrl rejects absolute URLs and protocol-relative URLs,
// preventing open redirect attacks where an attacker crafts a link like
// /auth/login?returnUrl=https://evil.com
private IActionResult SafeRedirect(string? url)
=> Url.IsLocalUrl(url) ? LocalRedirect(url) : RedirectToPage("/Index");
}