Compare commits

...
3 Commits
Author SHA1 Message Date
LiamPietralla 4fe6f9d7b5 Add backend and frontend tests and run them in CI
Build and Publish / Build Yale Access Frontend (pull_request) Successful in 1m17s
Build and Publish / Push Yale Access Frontend Docker Image (pull_request) Skipped
Build and Publish / Build Yale Access Backend (pull_request) Successful in 2m12s
Build and Publish / Push Yale Access Backend Docker Image (pull_request) Skipped
- Backend: xUnit integration tests (auth, rate limiting, people, lock codes,
  validation, error handling) using WebApplicationFactory with a fake lock
- Frontend: Vitest + Nuxt test utils for useApi, the auth middleware,
  LoginForm, UserCodeList and PeopleList
- Run both suites in CI before building
2026-11-16 12:23:32 +11:00
LiamPietralla a9bef7b50d Migrate frontend to Nuxt 4 and Nuxt UI
- Upgrade to Nuxt 4 (sources under app/), add @nuxt/ui, Tailwind v4 and
  Lucide icons; drop @nuxtjs/tailwindcss
- Replace the custom Yale* components, Modal, Navbar and icon components with
  UButton/UInput/UModal/UTable/UCard/UHeader/UBadge/UAlert and toasts
- Add dark/light mode toggle and a logout button
- Add a useApi composable: central base URL/credentials, JSON-encoded bodies,
  error handling, and redirect to login when the session expires
- Fix modal listener leak, missing People heading, unhandled fetch errors and
  login redirect for already-authenticated users
- Make the code and people tables fit on phone screens
- Retake README screenshots
2026-11-16 12:23:31 +11:00
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
75 changed files with 5912 additions and 3982 deletions

No files matched your search

+7
View File
@@ -33,6 +33,9 @@ jobs:
- name: Build - name: Build
run: dotnet build --configuration Release --no-restore run: dotnet build --configuration Release --no-restore
- name: Test
run: dotnet test ../backend.Tests --configuration Release
publish-backend: publish-backend:
name: Push Yale Access Backend Docker Image name: Push Yale Access Backend Docker Image
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -83,6 +86,10 @@ jobs:
working-directory: packages/frontend working-directory: packages/frontend
runtime: node@22 runtime: node@22
- name: Test
working-directory: ./packages/frontend
run: pnpm run test
- name: Build - name: Build
working-directory: ./packages/frontend working-directory: ./packages/frontend
run: pnpm run build run: pnpm run build
+2
View File
@@ -0,0 +1,2 @@
bin/
obj/
@@ -0,0 +1,101 @@
using System.Net;
using System.Net.Http.Json;
namespace YaleAccess.Tests;
public class AuthenticationTests
{
[Fact]
public async Task Protected_endpoints_return_401_without_a_login()
{
using var app = new TestApp();
var client = app.CreateClient();
Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/People")).StatusCode);
Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/Yale/codes")).StatusCode);
}
[Fact]
public async Task Health_endpoint_is_anonymous()
{
using var app = new TestApp();
var response = await app.CreateClient().GetAsync("/api/Health");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task Wrong_password_is_rejected_and_sets_no_cookie()
{
using var app = new TestApp();
var response = await app.CreateClient().PostAsJsonAsync("/api/Authentication/login", "wrong");
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.False(response.Headers.Contains("Set-Cookie"));
var body = await response.ReadApiAsync();
Assert.False(body.GetProperty("success").GetBoolean());
Assert.Equal("Incorrect password.", body.GetProperty("error").GetString());
}
[Fact]
public async Task Correct_password_sets_a_strict_httponly_cookie_and_grants_access()
{
using var app = new TestApp();
var client = app.CreateClient();
var login = await client.PostAsJsonAsync("/api/Authentication/login", TestConstants.Password);
Assert.Equal(HttpStatusCode.OK, login.StatusCode);
var cookie = Assert.Single(login.Headers.GetValues("Set-Cookie"));
Assert.Contains("samesite=strict", cookie, StringComparison.OrdinalIgnoreCase);
Assert.Contains("httponly", cookie, StringComparison.OrdinalIgnoreCase);
Assert.Equal(HttpStatusCode.OK, (await client.GetAsync("/api/People")).StatusCode);
}
[Fact]
public async Task Passwords_containing_quotes_and_backslashes_work()
{
const string password = "pa\"ss\\word";
using var app = new TestApp(password);
var response = await app.CreateClient().PostAsJsonAsync("/api/Authentication/login", password);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task Logout_ends_the_session()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
Assert.Equal(HttpStatusCode.OK, (await client.PostAsync("/api/Authentication/logout", null)).StatusCode);
Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/People")).StatusCode);
}
[Fact]
public async Task Login_is_refused_when_no_password_is_configured()
{
using var app = new TestApp(password: "");
var response = await app.CreateClient().PostAsJsonAsync("/api/Authentication/login", "");
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
}
[Fact]
public async Task Login_attempts_are_rate_limited()
{
using var app = new TestApp();
var client = app.CreateClient();
for (int i = 0; i < 5; i++)
{
var attempt = await client.PostAsJsonAsync("/api/Authentication/login", "wrong");
Assert.Equal(HttpStatusCode.Unauthorized, attempt.StatusCode);
}
// Even the right password is blocked once the limit is hit
var limited = await client.PostAsJsonAsync("/api/Authentication/login", TestConstants.Password);
Assert.Equal(HttpStatusCode.TooManyRequests, limited.StatusCode);
var body = await limited.ReadApiAsync();
Assert.False(body.GetProperty("success").GetBoolean());
Assert.Contains("Too many", body.GetProperty("error").GetString());
}
}
+77
View File
@@ -0,0 +1,77 @@
using System.Net;
using System.Net.Http.Json;
namespace YaleAccess.Tests;
public class PeopleTests
{
[Fact]
public async Task Create_list_and_delete_a_person()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var created = await client.PostAsJsonAsync("/api/People", new { name = " Alex ", phoneNumber = "+61400000001" });
Assert.Equal(HttpStatusCode.OK, created.StatusCode);
var person = (await created.ReadApiAsync()).GetProperty("data");
Assert.Equal("Alex", person.GetProperty("name").GetString()); // trimmed
int id = person.GetProperty("id").GetInt32();
var list = (await (await client.GetAsync("/api/People")).ReadApiAsync()).GetProperty("data");
Assert.Single(list.EnumerateArray());
Assert.Equal(HttpStatusCode.OK, (await client.DeleteAsync($"/api/People/{id}")).StatusCode);
list = (await (await client.GetAsync("/api/People")).ReadApiAsync()).GetProperty("data");
Assert.Empty(list.EnumerateArray());
}
[Theory]
[InlineData("0400000000")] // no country code
[InlineData("+61 400 000 001")] // spaces
[InlineData("+0123456789")] // leading zero after +
[InlineData("+12345")] // too short
[InlineData("")]
public async Task Invalid_phone_numbers_are_rejected(string phone)
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/People", new { name = "Alex", phoneNumber = phone });
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Contains("international format", (await response.ReadApiAsync()).GetProperty("error").GetString());
}
[Theory]
[InlineData("")]
[InlineData(" ")]
public async Task A_name_is_required(string name)
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/People", new { name, phoneNumber = "+61400000001" });
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task Names_over_100_characters_are_rejected()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/People", new { name = new string('a', 101), phoneNumber = "+61400000001" });
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task Deleting_a_missing_person_returns_404()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.DeleteAsync("/api/People/9999");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Equal("Person not found.", (await response.ReadApiAsync()).GetProperty("error").GetString());
}
}
+107
View File
@@ -0,0 +1,107 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using System.Net.Http.Json;
using System.Text.Json;
using YaleAccess.Models;
using YaleAccess.Services.Interfaces;
namespace YaleAccess.Tests;
public static class TestConstants
{
public const string Password = "test-password";
public const int HomeCode = 1;
}
/// <summary>
/// In-memory stand-in for the Z-Wave lock.
/// </summary>
public class FakeYaleAccessor : IYaleAccessor
{
public Dictionary<int, YaleUserCode> Codes { get; } = new()
{
[1] = new() { Id = 1, Code = "1111", Status = UserCodeStatus.ENABLED },
[2] = new() { Id = 2, Code = "2222", Status = UserCodeStatus.ENABLED },
[3] = new() { Id = 3, Code = "", Status = UserCodeStatus.AVAILABLE },
};
public bool FailWrites { get; set; }
public bool ThrowOnRead { get; set; }
public Task<YaleUserCode> GetCodeInformationAsync(int userCodeId)
{
if (ThrowOnRead) throw new InvalidOperationException("Lock unavailable");
var c = Codes[userCodeId];
return Task.FromResult(new YaleUserCode { Id = c.Id, Code = c.Code, Status = c.Status });
}
public Task<bool> SetUserCode(int userCodeId, string code)
{
if (FailWrites) return Task.FromResult(false);
Codes[userCodeId].Code = code;
Codes[userCodeId].Status = UserCodeStatus.ENABLED;
return Task.FromResult(true);
}
public Task<bool> SetCodeAsAvailable(int userCode)
{
if (FailWrites) return Task.FromResult(false);
Codes[userCode].Code = "";
Codes[userCode].Status = UserCodeStatus.AVAILABLE;
return Task.FromResult(true);
}
}
/// <summary>
/// Boots the real app with a throwaway SQLite database and a fake lock.
/// Use a fresh instance per test: the login rate limiter is per app instance.
/// </summary>
public class TestApp : WebApplicationFactory<Program>
{
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"yale-test-{Guid.NewGuid():N}.db");
private readonly string _password;
public FakeYaleAccessor Lock { get; } = new();
public TestApp(string password = TestConstants.Password) => _password = password;
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
// Development keeps the auth cookie non-Secure, so it works over the test server's plain HTTP
builder.UseEnvironment("Development");
builder.UseSetting("UseMockDevelopmentMode", "false");
builder.UseSetting("ConnectionStrings:YaleContext", $"Data Source={_dbPath}");
builder.UseSetting("Authentication:Password", _password);
builder.UseSetting("Codes:Home", TestConstants.HomeCode.ToString());
builder.UseSetting("Codes:GuestCodeRangeStart", "2");
builder.UseSetting("Codes:GuestCodeRangeCount", "2");
builder.ConfigureTestServices(services =>
{
services.AddSingleton<IYaleAccessor>(Lock);
});
}
public async Task<HttpClient> LoggedInClientAsync()
{
var client = CreateClient();
var response = await client.PostAsJsonAsync("/api/Authentication/login", TestConstants.Password);
response.EnsureSuccessStatusCode();
return client;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
try { File.Delete(_dbPath); } catch { /* best effort */ }
}
}
public static class HttpExtensions
{
public static async Task<JsonElement> ReadApiAsync(this HttpResponseMessage response)
=> await response.Content.ReadFromJsonAsync<JsonElement>();
}
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\backend\YaleAccess.csproj" />
</ItemGroup>
</Project>
+143
View File
@@ -0,0 +1,143 @@
using System.Net;
using System.Net.Http.Json;
using YaleAccess.Models;
using YaleAccess.Services;
namespace YaleAccess.Tests;
public class YaleCodeValidationTests
{
[Theory]
[InlineData("1234")]
[InlineData("12345")]
[InlineData("123456")]
[InlineData("0000")]
public void Valid_codes_pass(string code) => Assert.Equal(string.Empty, YaleAccessor.ValidateCode(code));
[Theory]
[InlineData("")]
[InlineData("123")]
[InlineData("1234567")]
public void Wrong_length_is_rejected(string code) => Assert.NotEqual(string.Empty, YaleAccessor.ValidateCode(code));
[Theory]
[InlineData("12a4")]
[InlineData("+123")]
[InlineData("-123")]
[InlineData(" 123")]
[InlineData("12.4")]
[InlineData("١٢٣٤")] // Arabic-Indic digits, not ASCII
public void Non_digit_codes_are_rejected(string code) => Assert.Equal("The code must be numeric.", YaleAccessor.ValidateCode(code));
[Fact]
public void The_home_code_cannot_be_cleared()
{
Assert.NotEqual(string.Empty, YaleAccessor.ValidateClearCode(1, 1));
Assert.Equal(string.Empty, YaleAccessor.ValidateClearCode(2, 1));
}
}
public class YaleEndpointTests
{
[Fact]
public async Task Codes_list_includes_guest_codes_and_flags_the_home_code()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var data = (await (await client.GetAsync("/api/Yale/codes")).ReadApiAsync()).GetProperty("data");
var codes = data.EnumerateArray().ToList();
Assert.Equal(3, codes.Count); // 2 guest codes + home
Assert.Equal(new[] { 1 }, codes.Where(c => c.GetProperty("isHome").GetBoolean()).Select(c => c.GetProperty("id").GetInt32()));
}
[Fact]
public async Task Setting_a_valid_code_updates_the_lock()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/Yale/code/3", "4321");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("4321", app.Lock.Codes[3].Code);
Assert.Equal(UserCodeStatus.ENABLED, app.Lock.Codes[3].Status);
}
[Theory]
[InlineData("12a4")]
[InlineData("+123")]
[InlineData("12")]
public async Task Invalid_codes_are_rejected_without_touching_the_lock(string code)
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/Yale/code/2", code);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal("2222", app.Lock.Codes[2].Code);
}
[Fact]
public async Task A_failed_lock_write_returns_502()
{
using var app = new TestApp();
app.Lock.FailWrites = true;
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/Yale/code/2", "4321");
Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
}
[Fact]
public async Task Clearing_a_guest_code_makes_it_available()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsync("/api/Yale/code/2/status", null);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(UserCodeStatus.AVAILABLE, app.Lock.Codes[2].Status);
}
[Fact]
public async Task The_home_code_cannot_be_cleared_via_the_api()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsync("/api/Yale/code/1/status", null);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal(UserCodeStatus.ENABLED, app.Lock.Codes[1].Status);
}
[Fact]
public async Task Sending_an_unset_code_is_rejected()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/Yale/code/3/send", "+61400000001");
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task Unexpected_errors_become_a_json_500_without_leaking_details()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
app.Lock.ThrowOnRead = true;
var response = await client.GetAsync("/api/Yale/codes");
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
var body = await response.ReadApiAsync();
Assert.False(body.GetProperty("success").GetBoolean());
Assert.Equal("An unexpected error occurred.", body.GetProperty("error").GetString());
}
}
@@ -3,8 +3,11 @@ using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using System.Security.Claims; using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using YaleAccess.Models; using YaleAccess.Models;
namespace YaleAccess.Controllers namespace YaleAccess.Controllers
@@ -15,15 +18,25 @@ namespace YaleAccess.Controllers
[Authorize] [Authorize]
public class AuthenticationController(IOptions<Models.Options.AuthenticationOptions> authenticationOptions, ILogger<AuthenticationController> logger) : ControllerBase public class AuthenticationController(IOptions<Models.Options.AuthenticationOptions> authenticationOptions, ILogger<AuthenticationController> logger) : ControllerBase
{ {
public const string LoginRateLimitPolicy = "login";
[HttpPost("login")] [HttpPost("login")]
[AllowAnonymous] [AllowAnonymous]
[EnableRateLimiting(LoginRateLimitPolicy)]
public async Task<IActionResult> Login([FromBody] string password) public async Task<IActionResult> Login([FromBody] string password)
{ {
try // 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 // Check if the password is correct
if (password != authenticationOptions.Value.Password) if (!PasswordMatches(password, expectedPassword))
{ {
logger.LogWarning("Failed login attempt from {RemoteIp}.", HttpContext.Connection.RemoteIpAddress);
return Unauthorized(new ApiResponse("Incorrect password.")); return Unauthorized(new ApiResponse("Incorrect password."));
} }
@@ -40,29 +53,25 @@ namespace YaleAccess.Controllers
// Return the response // Return the response
return Ok(new ApiResponse(true)); return Ok(new ApiResponse(true));
} }
catch(Exception ex)
{
logger.LogError(ex, "An error occurred logging in.");
return BadRequest(new ApiResponse("An error occurred logging in."));
}
}
[HttpPost("logout")] [HttpPost("logout")]
[AllowAnonymous] [AllowAnonymous]
public async Task<IActionResult> Logout() public async Task<IActionResult> Logout()
{
try
{ {
// Sign the user out // Sign the user out
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok(new ApiResponse(true)); return Ok(new ApiResponse(true));
} }
catch (Exception ex)
/// <summary>
/// Compares the passwords in constant time (by comparing hashes, so differing lengths don't leak either).
/// </summary>
private static bool PasswordMatches(string? provided, string expected)
{ {
logger.LogError(ex, "An error occured logging out."); byte[] providedHash = SHA256.HashData(Encoding.UTF8.GetBytes(provided ?? string.Empty));
return BadRequest(new ApiResponse("An error occured logging out.")); byte[] expectedHash = SHA256.HashData(Encoding.UTF8.GetBytes(expected));
} return CryptographicOperations.FixedTimeEquals(providedHash, expectedHash);
} }
} }
} }
@@ -2,6 +2,7 @@
using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System.Text.RegularExpressions;
using YaleAccess.Data; using YaleAccess.Data;
using YaleAccess.Models; using YaleAccess.Models;
@@ -11,66 +12,62 @@ namespace YaleAccess.Controllers
[Route("api/[controller]")] [Route("api/[controller]")]
[EnableCors] [EnableCors]
[Authorize] [Authorize]
public class PeopleController(ILogger<PeopleController> logger, YaleContext context) : ControllerBase 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] [HttpGet]
public async Task<IActionResult> GetPeople() public async Task<IActionResult> GetPeople()
{
try
{ {
// Return all people // Return all people
List<Person> people = await context.People.ToListAsync(); List<Person> people = await context.People.ToListAsync();
return Ok(new ApiResponse(people)); return Ok(new ApiResponse(people));
} }
catch (Exception ex)
{
logger.LogError(ex, "An error occured retriving the people.");
return BadRequest(new ApiResponse("An error occured retriving the people."));
}
}
[HttpPost] [HttpPost]
public async Task<IActionResult> CreatePerson([FromBody] Person person) public async Task<IActionResult> CreatePerson([FromBody] Person person)
{ {
try // Validate the person
{ string name = person.Name?.Trim() ?? string.Empty;
// Create a new person string phoneNumber = person.PhoneNumber?.Trim() ?? string.Empty;
Person newPerson = new() { Name = person.Name, PhoneNumber = person.PhoneNumber };
// Add the person 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.AddAsync(newPerson);
await context.SaveChangesAsync(); await context.SaveChangesAsync();
// Return the newly created person // Return the newly created person
return Ok(new ApiResponse(newPerson)); return Ok(new ApiResponse(newPerson));
} }
catch (Exception ex)
{
logger.LogError(ex, "An error occured creating the person.");
return BadRequest(new ApiResponse("An error occured creating the person."));
}
}
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<IActionResult> DeletePerson([FromRoute] int id) public async Task<IActionResult> DeletePerson([FromRoute] int id)
{
try
{ {
// Ensure the person exists // Ensure the person exists
Person person = await context.People.FindAsync(id) ?? throw new Exception("Person not found."); Person? person = await context.People.FindAsync(id);
if (person is null)
{
return NotFound(new ApiResponse("Person not found."));
}
// Remove the person // Remove the person
context.Remove(person); context.Remove(person);
await context.SaveChangesAsync(); await context.SaveChangesAsync();
// Return the newly removed person // Return the removed person
return Ok(new ApiResponse(person)); return Ok(new ApiResponse(person));
} }
catch (Exception ex)
{
logger.LogError(ex, "An error occured deletiong the person.");
return BadRequest(new ApiResponse("An error occured deletiong the person."));
}
}
} }
} }
+19 -51
View File
@@ -22,8 +22,6 @@ namespace YaleAccess.Controllers
{ {
[HttpGet("codes")] [HttpGet("codes")]
public async Task<IActionResult> GetUserCodes() public async Task<IActionResult> GetUserCodes()
{
try
{ {
// Get the home code first // Get the home code first
YaleUserCode homeCode = await yaleAccessor.GetCodeInformationAsync(codeOptions.Value.Home); YaleUserCode homeCode = await yaleAccessor.GetCodeInformationAsync(codeOptions.Value.Home);
@@ -42,17 +40,9 @@ namespace YaleAccess.Controllers
// Return the codes // Return the codes
return Ok(new ApiResponse(guestCodes)); return Ok(new ApiResponse(guestCodes));
} }
catch(Exception ex)
{
logger.LogError(ex, "An error occurred retriving the codes.");
return BadRequest(new ApiResponse("An error occurred retriving the codes."));
}
}
[HttpPost("code/{id}")] [HttpPost("code/{id}")]
public async Task<IActionResult> SetUserCode([FromRoute] int id, [FromBody] string newCode) public async Task<IActionResult> SetUserCode([FromRoute] int id, [FromBody] string newCode)
{
try
{ {
// First validate the user code // First validate the user code
string validCode = YaleAccessor.ValidateCode(newCode); string validCode = YaleAccessor.ValidateCode(newCode);
@@ -61,32 +51,21 @@ namespace YaleAccess.Controllers
return BadRequest(new ApiResponse(validCode)); return BadRequest(new ApiResponse(validCode));
} }
// Set the new code // Set the new code (the code itself is never logged)
bool result = await yaleAccessor.SetUserCode(id, newCode); bool result = await yaleAccessor.SetUserCode(id, newCode);
// Return the result if (!result)
if (result)
{ {
logger.LogInformation("Updated code for user {id} to {code}", id, newCode); logger.LogWarning("Failed to update code for user {Id}", id);
return StatusCode(StatusCodes.Status502BadGateway, new ApiResponse("An error occurred setting the code."));
}
logger.LogInformation("Updated code for user {Id}", id);
return Ok(new ApiResponse(true)); return Ok(new ApiResponse(true));
} }
else
{
logger.LogInformation("Failed to update code for user {id} to {code}", id, newCode);
return BadRequest(new ApiResponse("An error occurred setting the code."));
}
}
catch (Exception ex)
{
logger.LogError(ex, "An error occurred setting the code.");
return BadRequest(new ApiResponse("An error occurred setting the code."));
}
}
[HttpPost("code/{id}/status")] [HttpPost("code/{id}/status")]
public async Task<IActionResult> SetUserCodeStatusAsAvailable([FromRoute] int id) public async Task<IActionResult> SetUserCodeStatusAsAvailable([FromRoute] int id)
{
try
{ {
// First validate the user code // First validate the user code
string validCode = YaleAccessor.ValidateClearCode(id, codeOptions.Value.Home); string validCode = YaleAccessor.ValidateClearCode(id, codeOptions.Value.Home);
@@ -98,44 +77,33 @@ namespace YaleAccess.Controllers
// Set the available status // Set the available status
bool result = await yaleAccessor.SetCodeAsAvailable(id); bool result = await yaleAccessor.SetCodeAsAvailable(id);
// Return the result if (!result)
if (result)
{ {
logger.LogInformation("Updated code status for user {id} to available", id); logger.LogWarning("Failed to update code status for user {Id} to available", id);
return StatusCode(StatusCodes.Status502BadGateway, new ApiResponse("An error occurred setting the code status."));
}
logger.LogInformation("Updated code status for user {Id} to available", id);
return Ok(new ApiResponse(true)); return Ok(new ApiResponse(true));
} }
else
{
logger.LogInformation("Failed to update code status for user {id} to available", id);
return BadRequest(new ApiResponse("An error occurred setting the code status."));
}
}
catch (Exception ex)
{
logger.LogError(ex, "An error occurred setting the code status.");
return BadRequest(new ApiResponse("An error occurred setting the code status."));
}
}
[HttpPost("code/{id}/send")] [HttpPost("code/{id}/send")]
public async Task<IActionResult> SendUserCode([FromRoute] int id, [FromBody] string phoneNumber) public async Task<IActionResult> SendUserCode([FromRoute] int id, [FromBody] string phoneNumber)
{
try
{ {
// Get the user code // Get the user code
YaleUserCode userCode = await yaleAccessor.GetCodeInformationAsync(id); YaleUserCode userCode = await yaleAccessor.GetCodeInformationAsync(id);
// There is nothing to send if the code isn't set
if (string.IsNullOrEmpty(userCode.Code))
{
return BadRequest(new ApiResponse("This code is not set, so it cannot be sent."));
}
// Send the code via SMS to the phone number // Send the code via SMS to the phone number
await smsService.SendCodeViaSMSAsync(userCode.Code, phoneNumber); await smsService.SendCodeViaSMSAsync(userCode.Code, phoneNumber);
// Return success // Return success
return Ok(new ApiResponse(true)); return Ok(new ApiResponse(true));
} }
catch (Exception ex)
{
logger.LogError(ex, "An error occurred sending the code.");
return BadRequest(new ApiResponse("An error occurred sending the code."));
}
}
} }
} }
+1 -1
View File
@@ -7,7 +7,7 @@
public object? Data { get; set; } public object? Data { get; set; }
/// <summary> /// <summary>
/// If passing in data only then the resonse is successful /// If passing in data only then the response is successful
/// </summary> /// </summary>
/// <param name="data"></param> /// <param name="data"></param>
public ApiResponse(object data) public ApiResponse(object data)
@@ -1,6 +1,6 @@
namespace YaleAccess.Models.Options namespace YaleAccess.Models.Options
{ {
public class TwiloOptions public class TwilioOptions
{ {
public const string Twilio = "Twilio"; public const string Twilio = "Twilio";
+45 -1
View File
@@ -1,8 +1,12 @@
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System.Threading.RateLimiting;
using OpenTelemetry.Logs; using OpenTelemetry.Logs;
using YaleAccess.Controllers;
using YaleAccess.Data; using YaleAccess.Data;
using YaleAccess.Models;
using YaleAccess.Models.Options; using YaleAccess.Models.Options;
using YaleAccess.Services; using YaleAccess.Services;
using YaleAccess.Services.Interfaces; using YaleAccess.Services.Interfaces;
@@ -42,7 +46,7 @@ try
builder.Services.Configure<CodesOptions>(builder.Configuration.GetSection(CodesOptions.Codes)); builder.Services.Configure<CodesOptions>(builder.Configuration.GetSection(CodesOptions.Codes));
builder.Services.Configure<DevicesOptions>(builder.Configuration.GetSection(DevicesOptions.Devices)); builder.Services.Configure<DevicesOptions>(builder.Configuration.GetSection(DevicesOptions.Devices));
builder.Services.Configure<ZWaveOptions>(builder.Configuration.GetSection(ZWaveOptions.ZWave)); builder.Services.Configure<ZWaveOptions>(builder.Configuration.GetSection(ZWaveOptions.ZWave));
builder.Services.Configure<TwiloOptions>(builder.Configuration.GetSection(TwiloOptions.Twilio)); builder.Services.Configure<TwilioOptions>(builder.Configuration.GetSection(TwilioOptions.Twilio));
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
@@ -86,6 +90,9 @@ try
// Set HTTP only to true to prevent XSS attacks // Set HTTP only to true to prevent XSS attacks
options.Cookie.HttpOnly = true; options.Cookie.HttpOnly = true;
// The frontend and API are served from the same site, so strict SameSite blocks cross-site (CSRF) requests
options.Cookie.SameSite = SameSiteMode.Strict;
// Set secure policy to always to prevent sending cookies over HTTP for production use, for development set to None // Set secure policy to always to prevent sending cookies over HTTP for production use, for development set to None
if (builder.Environment.IsDevelopment()) if (builder.Environment.IsDevelopment())
options.Cookie.SecurePolicy = CookieSecurePolicy.None; options.Cookie.SecurePolicy = CookieSecurePolicy.None;
@@ -102,6 +109,26 @@ try
}; };
}); });
// Rate limit login attempts per client IP to slow down password guessing
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.AddPolicy(AuthenticationController.LoginRateLimitPolicy, context =>
RateLimitPartition.GetFixedWindowLimiter(
context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = 5,
Window = TimeSpan.FromMinutes(1),
QueueLimit = 0
}));
options.OnRejected = async (context, token) =>
{
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
await context.HttpContext.Response.WriteAsJsonAsync(new ApiResponse("Too many login attempts. Please wait a minute and try again."), token);
};
});
var app = builder.Build(); var app = builder.Build();
// Create the database if it doesn't exist // Create the database if it doesn't exist
@@ -129,10 +156,24 @@ try
app.UseCors(); app.UseCors();
// Turn unhandled exceptions into a JSON 500 (after CORS, so the browser can still read the response)
app.UseExceptionHandler(errorApp => errorApp.Run(async context =>
{
var exception = context.Features.Get<IExceptionHandlerFeature>()?.Error;
context.RequestServices.GetRequiredService<ILoggerFactory>()
.CreateLogger("UnhandledException")
.LogError(exception, "An unhandled error occurred handling {Method} {Path}.", context.Request.Method, context.Request.Path);
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
await context.Response.WriteAsJsonAsync(new ApiResponse("An unexpected error occurred."));
}));
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
app.UseRateLimiter();
app.MapControllers(); app.MapControllers();
app.Run(); app.Run();
@@ -147,3 +188,6 @@ catch (Exception ex)
throw; throw;
} }
} }
// Exposes the entry point to the integration tests (WebApplicationFactory<Program>)
public partial class Program { }
+5 -5
View File
@@ -5,23 +5,23 @@ using YaleAccess.Models.Options;
namespace YaleAccess.Services namespace YaleAccess.Services
{ {
public class SMSService(ILogger<SMSService> logger, IOptions<TwiloOptions> twiloOptions) public class SMSService(ILogger<SMSService> logger, IOptions<TwilioOptions> twilioOptions)
{ {
public async Task SendCodeViaSMSAsync(string code, string phoneNumber) public async Task SendCodeViaSMSAsync(string code, string phoneNumber)
{ {
// Create a Twilio client // Create a Twilio client
TwilioClient.Init(twiloOptions.Value.AccountSid, twiloOptions.Value.AuthToken); TwilioClient.Init(twilioOptions.Value.AccountSid, twilioOptions.Value.AuthToken);
// Send the message // Send the message
var message = await MessageResource.CreateAsync( var message = await MessageResource.CreateAsync(
body: $"{twiloOptions.Value.Message} {code}", body: $"{twilioOptions.Value.Message} {code}",
from: new Twilio.Types.PhoneNumber(twiloOptions.Value.FromNumber), from: new Twilio.Types.PhoneNumber(twilioOptions.Value.FromNumber),
to: new Twilio.Types.PhoneNumber(phoneNumber) to: new Twilio.Types.PhoneNumber(phoneNumber)
); );
// Log the message // Log the message
// (the message body contains the door code, so it is deliberately not logged)
logger.LogInformation("SMS sent to {PhoneNumber} with message SID {MessageSid}.", phoneNumber, message.Sid); logger.LogInformation("SMS sent to {PhoneNumber} with message SID {MessageSid}.", phoneNumber, message.Sid);
logger.LogDebug("SMS message: {MessageBody}", message.Body);
} }
} }
} }
+2 -1
View File
@@ -223,7 +223,8 @@ namespace YaleAccess.Services
} }
// The code must be numeric // The code must be numeric
if (!int.TryParse(newCode, out int _)) // (int.TryParse would also accept signs and whitespace, so check each character)
if (!newCode.All(char.IsAsciiDigit))
{ {
return "The code must be numeric."; return "The code must be numeric.";
} }
+1
View File
@@ -0,0 +1 @@
setups.@nuxt/test-utils="4.4.0"
-13
View File
@@ -1,13 +0,0 @@
<script setup lang="ts">
useHead({
bodyAttrs: {
class: 'bg-black'
}
})
</script>
<template>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</template>
+7
View File
@@ -0,0 +1,7 @@
<template>
<UApp>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</UApp>
</template>
@@ -0,0 +1,2 @@
@import "tailwindcss";
@import "@nuxt/ui";
@@ -0,0 +1,22 @@
<script setup lang="ts">
const config = useRuntimeConfig()
const healthResult = ref('Fetching health check...')
onMounted(async () => {
try {
healthResult.value = await $fetch<string>('/api/Health', {
baseURL: config.public.apiBaseUrl,
responseType: 'text'
})
} catch {
healthResult.value = 'Unable to reach the API.'
}
})
</script>
<template>
<div>
<h1 class="text-xl font-semibold">Health Check</h1>
<p>{{ healthResult }}</p>
</div>
</template>
@@ -0,0 +1,61 @@
<script setup lang="ts">
const api = useApi()
const authenticated = useCookie<boolean>('authenticated')
const password = ref('')
const showPassword = ref(false)
const error = ref('')
const loading = ref(false)
const handleLogin = async () => {
error.value = ''
loading.value = true
const response = await api.post<boolean>('/api/Authentication/login', password.value)
loading.value = false
if (response.success) {
authenticated.value = true
await navigateTo('/')
} else {
error.value = response.error ?? 'Unknown error'
}
}
</script>
<template>
<UCard class="w-full md:w-96">
<template #header>
<div class="text-center">
<h1 class="text-5xl font-bold">Yale</h1>
<p class="text-muted mt-1">User Access</p>
</div>
</template>
<UForm :state="{ password }" class="space-y-4" @submit="handleLogin">
<UFormField name="password" :error="error || undefined">
<UInput
v-model="password"
:type="showPassword ? 'text' : 'password'"
placeholder="Password"
autocomplete="current-password"
class="w-full"
autofocus
>
<template #trailing>
<UButton
color="neutral"
variant="link"
size="sm"
:icon="showPassword ? 'i-lucide-eye-off' : 'i-lucide-eye'"
:aria-label="showPassword ? 'Hide password' : 'Show password'"
@click="showPassword = !showPassword"
/>
</template>
</UInput>
</UFormField>
<UButton type="submit" block :loading="loading" :disabled="!password">Login</UButton>
</UForm>
</UCard>
</template>
@@ -0,0 +1,109 @@
<script setup lang="ts">
import type { FormError, TableColumn } from '@nuxt/ui'
import type { Person } from '~/types/yale'
const api = useApi()
const toast = useToast()
const people = ref<Person[]>([])
const loading = ref(true)
const saving = ref(false)
const addOpen = ref(false)
const newPerson = reactive({ name: '', phoneNumber: '' })
const columns: TableColumn<Person>[] = [
{ accessorKey: 'id', header: 'Person ID' },
{ accessorKey: 'name', header: 'Name' },
{ accessorKey: 'phoneNumber', header: 'Phone Number' },
{ id: 'actions', header: 'Actions' }
]
const loadPeople = async () => {
loading.value = true
const response = await api.get<Person[]>('/api/People')
if (response.success) {
people.value = response.data ?? []
} else {
toast.add({ title: 'Could not load people', description: response.error, color: 'error' })
}
loading.value = false
}
onMounted(loadPeople)
const validate = (state: typeof newPerson): FormError[] => {
const errors: FormError[] = []
if (!state.name.trim()) errors.push({ name: 'name', message: 'Name is required' })
if (!/^\+[1-9]\d{6,14}$/.test(state.phoneNumber.trim())) {
errors.push({ name: 'phoneNumber', message: 'Use international format, e.g. +61400000000' })
}
return errors
}
const savePerson = async () => {
saving.value = true
const response = await api.post<Person>('/api/People', { id: 0, ...newPerson })
saving.value = false
if (response.success && response.data) {
people.value.push(response.data)
addOpen.value = false
newPerson.name = ''
newPerson.phoneNumber = ''
toast.add({ title: 'Person added', color: 'success' })
} else {
toast.add({ title: 'Could not add person', description: response.error, color: 'error' })
}
}
const deletePerson = async (id: number) => {
const response = await api.delete<Person>(`/api/People/${id}`)
if (response.success) {
people.value = people.value.filter(x => x.id !== id)
toast.add({ title: 'Person removed', color: 'success' })
} else {
toast.add({ title: 'Could not remove person', description: response.error, color: 'error' })
}
}
</script>
<template>
<div>
<div class="flex justify-end mb-4">
<UButton icon="i-lucide-user-plus" @click="addOpen = true">Add Person</UButton>
</div>
<UTable
:data="people" :columns="columns" :loading="loading"
:ui="{ th: 'px-2 whitespace-nowrap', td: 'px-2' }"
>
<template #actions-cell="{ row }">
<UButton
color="error"
variant="ghost"
icon="i-lucide-trash-2"
:aria-label="`Delete ${row.original.name}`"
@click="deletePerson(row.original.id)"
/>
</template>
<template #empty>No people yet.</template>
</UTable>
<UModal v-model:open="addOpen" title="Add Person">
<template #body>
<UForm id="add-person" :state="newPerson" :validate="validate" class="space-y-4" @submit="savePerson">
<UFormField label="Name" name="name">
<UInput v-model="newPerson.name" placeholder="Name" class="w-full" />
</UFormField>
<UFormField label="Phone" name="phoneNumber">
<UInput v-model="newPerson.phoneNumber" type="tel" placeholder="+61400000000" class="w-full" />
</UFormField>
</UForm>
</template>
<template #footer>
<UButton color="neutral" variant="outline" @click="addOpen = false">Cancel</UButton>
<UButton type="submit" form="add-person" :loading="saving">Save</UButton>
</template>
</UModal>
</div>
</template>
@@ -0,0 +1,228 @@
<script setup lang="ts">
import type { TableColumn } from '@nuxt/ui'
import { UserCodeStatus, type Person, type YaleUserCode } from '~/types/yale'
type ModalKind = 'show' | 'edit' | 'clear' | 'send'
const api = useApi()
const toast = useToast()
const userCodes = ref<YaleUserCode[]>([])
const people = ref<{ label: string, value: string }[]>([])
const loading = ref(true)
const saving = ref(false)
// Only one modal is ever open, for one code at a time
const activeModal = ref<ModalKind | null>(null)
const activeCode = ref<YaleUserCode | null>(null)
const newCode = ref('')
const newCodeError = ref('')
const personNumber = ref<string | undefined>(undefined)
const columns: TableColumn<YaleUserCode>[] = [
{ accessorKey: 'id', header: 'Code ID' },
{ accessorKey: 'status', header: 'Status' },
{ id: 'actions', header: 'Actions' }
]
const statusDisplay: Record<UserCodeStatus, { label: string, color: 'success' | 'neutral' | 'error' }> = {
[UserCodeStatus.AVAILABLE]: { label: 'Available', color: 'neutral' },
[UserCodeStatus.ENABLED]: { label: 'Enabled', color: 'success' },
[UserCodeStatus.DISABLED]: { label: 'Disabled', color: 'error' }
}
const modalOpen = (kind: ModalKind) => activeModal.value === kind
const setModalOpen = (open: boolean) => {
if (!open) activeModal.value = null
}
const loadAll = async () => {
loading.value = true
const [codes, peopleResponse] = await Promise.all([
api.get<YaleUserCode[]>('/api/Yale/codes'),
api.get<Person[]>('/api/People')
])
if (codes.success) {
userCodes.value = (codes.data ?? []).sort((a, b) => a.id - b.id)
} else {
toast.add({ title: 'Could not load codes', description: codes.error, color: 'error' })
}
if (peopleResponse.success) {
people.value = (peopleResponse.data ?? []).map(x => ({ label: x.name, value: x.phoneNumber }))
}
loading.value = false
}
onMounted(loadAll)
const openModal = (kind: ModalKind, code: YaleUserCode) => {
activeCode.value = code
newCode.value = ''
newCodeError.value = ''
personNumber.value = undefined
activeModal.value = kind
}
const confirmUpdateCode = async () => {
const code = activeCode.value
if (!code) return
newCodeError.value = ''
if (!/^\d{4,6}$/.test(newCode.value)) {
newCodeError.value = 'Code must be 4, 5 or 6 digits long'
return
}
saving.value = true
const response = await api.post<boolean>(`/api/Yale/code/${code.id}`, newCode.value)
saving.value = false
if (response.success) {
code.code = newCode.value
code.status = UserCodeStatus.ENABLED
activeModal.value = null
toast.add({ title: `Code #${code.id} updated`, color: 'success' })
} else {
toast.add({ title: 'Could not update code', description: response.error, color: 'error' })
}
}
const confirmClearCode = async () => {
const code = activeCode.value
if (!code) return
saving.value = true
const response = await api.post<boolean>(`/api/Yale/code/${code.id}/status`)
saving.value = false
if (response.success) {
code.code = ''
code.status = UserCodeStatus.AVAILABLE
activeModal.value = null
toast.add({ title: `Code #${code.id} deleted`, color: 'success' })
} else {
toast.add({ title: 'Could not delete code', description: response.error, color: 'error' })
}
}
const confirmSendCode = async () => {
const code = activeCode.value
if (!code || !personNumber.value) return
saving.value = true
const response = await api.post<boolean>(`/api/Yale/code/${code.id}/send`, personNumber.value)
saving.value = false
if (response.success) {
activeModal.value = null
toast.add({ title: 'Code sent successfully', color: 'success' })
} else {
toast.add({ title: 'Could not send code', description: response.error, color: 'error' })
}
}
</script>
<template>
<div>
<UTable
:data="userCodes" :columns="columns" :loading="loading"
:ui="{ th: 'px-2 whitespace-nowrap', td: 'px-2' }"
>
<template #id-cell="{ row }">
<span class="inline-flex items-center gap-1">
{{ row.original.id }}
<UIcon v-if="row.original.isHome" name="i-lucide-house" class="size-4" aria-label="Home code" />
</span>
</template>
<template #status-cell="{ row }">
<UBadge
:color="statusDisplay[row.original.status]?.color ?? 'neutral'"
variant="subtle"
>
{{ statusDisplay[row.original.status]?.label ?? 'Unknown' }}
</UBadge>
</template>
<template #actions-cell="{ row }">
<div class="flex">
<UButton
color="neutral" variant="ghost" size="sm" icon="i-lucide-eye" aria-label="Show code"
:disabled="row.original.status !== UserCodeStatus.ENABLED"
@click="openModal('show', row.original)"
/>
<UButton
color="neutral" variant="ghost" size="sm" icon="i-lucide-pencil" aria-label="Edit code"
@click="openModal('edit', row.original)"
/>
<template v-if="!row.original.isHome">
<UButton
color="neutral" variant="ghost" size="sm" icon="i-lucide-send" aria-label="Send code"
:disabled="row.original.status !== UserCodeStatus.ENABLED"
@click="openModal('send', row.original)"
/>
<UButton
color="error" variant="ghost" size="sm" icon="i-lucide-trash-2" aria-label="Delete code"
:disabled="row.original.status !== UserCodeStatus.ENABLED"
@click="openModal('clear', row.original)"
/>
</template>
</div>
</template>
</UTable>
<!-- Show -->
<UModal :open="modalOpen('show')" :title="`User Code #${activeCode?.id}`" @update:open="setModalOpen">
<template #body>
<p class="text-2xl font-mono tracking-widest text-center">{{ activeCode?.code }}</p>
</template>
</UModal>
<!-- Edit -->
<UModal :open="modalOpen('edit')" :title="`Edit User Code #${activeCode?.id}`" @update:open="setModalOpen">
<template #body>
<form id="edit-code" class="space-y-4" @submit.prevent="confirmUpdateCode">
<UAlert
v-if="activeCode?.isHome"
color="warning" variant="subtle" icon="i-lucide-triangle-alert"
title="You are about to edit the home code, are you sure?"
/>
<UFormField :error="newCodeError || undefined">
<UInput
v-model="newCode" placeholder="New Code" inputmode="numeric" maxlength="6"
autocomplete="off" class="w-full" autofocus
/>
</UFormField>
</form>
</template>
<template #footer>
<UButton color="neutral" variant="outline" @click="activeModal = null">Cancel</UButton>
<UButton type="submit" form="edit-code" :loading="saving">Update Code</UButton>
</template>
</UModal>
<!-- Delete -->
<UModal :open="modalOpen('clear')" :title="`Delete User Code #${activeCode?.id}`" @update:open="setModalOpen">
<template #body>
<p>Are you sure you want to delete this code?</p>
</template>
<template #footer>
<UButton color="neutral" variant="outline" @click="activeModal = null">Cancel</UButton>
<UButton color="error" :loading="saving" @click="confirmClearCode">Delete Code</UButton>
</template>
</UModal>
<!-- Send -->
<UModal :open="modalOpen('send')" :title="`Send User Code #${activeCode?.id}`" @update:open="setModalOpen">
<template #body>
<USelect v-model="personNumber" :items="people" placeholder="Select a person" class="w-full" />
</template>
<template #footer>
<UButton color="neutral" variant="outline" @click="activeModal = null">Cancel</UButton>
<UButton :loading="saving" :disabled="!personNumber" @click="confirmSendCode">Send Code</UButton>
</template>
</UModal>
</div>
</template>
@@ -0,0 +1,46 @@
import type { FetchError } from 'ofetch'
import type { ApiResponse } from '~/types/api-response'
/**
* Thin wrapper around $fetch for the Yale Access API.
* Always resolves to an ApiResponse (never throws), and sends the user
* back to the login page when the server session has expired.
*/
export function useApi() {
const config = useRuntimeConfig()
const authenticated = useCookie<boolean>('authenticated')
async function request<T>(path: string, method: 'GET' | 'POST' | 'DELETE' = 'GET', body?: unknown): Promise<ApiResponse<T>> {
try {
return await $fetch<ApiResponse<T>>(path, {
baseURL: config.public.apiBaseUrl,
method,
credentials: 'include',
// The API takes bare JSON strings for some bodies, so always JSON-encode
...(body !== undefined && {
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' }
})
})
} catch (e) {
const err = e as FetchError<ApiResponse<T>>
// The cookie auth middleware answers an expired session with an empty 401
if (err.status === 401 && !err.data?.error) {
authenticated.value = false
await navigateTo('/login')
return { success: false, error: 'Your session has expired. Please log in again.' }
}
return err.data?.error
? { success: false, error: err.data.error }
: { success: false, error: 'Unable to reach the server.' }
}
}
return {
get: <T>(path: string) => request<T>(path),
post: <T>(path: string, body?: unknown) => request<T>(path, 'POST', body),
delete: <T>(path: string) => request<T>(path, 'DELETE')
}
}
+5
View File
@@ -0,0 +1,5 @@
<template>
<div class="min-h-screen flex items-center justify-center p-4">
<slot />
</div>
</template>
+34
View File
@@ -0,0 +1,34 @@
<script setup lang="ts">
const api = useApi()
const authenticated = useCookie<boolean>('authenticated')
const items = [
{ label: 'Home', to: '/', icon: 'i-lucide-house' },
{ label: 'People', to: '/people', icon: 'i-lucide-users' }
]
const logout = async () => {
await api.post('/api/Authentication/logout')
authenticated.value = false
await navigateTo('/login')
}
</script>
<template>
<UHeader title="Yale | User Access">
<UNavigationMenu :items="items" />
<template #right>
<UColorModeButton />
<UButton color="neutral" variant="ghost" icon="i-lucide-log-out" aria-label="Log out" @click="logout" />
</template>
<template #body>
<UNavigationMenu :items="items" orientation="vertical" class="-mx-2.5" />
</template>
</UHeader>
<UContainer class="py-6">
<slot />
</UContainer>
</template>
@@ -0,0 +1,15 @@
const anonymousRoutes = ['/login', '/health']
export default defineNuxtRouteMiddleware((to) => {
const authenticated = useCookie<boolean>('authenticated')
// Not logged in: send to the login page
if (!anonymousRoutes.includes(to.path) && !authenticated.value) {
return navigateTo('/login')
}
// Already logged in: skip the login page
if (to.path === '/login' && authenticated.value) {
return navigateTo('/')
}
})
+5
View File
@@ -0,0 +1,5 @@
<template>
<UContainer class="py-6">
<HealthCheck />
</UContainer>
</template>
+8
View File
@@ -0,0 +1,8 @@
<template>
<UCard>
<template #header>
<h2 class="text-lg font-semibold">User Codes</h2>
</template>
<UserCodeList />
</UCard>
</template>
+9
View File
@@ -0,0 +1,9 @@
<script setup lang="ts">
definePageMeta({
layout: 'blank'
})
</script>
<template>
<LoginForm />
</template>
+8
View File
@@ -0,0 +1,8 @@
<template>
<UCard>
<template #header>
<h2 class="text-lg font-semibold">People</h2>
</template>
<PeopleList />
</UCard>
</template>
File renamed without changes.
@@ -1,26 +0,0 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
const runtimeConfig = useRuntimeConfig();
const healthResult = ref<string>("Fetching health check...");
onMounted(async () => {
// Send a request to the API Health Check endpoint
const response = await fetch(`${runtimeConfig.public.apiBaseUrl}/api/Health`);
// Extract the response payload (string result)
const result = await response.text();
// Set the result
healthResult.value = result;
})
</script>
<template>
<div class="text-slate-300">
<h1>Health Check</h1>
<p>{{ healthResult }}</p>
</div>
</template>
@@ -1,67 +0,0 @@
<script setup lang='ts'>
import { ref } from 'vue';
import { type ApiResponse } from '~/types/api-response';
const password = ref('');
const passwordError = ref('');
const authenticated = useCookie<boolean>('authenticated');
const runtimeConfig = useRuntimeConfig();
const handleLogin = async (event: Event) => {
// Prevent default form submission
event.preventDefault();
// Reset the error
passwordError.value = '';
// Send a request to the api to login
const response = await fetch(`${runtimeConfig.public.apiBaseUrl}/api/Authentication/login`, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
body: `"${password.value}"`
});
// Parse the response
const apiResponse = await response.json() as ApiResponse<boolean>;
if (apiResponse.success) {
// If the response was successful, login and redirect to the home page
authenticated.value = true;
navigateTo('/');
} else {
// Otherwise, set the error
passwordError.value = apiResponse.error ?? 'Unknown error';
}
}
</script>
<template>
<div class="bg-zinc-800 text-slate-300 text-center w-full md:w-96 rounded-md">
<h1 class="text-7xl mt-5">Yale</h1>
<div>
<h4 class="hr text-2xl mt-3">User Access</h4>
</div>
<form @submit="handleLogin">
<YaleFormInput type="password" v-model="password" placeholder="Password" class="block mt-10 w-5/6 mx-auto" />
<p class="mt-3 w-5/6 mx-auto text-red-600" v-if="passwordError">{{ passwordError }}</p>
<YaleButton type="submit" class="mb-8 mt-3 w-5/6 mx-auto ">Login</YaleButton>
</form>
</div>
</template>
<style>
.hr {
display: inline-block;
}
.hr::after {
content: '';
display: block;
border-top: 2px solid theme('colors.slate.300');
margin-top: .1rem;
}
</style>
-37
View File
@@ -1,37 +0,0 @@
<script setup lang="ts">
const emit = defineEmits<{
(e: "close"): void
}>();
const handleClick = () => {
emit("close");
}
// If clicking outside the modal, close it
document.addEventListener("click", (event) => {
if (event.target === document.querySelector(".fixed")) {
handleClick();
}
});
</script>
<template>
<div class="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center">
<div class="bg-zinc-800 rounded-md min-w-96">
<div class="p-6 border-b border-slate-300">
<h3 class="text-md font-bold flex justify-between items-center">
<slot name="title"></slot>
<YaleButton type="button" @click="handleClick">
<IconXMark />
</YaleButton>
</h3>
</div>
<div class="p-6 border-b border-slate-300">
<slot></slot>
</div>
<div class="p-6">
<slot name="footer"></slot>
</div>
</div>
</div>
</template>
-7
View File
@@ -1,7 +0,0 @@
<template>
<nav class="w-full bg-zinc-800 p-4 mb-4 flex gap-5 items-center">
<h1 class="text-slate-300 font-bold text-2xl inline-block">Yale | User Access</h1>
<NuxtLink to="/" class="text-slate-300 hover:text-slate-100">Home</NuxtLink>
<NuxtLink to="/people" class="text-slate-300 hover:text-slate-100">People</NuxtLink>
</nav>
</template>
-132
View File
@@ -1,132 +0,0 @@
<script setup lang="ts">
import { type Person } from '@/types/yale';
import { onMounted, ref } from 'vue';
import type { ApiResponse } from '~/types/api-response';
const people = ref([] as Person[]);
const person = ref({ id: 0, name: '', phoneNumber: '' } as Person);
const loading = ref(true);
const runtimeConfig = useRuntimeConfig();
const addModal = ref(false);
// When the component is mounted, load the people
onMounted(async () => {
await loadPeople();
loading.value = false;
});
const loadPeople = async () => {
// Send a request to the api to get the people
const response = await fetch(`${runtimeConfig.public.apiBaseUrl}/api/People`, { credentials: 'include' });
// Parse the response
const apiResponse = await response.json() as ApiResponse<Person[]>;
// Set the people
people.value = apiResponse.data || [];
}
const handleAddPerson = () => {
addModal.value = true;
}
const handleSavePerson = async () => {
// Validate the person fields
if (!person.value.name || !person.value.phoneNumber) {
alert('Name and phone number are required');
return;
}
// Set the loading status
loading.value = true;
// Send a request to the api to save the person
const response = await fetch(`${runtimeConfig.public.apiBaseUrl}/api/People`, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(person.value)
});
// Parse the response
const apiResponse = await response.json() as ApiResponse<Person>;
if (apiResponse.success) {
// Add the new person to the list
people.value.push(apiResponse.data!);
addModal.value = false;
} else {
alert(apiResponse.error ?? 'An error occurred');
}
// Close the modal and reset the person
loading.value = false;
person.value = { id: 0, name: '', phoneNumber: '' };
// Set the loading status
loading.value = false;
}
const handleDeletePerson = async (id: number) => {
// Set the loading status
loading.value = true;
// Send a request to the api to delete the person
const response = await fetch(`${runtimeConfig.public.apiBaseUrl}/api/People/${id}`, {
method: 'DELETE',
credentials: 'include'
});
// Parse the response
const apiResponse = await response.json() as ApiResponse<Person>;
if (apiResponse.success) {
// Remove the person from the list
const index = people.value.findIndex(x => x.id === id);
people.value.splice(index, 1);
} else {
alert(apiResponse.error ?? 'An error occurred');
}
// Set the loading status
loading.value = false;
}
</script>
<template>
<!-- Handle loading state -->
<div v-if="loading">Loading...</div>
<template v-else>
<div class="text-end my-2">
<YaleButton type="button" @click="handleAddPerson">Add Person</YaleButton>
</div>
<table class="w-full text-left">
<tr>
<th scope="col">Person ID</th>
<th scope="col">Name</th>
<th scope="col">Phone Number</th>
<th scope="col">Actions</th>
</tr>
<PeopleListRow v-for="person in people" :key="person.id" :person="person" @delete-person="handleDeletePerson" />
</table>
</template>
<!-- Add modal -->
<Modal v-if="addModal" @close="addModal = false">
<template #title>
Add Person
</template>
<template #default>
<div class="flex flex-col space-y-2">
<YaleFormInput v-model="person.name" type="text" placeholder="Name" class="block w-full" />
<YaleFormInput v-model="person.phoneNumber" type="text" placeholder="Phone" class="block w-full" />
<div class="flex justify-end">
<YaleButton type="button" @click="handleSavePerson">Save</YaleButton>
</div>
</div>
</template>
</Modal>
</template>
@@ -1,34 +0,0 @@
<script setup lang='ts'>
import { type Person } from '~/types/yale';
import { type PropType } from 'vue';
const props = defineProps({
person: {
type: Object as PropType<Person>,
required: true
}
});
const emit = defineEmits<{
(e: "delete-person", id: number): void
}>();
// Handle the clear code button click
const handleDeletePersonClick = () => {
// Emit the event to the parent component
emit("delete-person", props.person.id);
}
</script>
<template>
<tr scope="row">
<td>{{ person.id }}</td>
<td>{{ person.name }}</td>
<td>{{ person.phoneNumber }}</td>
<td class="flex">
<YaleButton type="button" @click="handleDeletePersonClick">
<IconTrash />
</YaleButton>
</td>
</tr>
</template>
@@ -1,300 +0,0 @@
<script setup lang='ts'>
import type { ApiResponse } from '@/types/api-response';
import UserCodeListRow from './UserCodeListRow.vue';
import { onMounted, ref } from 'vue';
import { UserCodeStatus, type Person, type YaleUserCode } from '@/types/yale';
const userCodes = ref([] as YaleUserCode[]);
const userCode = ref({} as YaleUserCode);
const people = ref([] as { label: string, value: string }[]);
const personNumber = ref('');
const loading = ref(true);
const runtimeConfig = useRuntimeConfig();
// Modals
const showModal = ref(false);
const editModal = ref(false);
const clearModal = ref(false);
const sendModal = ref(false);
// Form Fields
const newCode = ref('');
const newCodeError = ref('');
// When the component is mounted, load the user codes
onMounted(async () => {
// Load the user codes and set the loading status when complete
await loadUserCodes();
await loadPeople();
loading.value = false;
});
const loadUserCodes = async () => {
// Send a request to the api to get the user codes
const response = await fetch(`${runtimeConfig.public.apiBaseUrl}/api/Yale/codes`, { credentials: 'include' });
// Parse the response
const apiResponse = await response.json() as ApiResponse<YaleUserCode[]>;
// Set the user codes by id
userCodes.value = apiResponse.data?.sort((a, b) => a.id - b.id) || [];
}
const loadPeople = async () => {
// Send a request to the api to get the people
const response = await fetch(`${runtimeConfig.public.apiBaseUrl}/api/People`, { credentials: 'include' });
// Parse the response
const apiResponse = await response.json() as ApiResponse<Person[]>;
// Set the people for drop down
people.value = apiResponse.data?.map(x => ({ label: x.name, value: x.phoneNumber })) || [];
}
const confirmUpdateCode = async (id: number, code: string) => {
// Reset the error
newCodeError.value = '';
// Validate the new code first
if (!/^\d{4,6}$/.test(code)) {
newCodeError.value = 'Code must be 4, 5 or 6 digits long';
return;
}
// Set the loading status
loading.value = true;
// Send a request to the api, the body will just be the new code
const response = await fetch(`${runtimeConfig.public.apiBaseUrl}/api/Yale/code/${id}`, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
body: `"${code}"`
});
// Parse the result
const apiResponse = await response.json() as ApiResponse<boolean>;
if (apiResponse.success) {
// If the response was successful update the code in the list
const index = userCodes.value.findIndex(x => x.id === id);
userCodes.value[index].code = code;
userCodes.value[index].status = UserCodeStatus.ENABLED;
} else {
// Otherwise display an error to the user.
alert(apiResponse.error ?? 'Unknown error');
}
// Reset the new code
newCode.value = '';
// Close the edit modal
editModal.value = false;
// Set the loading status
loading.value = false;
}
const confirmClearCode = async (id: number) => {
// Set the loading status
loading.value = true;
// Send a request to the api
const response = await fetch(`${runtimeConfig.public.apiBaseUrl}/api/Yale/code/${id}/status`, {
method: 'POST',
credentials: 'include'
});
// Parse the response
const apiResponse = await response.json() as ApiResponse<boolean>;
if (apiResponse.success) {
// If the response was successful set the code to available in the list
const index = userCodes.value.findIndex(x => x.id === id);
userCodes.value[index].code = '';
userCodes.value[index].status = UserCodeStatus.AVAILABLE;
} else {
// Otherwise display an error to the user.
alert(apiResponse.error ?? 'Unknown error');
}
// Close the clear modal
clearModal.value = false;
// Set the loading status
loading.value = false;
}
const handleShowCode = (id: number) => {
// Get the user code to show
const code = userCodes.value.find(x => x.id === id);
// If the code is not found then show an error to the user
if (!code) {
alert('Code not found');
return;
}
// Set the user code to show
userCode.value = code;
// Show the show-modal
showModal.value = true;
}
const handleUpdateCode = (id: number) => {
// Get the user code to update
const code = userCodes.value.find(x => x.id === id);
// If the code is not found then show an error to the user
if (!code) {
alert('Code not found');
return;
}
// Set the user code to update
userCode.value = code;
// Show the edit-modal
editModal.value = true;
}
const handleClearCode = (id: number) => {
// Get the user code to clear
const code = userCodes.value.find(x => x.id === id);
// If the code is not found then show an error to the user
if (!code) {
alert('Code not found');
return;
}
// Set the user code to clear
userCode.value = code;
// Show the clear-modal
clearModal.value = true;
}
const handleSendCode = (id: number) => {
// Get the user code to send
const code = userCodes.value.find(x => x.id === id);
// If the code is not found then show an error to the user
if (!code) {
alert('Code not found');
return;
}
// Set the user code
userCode.value = code;
// Show the send modal
sendModal.value = true;
}
const confirmSendCode = async (id: number) => {
// Set the loading status
loading.value = true;
if (!personNumber.value) {
alert('Please select a person to send the code to');
loading.value = false;
return;
}
// Send a request to the api to send the code
const response = await fetch(`${runtimeConfig.public.apiBaseUrl}/api/Yale/code/${id}/send`, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
body: `"${personNumber.value}"`
});
// Parse the response
const apiResponse = await response.json() as ApiResponse<boolean>;
if (apiResponse.success) {
alert('Code sent successfully');
} else {
alert(apiResponse.error ?? 'Unknown error');
}
// Close the clear modal
sendModal.value = false;
// Clear the person number and user code
personNumber.value = '';
userCode.value = {} as YaleUserCode;
// Set the loading status
loading.value = false;
}
</script>
<template>
<!-- Handle loading state -->
<div v-if="loading">Loading...</div>
<table v-else class="w-full text-left">
<tr>
<th scope="col">Code ID</th>
<th scope="col">Status</th>
<th scope="col">Actions</th>
</tr>
<UserCodeListRow v-for="userCode in userCodes" :key="userCode.id" :user-code="userCode"
@update-code="handleUpdateCode" @clear-code="handleClearCode" @show-code="handleShowCode"
@send-code="handleSendCode" />
</table>
<!-- Show modal -->
<Modal v-if="showModal" @close="showModal = false">
<template #title>
User Code # {{ userCode.id }}
</template>
<template #default>
Code: {{ userCode.code }}
</template>
</Modal>
<!-- Edit modal -->
<Modal v-if="editModal" @close="editModal = false">
<template #title>
Edit User Code # {{ userCode.id }}
</template>
<template #default>
<YaleFormInput v-model="newCode" type="text" placeholder="New Code" class="block w-full" />
<p class="text-red-600 mt-3" v-if="newCodeError">{{ newCodeError }}</p>
<YaleButton @click="confirmUpdateCode(userCode.id, newCode)" class="w-full mt-3">Update Code</YaleButton>
</template>
<template #footer v-if="userCode.isHome">
<p class="text-red-600 mt-3">You are about to edit the home code, are you sure?</p>
</template>
</Modal>
<!-- Clear modal -->
<Modal v-if="clearModal" @close="clearModal = false">
<template #title>
Delete User Code # {{ userCode.id }}
</template>
<template #default>
<p>Are you sure you want to delete this code?</p>
<YaleButton @click="confirmClearCode(userCode.id)" class="w-full mt-3">Delete Code</YaleButton>
</template>
</Modal>
<!-- Send modal -->
<Modal v-if="sendModal" @close="sendModal = false">
<template #title>
Send User Code # {{ userCode.id }}
</template>
<template #default>
<YaleFormSelect v-model="personNumber" :options="people" class="block w-full"
placeholder="Select a Person" />
<YaleButton @click="confirmSendCode(userCode.id)" class="w-full mt-3">Send Code</YaleButton>
</template>
</Modal>
</template>
@@ -1,82 +0,0 @@
<script setup lang='ts'>
import { UserCodeStatus, type YaleUserCode } from '~/types/yale';
import { type PropType } from 'vue';
const props = defineProps({
userCode: {
type: Object as PropType<YaleUserCode>,
required: true
}
});
const emit = defineEmits<{
(e: "show-code", id: number): void
(e: "update-code", id: number): void
(e: "clear-code", id: number): void
(e: "send-code", id: number): void
}>();
const handleShowCodeClick = () => {
// Emit the event to the parent component to handle
emit("show-code", props.userCode.id);
}
// Handle the update code button click
const handleUpdateCodeClick = () => {
// Emit the event to the parent component
emit("update-code", props.userCode.id);
}
// Handle the clear code button click
const handleClearCodeClick = () => {
// Emit the event to the parent component
emit("clear-code", props.userCode.id);
}
// Handle the send code button click
const handleSendCodeClick = () => {
// Emit the event to the parent component
emit("send-code", props.userCode.id);
}
const userCodeStatusDisplay = (status: UserCodeStatus): string => {
switch (status) {
case UserCodeStatus.AVAILABLE:
return 'Available';
case UserCodeStatus.ENABLED:
return 'Enabled';
case UserCodeStatus.DISABLED:
return 'Disabled';
default:
return 'Unknown';
}
}
</script>
<template>
<tr scope="row">
<td>
<template v-if="userCode.isHome">
{{ userCode.id }} (<IconHome />)
</template>
<template v-else>
{{ userCode.id }}
</template>
</td>
<td>{{ userCodeStatusDisplay(userCode.status) }}</td>
<td class="flex">
<YaleButton type="button" @click="handleShowCodeClick" :disabled="props.userCode.status !== UserCodeStatus.ENABLED">
<IconEye />
</YaleButton>
<YaleButton type="button" class="ml-2" @click="handleUpdateCodeClick">
<IconPencil />
</YaleButton>
<YaleButton type="button" class="ml-2" @click="handleSendCodeClick" :disabled="props.userCode.status !== UserCodeStatus.ENABLED" v-if="!props.userCode.isHome">
<IconSend />
</YaleButton>
<YaleButton type="button" class="ml-2" @click="handleClearCodeClick" :disabled="props.userCode.status !== UserCodeStatus.ENABLED" v-if="!props.userCode.isHome">
<IconTrash />
</YaleButton>
</td>
</tr>
</template>
@@ -1,7 +0,0 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"
class="w-6 h-6">
<path stroke-linecap="round" stroke-linejoin="round"
d="M3.98 8.223A10.477 10.477 0 0 0 1.934 12C3.226 16.338 7.244 19.5 12 19.5c.993 0 1.953-.138 2.863-.395M6.228 6.228A10.451 10.451 0 0 1 12 4.5c4.756 0 8.773 3.162 10.065 7.498a10.522 10.522 0 0 1-4.293 5.774M6.228 6.228 3 3m3.228 3.228 3.65 3.65m7.894 7.894L21 21m-3.228-3.228-3.65-3.65m0 0a3 3 0 1 0-4.243-4.243m4.242 4.242L9.88 9.88" />
</svg>
</template>
@@ -1,8 +0,0 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"
class="w-6 h-6">
<path stroke-linecap="round" stroke-linejoin="round"
d="M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z" />
<path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" />
</svg>
</template>
@@ -1,7 +0,0 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"
class="w-6 h-6 inline">
<path stroke-linecap="round" stroke-linejoin="round"
d="m2.25 12 8.954-8.955c.44-.439 1.152-.439 1.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21h4.125c.621 0 1.125-.504 1.125-1.125V9.75M8.25 21h8.25" />
</svg>
</template>
@@ -1,7 +0,0 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"
class="w-6 h-6">
<path stroke-linecap="round" stroke-linejoin="round"
d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L6.832 19.82a4.5 4.5 0 0 1-1.897 1.13l-2.685.8.8-2.685a4.5 4.5 0 0 1 1.13-1.897L16.863 4.487Zm0 0L19.5 7.125" />
</svg>
</template>
@@ -1,7 +0,0 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-send"
viewBox="0 0 24 24">
<path
d="M15.854.146a.5.5 0 0 1 .11.54l-5.819 14.547a.75.75 0 0 1-1.329.124l-3.178-4.995L.643 7.184a.75.75 0 0 1 .124-1.33L15.314.037a.5.5 0 0 1 .54.11ZM6.636 10.07l2.761 4.338L14.13 2.576zm6.787-8.201L1.591 6.602l4.339 2.76z" />
</svg>
</template>
@@ -1,7 +0,0 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"
class="w-6 h-6">
<path stroke-linecap="round" stroke-linejoin="round"
d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" />
</svg>
</template>
@@ -1,6 +0,0 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"
class="w-6 h-6">
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" />
</svg>
</template>
@@ -1,28 +0,0 @@
<script setup lang="ts">
import type { HTMLButtonTypes } from '~/types/html-input-types';
interface ButtonProps {
type?: HTMLButtonTypes
disabled?: boolean
}
const props = withDefaults(defineProps<ButtonProps>(), {
type: 'button',
disabled: false
})
const emit = defineEmits([
'click'
])
const handleClick = () => {
emit('click');
}
</script>
<template>
<button :type="props.type" :disabled="props.disabled" class="bg-stone-950 hover:bg-stone-900 p-2 rounded-md disabled:opacity-50 disabled:cursor-not-allowed"
@click="handleClick">
<slot></slot>
</button>
</template>
@@ -1,25 +0,0 @@
<script setup lang="ts">
import type { HTMLInputTypes } from '~/types/html-input-types';
const props = defineProps<{
type: HTMLInputTypes
placeholder: string
modelValue: string
}>();
const emit = defineEmits([
'update:modelValue'
])
const handleInput = (event: Event) => {
// If input is a text input, emit the value
if (props.type === 'text' || props.type === 'password') {
emit('update:modelValue', (event.target as HTMLInputElement).value);
}
}
</script>
<template>
<input class="bg-zinc-900 p-2 rounded-md" :type="props.type"
:value="props.modelValue" :placeholder="props.placeholder" @input="handleInput">
</template>~/types/html-input-types
@@ -1,27 +0,0 @@
<script setup lang="ts">
const props = defineProps<{
options: Array<{ label: string; value: string }>,
placeholder: string,
modelValue: string
}>();
const emit = defineEmits([
'update:modelValue'
]);
const handleSelect = (event: Event) => {
emit('update:modelValue', (event.target as HTMLSelectElement).value);
};
</script>
<template>
<select class="bg-zinc-900 p-2 rounded-md" :value="props.modelValue" @change="handleSelect">
<!-- Placeholder as the first option -->
<option value="" disabled selected>{{ props.placeholder }}</option>
<!-- Render options dynamically -->
<option v-for="option in props.options" :key="option.value" :value="option.value">
{{ option.label }}
</option>
</select>
</template>
@@ -1,25 +0,0 @@
<script setup lang="ts">
const props = defineProps<{
heading?: string;
}>();
</script>
<template>
<h2 v-if="props.heading" class="hr text-lg font-bold mb-2">{{ props.heading }}</h2>
<div class="rounded-md bg-zinc-800 p-2">
<slot></slot>
</div>
</template>
<style>
.hr {
display: inline-block;
}
.hr::after {
content: '';
display: block;
border-top: 2px solid theme('colors.slate.300');
margin-top: .1rem;
}
</style>
-5
View File
@@ -1,5 +0,0 @@
<template>
<div class="text-slate-300">
<slot />
</div>
</template>
-6
View File
@@ -1,6 +0,0 @@
<template>
<Navbar />
<div class="text-slate-300 container mx-auto px-4">
<slot />
</div>
</template>
@@ -1,9 +0,0 @@
const anonymousRoutes = ['/login', '/health'];
export default defineNuxtRouteMiddleware((to, from) => {
// If the route is not the login page and the user is not logged in then redirect to login
const authenticated = useCookie<boolean>('authenticated');
if (!anonymousRoutes.includes(to.path) && !(authenticated.value) ) {
return navigateTo('/login');
}
})
+4 -1
View File
@@ -1,7 +1,10 @@
// https://nuxt.com/docs/api/configuration/nuxt-config // https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({ export default defineNuxtConfig({
modules: [ '@nuxtjs/tailwindcss' ], modules: ['@nuxt/ui'],
css: ['~/assets/css/main.css'],
colorMode: { preference: 'dark', fallback: 'dark' },
devtools: { enabled: true }, devtools: { enabled: true },
compatibilityDate: '2025-07-15',
runtimeConfig: { runtimeConfig: {
public: { public: {
apiBaseUrl: 'https://localhost:7069' apiBaseUrl: 'https://localhost:7069'
+18 -7
View File
@@ -7,15 +7,26 @@
"dev": "nuxt dev", "dev": "nuxt dev",
"generate": "nuxt generate", "generate": "nuxt generate",
"preview": "nuxt preview", "preview": "nuxt preview",
"test": "vitest run",
"test:watch": "vitest",
"typecheck": "nuxt typecheck",
"postinstall": "nuxt prepare" "postinstall": "nuxt prepare"
}, },
"dependencies": { "dependencies": {
"@nuxt/devtools": "latest", "@iconify-json/lucide": "^1.2.155",
"@nuxtjs/tailwindcss": "^6.11.3", "@nuxt/ui": "^4.12.0",
"nuxt": "^3.9.1", "nuxt": "^4.6.4",
"vue": "^3.4.10", "tailwindcss": "^4.3.5",
"vue-router": "^4.2.5" "vue": "^3.5.45",
"vue-router": "^5.5.1"
}, },
"devDependencies": {}, "packageManager": "pnpm@12.6.0+sha512.3ef68f951cb111ac204b4a5a16f0b2ddf0da56a96e0413e81d855d9f0b55ef926714709028e1cd00c405c2c5fb7b9e8ec4dc46777c805d0373c2f2ff00fd20ec",
"packageManager": "pnpm@12.6.0+sha512.3ef68f951cb111ac204b4a5a16f0b2ddf0da56a96e0413e81d855d9f0b55ef926714709028e1cd00c405c2c5fb7b9e8ec4dc46777c805d0373c2f2ff00fd20ec" "devDependencies": {
"@nuxt/test-utils": "^4.4.0",
"@vue/test-utils": "^2.5.1",
"happy-dom": "^21.0.4",
"typescript": "^5.9.3",
"vitest": "^5.1.0",
"vue-tsc": "^3.3.14"
}
} }
-3
View File
@@ -1,3 +0,0 @@
<template>
<HealthCheck />
</template>
-5
View File
@@ -1,5 +0,0 @@
<template>
<YalePanel heading="User Code List">
<UserCodeList />
</YalePanel>
</template>
-11
View File
@@ -1,11 +0,0 @@
<script setup lang="ts">
definePageMeta({
layout: 'blank'
})
</script>
<template>
<div class="h-screen flex items-center justify-center w-11/12 md:w-auto mx-auto">
<LoginForm />
</div>
</template>
-5
View File
@@ -1,5 +0,0 @@
<template>
<YalePanel title="People">
<PeopleList />
</YalePanel>
</template>
+4238 -2971
View File
File diff suppressed because it is too large. Load diff
+2
View File
@@ -1,2 +1,4 @@
allowBuilds: allowBuilds:
esbuild: true esbuild: true
vue-demi: false
+66
View File
@@ -0,0 +1,66 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises } from '@vue/test-utils'
import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime'
import LoginForm from '~/components/LoginForm.vue'
const { api, navigateToMock } = vi.hoisted(() => ({
api: { get: vi.fn(), post: vi.fn(), delete: vi.fn() },
navigateToMock: vi.fn()
}))
mockNuxtImport('useApi', () => () => api)
mockNuxtImport('navigateTo', () => navigateToMock)
describe('LoginForm', () => {
beforeEach(() => {
api.post.mockReset()
navigateToMock.mockReset()
useCookie<boolean>('authenticated').value = false
})
it('disables the login button until a password is entered', async () => {
const wrapper = await mountSuspended(LoginForm)
const button = wrapper.find('button[type="submit"]')
expect(button.attributes('disabled')).toBeDefined()
await wrapper.find('input').setValue('secret')
expect(button.attributes('disabled')).toBeUndefined()
})
it('logs in with the password, sets the cookie and goes home', async () => {
api.post.mockResolvedValue({ success: true, data: true })
const wrapper = await mountSuspended(LoginForm)
await wrapper.find('input').setValue('pa"ss')
await wrapper.find('form').trigger('submit')
await flushPromises()
expect(api.post).toHaveBeenCalledWith('/api/Authentication/login', 'pa"ss')
expect(useCookie<boolean>('authenticated').value).toBe(true)
expect(navigateToMock).toHaveBeenCalledWith('/')
})
it('shows the error and stays on the page when the login fails', async () => {
api.post.mockResolvedValue({ success: false, error: 'Incorrect password.' })
const wrapper = await mountSuspended(LoginForm)
await wrapper.find('input').setValue('wrong')
await wrapper.find('form').trigger('submit')
await flushPromises()
expect(wrapper.text()).toContain('Incorrect password.')
expect(useCookie<boolean>('authenticated').value).toBe(false)
expect(navigateToMock).not.toHaveBeenCalled()
})
it('can reveal and hide the password', async () => {
const wrapper = await mountSuspended(LoginForm)
const input = wrapper.find('input')
expect(input.attributes('type')).toBe('password')
await wrapper.find('button[aria-label="Show password"]').trigger('click')
expect(input.attributes('type')).toBe('text')
await wrapper.find('button[aria-label="Hide password"]').trigger('click')
expect(input.attributes('type')).toBe('password')
})
})
+101
View File
@@ -0,0 +1,101 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
import PeopleList from '~/components/PeopleList.vue'
import { click, inBody, mountInApp, setInput, settle, submitForm } from './helpers'
const { api } = vi.hoisted(() => ({ api: { get: vi.fn(), post: vi.fn(), delete: vi.fn() } }))
mockNuxtImport('useApi', () => () => api)
const mountList = async () => {
const wrapper = await mountInApp(PeopleList)
await settle()
return wrapper
}
const openAddModal = async (wrapper: Awaited<ReturnType<typeof mountList>>) => {
const add = wrapper.findAll('button').find(b => b.text().includes('Add Person'))
await click(add!.element)
}
const fillAndSubmit = async (name: string, phone: string) => {
const [nameInput, phoneInput] = document.body.querySelectorAll<HTMLInputElement>('#add-person input')
await setInput(nameInput!, name)
await setInput(phoneInput!, phone)
await submitForm(inBody<HTMLFormElement>('#add-person')!)
}
describe('PeopleList', () => {
beforeEach(() => {
api.get.mockReset()
api.post.mockReset()
api.delete.mockReset()
api.get.mockResolvedValue({ success: true, data: [{ id: 1, name: 'Alex', phoneNumber: '+61400000001' }] })
document.body.innerHTML = ''
})
it('lists the people', async () => {
const wrapper = await mountList()
const row = wrapper.find('tbody tr')
expect(row.text()).toContain('Alex')
expect(row.text()).toContain('+61400000001')
})
it('shows an empty state', async () => {
api.get.mockResolvedValue({ success: true, data: [] })
const wrapper = await mountList()
expect(wrapper.text()).toContain('No people yet.')
})
it('requires a name and an international phone number before saving', async () => {
const wrapper = await mountList()
await openAddModal(wrapper)
await fillAndSubmit('', '0400 000 000')
expect(document.body.textContent).toContain('Name is required')
expect(document.body.textContent).toContain('Use international format')
expect(api.post).not.toHaveBeenCalled()
})
it('adds a person and shows them in the table', async () => {
api.post.mockResolvedValue({ success: true, data: { id: 2, name: 'Sam', phoneNumber: '+61400000002' } })
const wrapper = await mountList()
await openAddModal(wrapper)
await fillAndSubmit('Sam', '+61400000002')
expect(api.post).toHaveBeenCalledExactlyOnceWith('/api/People', { id: 0, name: 'Sam', phoneNumber: '+61400000002' })
expect(wrapper.findAll('tbody tr')).toHaveLength(2)
expect(wrapper.text()).toContain('Sam')
})
it('keeps the list unchanged when the API rejects the new person', async () => {
api.post.mockResolvedValue({ success: false, error: 'nope' })
const wrapper = await mountList()
await openAddModal(wrapper)
await fillAndSubmit('Sam', '+61400000002')
expect(wrapper.findAll('tbody tr')).toHaveLength(1)
})
it('deletes a person', async () => {
api.delete.mockResolvedValue({ success: true, data: { id: 1 } })
const wrapper = await mountList()
await click(wrapper.find('button[aria-label="Delete Alex"]').element)
expect(api.delete).toHaveBeenCalledExactlyOnceWith('/api/People/1')
expect(wrapper.text()).not.toContain('+61400000001')
})
it('keeps the person when the delete fails', async () => {
api.delete.mockResolvedValue({ success: false, error: 'Person not found.' })
const wrapper = await mountList()
await click(wrapper.find('button[aria-label="Delete Alex"]').element)
expect(wrapper.text()).toContain('Alex')
})
})
+135
View File
@@ -0,0 +1,135 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
import UserCodeList from '~/components/UserCodeList.vue'
import { UserCodeStatus } from '~/types/yale'
import { click, inBody, mountInApp, setInput, settle, submitForm } from './helpers'
const { api } = vi.hoisted(() => ({ api: { get: vi.fn(), post: vi.fn(), delete: vi.fn() } }))
mockNuxtImport('useApi', () => () => api)
const codes = [
{ id: 4, code: '9999', status: UserCodeStatus.ENABLED, isHome: true },
{ id: 2, code: '2222', status: UserCodeStatus.ENABLED, isHome: false },
{ id: 3, code: '', status: UserCodeStatus.AVAILABLE, isHome: false }
]
const mountList = async () => {
const wrapper = await mountInApp(UserCodeList)
await settle()
return wrapper
}
const rows = (wrapper: Awaited<ReturnType<typeof mountList>>) => wrapper.findAll('tbody tr')
const buttonLabels = (row: { findAll: (s: string) => { attributes: (n: string) => string | undefined }[] }) =>
row.findAll('button').map(b => b.attributes('aria-label'))
describe('UserCodeList', () => {
beforeEach(() => {
api.get.mockReset()
api.post.mockReset()
api.get.mockImplementation(async (path: string) =>
path === '/api/Yale/codes'
? { success: true, data: structuredClone(codes) }
: { success: true, data: [{ id: 1, name: 'Alex', phoneNumber: '+61400000001' }] })
api.post.mockResolvedValue({ success: true, data: true })
document.body.innerHTML = ''
})
it('lists the codes sorted by id with their status', async () => {
const wrapper = await mountList()
const r = rows(wrapper)
expect(r).toHaveLength(3)
expect(r.map(x => x.findAll('td')[0]!.text())).toEqual(['2', '3', '4'])
expect(r[0]!.text()).toContain('Enabled')
expect(r[1]!.text()).toContain('Available')
})
it('only offers show and edit for the home code, and marks it with the home icon', async () => {
const wrapper = await mountList()
const home = rows(wrapper)[2]!
expect(buttonLabels(home)).toEqual(['Show code', 'Edit code'])
expect(home.find('[aria-label="Home code"]').exists()).toBe(true)
})
it('disables show, send and delete for an available (unset) code', async () => {
const wrapper = await mountList()
const available = rows(wrapper)[1]!
for (const label of ['Show code', 'Send code', 'Delete code']) {
expect(available.find(`button[aria-label="${label}"]`).attributes('disabled')).toBeDefined()
}
expect(available.find('button[aria-label="Edit code"]').attributes('disabled')).toBeUndefined()
})
it('shows the code in a modal', async () => {
const wrapper = await mountList()
await click(rows(wrapper)[0]!.find('button[aria-label="Show code"]').element)
expect(document.body.textContent).toContain('User Code #2')
expect(document.body.textContent).toContain('2222')
})
it('rejects a code that is not 4-6 digits without calling the API', async () => {
const wrapper = await mountList()
await click(rows(wrapper)[0]!.find('button[aria-label="Edit code"]').element)
await setInput(inBody<HTMLInputElement>('input')!, '12')
await submitForm(inBody<HTMLFormElement>('#edit-code')!)
expect(document.body.textContent).toContain('Code must be 4, 5 or 6 digits long')
expect(api.post).not.toHaveBeenCalled()
})
it('updates a code through the API and reflects it in the table', async () => {
const wrapper = await mountList()
await click(rows(wrapper)[1]!.find('button[aria-label="Edit code"]').element) // available code #3
await setInput(inBody<HTMLInputElement>('input')!, '123456')
await submitForm(inBody<HTMLFormElement>('#edit-code')!)
expect(api.post).toHaveBeenCalledExactlyOnceWith('/api/Yale/code/3', '123456')
expect(rows(wrapper)[1]!.text()).toContain('Enabled')
})
it('warns before editing the home code', async () => {
const wrapper = await mountList()
await click(rows(wrapper)[2]!.find('button[aria-label="Edit code"]').element)
expect(document.body.textContent).toContain('You are about to edit the home code')
})
it('does not change the table when the API rejects the update', async () => {
api.post.mockResolvedValue({ success: false, error: 'An error occurred setting the code.' })
const wrapper = await mountList()
await click(rows(wrapper)[1]!.find('button[aria-label="Edit code"]').element)
await setInput(inBody<HTMLInputElement>('input')!, '4321')
await submitForm(inBody<HTMLFormElement>('#edit-code')!)
expect(rows(wrapper)[1]!.text()).toContain('Available')
})
it('deletes a code after confirmation and marks it available', async () => {
const wrapper = await mountList()
await click(rows(wrapper)[0]!.find('button[aria-label="Delete code"]').element) // code #2
expect(document.body.textContent).toContain('Are you sure you want to delete this code?')
expect(api.post).not.toHaveBeenCalled()
const confirm = [...document.body.querySelectorAll('button')].find(b => b.textContent?.trim() === 'Delete Code')
await click(confirm ?? null)
expect(api.post).toHaveBeenCalledExactlyOnceWith('/api/Yale/code/2/status')
expect(rows(wrapper)[0]!.text()).toContain('Available')
})
it('keeps the send button disabled until a person is chosen', async () => {
const wrapper = await mountList()
await click(rows(wrapper)[0]!.find('button[aria-label="Send code"]').element)
const send = [...document.body.querySelectorAll('button')].find(b => b.textContent?.trim() === 'Send Code')
expect(send?.hasAttribute('disabled')).toBe(true)
})
})
@@ -0,0 +1,47 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
import middleware from '~/middleware/authentication.global'
// Returning false aborts the navigation. (Returning a path would make the real router follow it, and
// since this mock also applies to the app's own startup navigation, that could redirect forever.)
const { navigateToMock } = vi.hoisted(() => ({ navigateToMock: vi.fn(() => false) }))
mockNuxtImport('navigateTo', () => navigateToMock)
// The middleware only reads `to.path`
const run = (path: string) => (middleware as (to: unknown, from: unknown) => unknown)({ path }, { path: '/' })
describe('authentication middleware', () => {
describe('when logged out', () => {
beforeEach(() => {
useCookie<boolean>('authenticated').value = false
navigateToMock.mockClear()
})
it.each(['/', '/people'])('redirects %s to the login page', (path) => {
run(path)
expect(navigateToMock).toHaveBeenCalledExactlyOnceWith('/login')
})
it.each(['/login', '/health'])('allows anonymous access to %s', (path) => {
expect(run(path)).toBeUndefined()
expect(navigateToMock).not.toHaveBeenCalled()
})
})
describe('when logged in', () => {
beforeEach(() => {
useCookie<boolean>('authenticated').value = true
navigateToMock.mockClear()
})
it.each(['/', '/people', '/health'])('allows %s', (path) => {
expect(run(path)).toBeUndefined()
expect(navigateToMock).not.toHaveBeenCalled()
})
it('skips the login page', () => {
run('/login')
expect(navigateToMock).toHaveBeenCalledExactlyOnceWith('/')
})
})
})
+37
View File
@@ -0,0 +1,37 @@
import { expect } from 'vitest'
import { defineComponent, h, nextTick, type Component } from 'vue'
import { flushPromises } from '@vue/test-utils'
import { mountSuspended } from '@nuxt/test-utils/runtime'
import { UApp } from '#components'
/** Mounts a component inside <UApp>, which modals and toasts need. */
export const mountInApp = (component: Component) =>
mountSuspended(defineComponent({ render: () => h(UApp, null, { default: () => h(component) }) }))
/** Lets promises, reactivity and (async) form validation settle. */
export const settle = async () => {
for (let i = 0; i < 4; i++) {
await flushPromises()
await nextTick()
}
}
/** Modals render in a portal, so query the whole document. */
export const inBody = <T extends Element = HTMLElement>(selector: string) => document.body.querySelector<T>(selector)
export const setInput = async (input: HTMLInputElement, value: string) => {
input.value = value
input.dispatchEvent(new Event('input', { bubbles: true }))
await settle()
}
export const submitForm = async (form: HTMLFormElement) => {
form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))
await settle()
}
export const click = async (el: Element | null) => {
expect(el, 'element to click').not.toBeNull()
;(el as HTMLElement).click()
await settle()
}
+98
View File
@@ -0,0 +1,98 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { mockNuxtImport, registerEndpoint } from '@nuxt/test-utils/runtime'
import { createError, defineEventHandler, getHeader, readBody, setResponseStatus } from 'h3'
import { useApi } from '~/composables/useApi'
const { navigateToMock } = vi.hoisted(() => ({ navigateToMock: vi.fn() }))
mockNuxtImport('navigateTo', () => navigateToMock)
// Each test registers its own endpoint, with an empty base URL (see vitest.config.ts) so requests hit it directly
const respond = (path: string, status: number, body: unknown, method: 'GET' | 'POST' | 'DELETE' = 'GET') =>
registerEndpoint(path, {
method,
handler: defineEventHandler((event) => {
setResponseStatus(event, status)
return body
})
})
describe('useApi', () => {
beforeEach(() => {
navigateToMock.mockReset()
useCookie<boolean>('authenticated').value = true
})
it('returns the API response on success', async () => {
respond('/api/test/ok', 200, { success: true, data: [1, 2] })
expect(await useApi().get<number[]>('/api/test/ok')).toEqual({ success: true, data: [1, 2] })
})
it('JSON-encodes bare string bodies so quotes and backslashes survive', async () => {
const password = 'pa"ss\\word'
let received: unknown
let contentType: string | undefined
registerEndpoint('/api/test/echo', {
method: 'POST',
handler: defineEventHandler(async (event) => {
contentType = getHeader(event, 'content-type')
received = await readBody(event)
return { success: true }
})
})
await useApi().post('/api/test/echo', password)
expect(contentType).toContain('application/json')
expect(received).toBe(password)
})
it('sends DELETE requests', async () => {
respond('/api/test/delete', 200, { success: true, data: { id: 3 } }, 'DELETE')
expect((await useApi().delete('/api/test/delete')).success).toBe(true)
})
it('passes through the API error message for failed requests', async () => {
respond('/api/test/bad', 400, { success: false, error: 'The code must be numeric.' }, 'POST')
const result = await useApi().post('/api/test/bad', 'abcd')
expect(result).toEqual({ success: false, error: 'The code must be numeric.' })
expect(navigateToMock).not.toHaveBeenCalled()
})
it('does not treat a wrong-password 401 as an expired session', async () => {
respond('/api/test/login', 401, { success: false, error: 'Incorrect password.' }, 'POST')
const result = await useApi().post('/api/test/login', 'nope')
expect(result.error).toBe('Incorrect password.')
expect(navigateToMock).not.toHaveBeenCalled()
expect(useCookie<boolean>('authenticated').value).toBe(true)
})
it('sends the user to the login page when the session has expired (empty 401)', async () => {
registerEndpoint('/api/test/expired', () => {
throw createError({ statusCode: 401, data: undefined })
})
const result = await useApi().get('/api/test/expired')
expect(result.success).toBe(false)
expect(result.error).toMatch(/session has expired/i)
expect(navigateToMock).toHaveBeenCalledWith('/login')
expect(useCookie<boolean>('authenticated').value).toBe(false)
})
it('surfaces rate limiting (429) messages', async () => {
respond('/api/test/limited', 429, { success: false, error: 'Too many login attempts.' }, 'POST')
expect((await useApi().post('/api/test/limited', 'x')).error).toBe('Too many login attempts.')
})
it('falls back to a generic message when the server cannot be reached', async () => {
// Nothing is registered at this path and the request is aborted by the network layer
const result = await useApi().get('http://127.0.0.1:1/unreachable')
expect(result).toEqual({ success: false, error: 'Unable to reach the server.' })
expect(navigateToMock).not.toHaveBeenCalled()
})
})
@@ -1,3 +0,0 @@
export type HTMLInputTypes = 'text' | 'password' | 'email' | 'number' | 'tel' | 'url' | 'search' | 'date' | 'time' | 'datetime-local' | 'month' | 'week' | 'color';
export type HTMLButtonTypes = 'submit' | 'reset' | 'button';
+20
View File
@@ -0,0 +1,20 @@
import { defineVitestConfig } from '@nuxt/test-utils/config'
export default defineVitestConfig({
test: {
environment: 'nuxt',
include: ['test/**/*.test.ts'],
// Booting the Nuxt environment can be slow on a cold start (and in CI)
hookTimeout: 60_000,
testTimeout: 30_000,
environmentOptions: {
nuxt: {
domEnvironment: 'happy-dom',
// Empty base URL so $fetch calls hit endpoints registered with registerEndpoint()
overrides: {
runtimeConfig: { public: { apiBaseUrl: '' } }
}
}
}
}
})
Binary file not shown.

Before

Width:  |  Height:  |  Size: 128 KiB

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 124 KiB

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 128 KiB

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 75 KiB

After

Width:  |  Height:  |  Size: 37 KiB