using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; using Microsoft.Extensions.Options; using System.Security.Claims; using System.Security.Cryptography; using System.Text; using YaleAccess.Models; namespace YaleAccess.Controllers { [ApiController] [Route("api/[controller]")] [EnableCors] [Authorize] public class AuthenticationController(IOptions authenticationOptions, ILogger logger) : ControllerBase { public const string LoginRateLimitPolicy = "login"; [HttpPost("login")] [AllowAnonymous] [EnableRateLimiting(LoginRateLimitPolicy)] public async Task Login([FromBody] string password) { // Refuse to authenticate at all if no password has been configured string expectedPassword = authenticationOptions.Value.Password; if (string.IsNullOrEmpty(expectedPassword)) { logger.LogError("No authentication password has been configured, refusing all logins."); return StatusCode(StatusCodes.Status500InternalServerError, new ApiResponse("Authentication is not configured.")); } // Check if the password is correct if (!PasswordMatches(password, expectedPassword)) { logger.LogWarning("Failed login attempt from {RemoteIp}.", HttpContext.Connection.RemoteIpAddress); return Unauthorized(new ApiResponse("Incorrect password.")); } // Log the user in List claims = new() { new Claim(ClaimTypes.Name, "YaleAccess") }; ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme); ClaimsPrincipal claimsPrincipal = new(claimsIdentity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal); // Return the response return Ok(new ApiResponse(true)); } [HttpPost("logout")] [AllowAnonymous] public async Task Logout() { // Sign the user out await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Ok(new ApiResponse(true)); } /// /// Compares the passwords in constant time (by comparing hashes, so differing lengths don't leak either). /// private static bool PasswordMatches(string? provided, string expected) { byte[] providedHash = SHA256.HashData(Encoding.UTF8.GetBytes(provided ?? string.Empty)); byte[] expectedHash = SHA256.HashData(Encoding.UTF8.GetBytes(expected)); return CryptographicOperations.FixedTimeEquals(providedHash, expectedHash); } } }