Files
yale-user-access/packages/backend/Controllers/PeopleController.cs
T
LiamPietralla d0425c8cb2 Harden backend auth, validation and error handling
- Rate limit login (5 attempts/min per IP) with a JSON 429 response
- Constant-time password comparison; refuse login if no password is configured
- Explicit SameSite=Strict auth cookie; log failed logins with client IP
- Stop logging door codes (update log lines and the SMS body)
- Replace per-action try/catch -> 400 with a global exception handler (JSON 500)
- Return proper statuses: 404 for missing person, 502 for failed lock writes
- Validate codes as ASCII digits only (int.TryParse accepted +/-/whitespace)
- Validate person name and E.164 phone number; reject sending an unset code
- Rename TwiloOptions -> TwilioOptions and fix message typos
- Expose Program for integration tests
2026-11-16 12:23:31 +11:00

74 lines
2.4 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Text.RegularExpressions;
using YaleAccess.Data;
using YaleAccess.Models;
namespace YaleAccess.Controllers
{
[ApiController]
[Route("api/[controller]")]
[EnableCors]
[Authorize]
public partial class PeopleController(YaleContext context) : ControllerBase
{
// Twilio requires numbers in E.164 format, e.g. +61400000000
[GeneratedRegex(@"^\+[1-9]\d{6,14}$")]
private static partial Regex PhoneNumberRegex();
[HttpGet]
public async Task<IActionResult> GetPeople()
{
// Return all people
List<Person> people = await context.People.ToListAsync();
return Ok(new ApiResponse(people));
}
[HttpPost]
public async Task<IActionResult> CreatePerson([FromBody] Person person)
{
// Validate the person
string name = person.Name?.Trim() ?? string.Empty;
string phoneNumber = person.PhoneNumber?.Trim() ?? string.Empty;
if (name.Length == 0 || name.Length > 100)
{
return BadRequest(new ApiResponse("The name is required and must be 100 characters or fewer."));
}
if (!PhoneNumberRegex().IsMatch(phoneNumber))
{
return BadRequest(new ApiResponse("The phone number must be in international format, e.g. +61400000000."));
}
// Create a new person and add them
Person newPerson = new() { Name = name, PhoneNumber = phoneNumber };
await context.AddAsync(newPerson);
await context.SaveChangesAsync();
// Return the newly created person
return Ok(new ApiResponse(newPerson));
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeletePerson([FromRoute] int id)
{
// Ensure the person exists
Person? person = await context.People.FindAsync(id);
if (person is null)
{
return NotFound(new ApiResponse("Person not found."));
}
// Remove the person
context.Remove(person);
await context.SaveChangesAsync();
// Return the removed person
return Ok(new ApiResponse(person));
}
}
}