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
This commit is contained in:
LiamPietralla committed 2026-11-16 12:23:31 +11:00
1 parent 768bcc90e4
commit d0425c8cb2
38 files changed
+189 -487

No files matched your search

@@ -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,54 +18,60 @@ 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))
{ {
// Check if the password is correct logger.LogError("No authentication password has been configured, refusing all logins.");
if (password != authenticationOptions.Value.Password) return StatusCode(StatusCodes.Status500InternalServerError, new ApiResponse("Authentication is not configured."));
{
return Unauthorized(new ApiResponse("Incorrect password."));
}
// Log the user in
List<Claim> claims = new()
{
new Claim(ClaimTypes.Name, "YaleAccess")
};
ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal claimsPrincipal = new(claimsIdentity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
// Return the response
return Ok(new ApiResponse(true));
} }
catch(Exception ex)
// Check if the password is correct
if (!PasswordMatches(password, expectedPassword))
{ {
logger.LogError(ex, "An error occurred logging in."); logger.LogWarning("Failed login attempt from {RemoteIp}.", HttpContext.Connection.RemoteIpAddress);
return BadRequest(new ApiResponse("An error occurred logging in.")); return Unauthorized(new ApiResponse("Incorrect password."));
} }
// Log the user in
List<Claim> claims = new()
{
new Claim(ClaimTypes.Name, "YaleAccess")
};
ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal claimsPrincipal = new(claimsIdentity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
// Return the response
return Ok(new ApiResponse(true));
} }
[HttpPost("logout")] [HttpPost("logout")]
[AllowAnonymous] [AllowAnonymous]
public async Task<IActionResult> Logout() public async Task<IActionResult> Logout()
{ {
try // Sign the user out
{ await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
// Sign the user out
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok(new ApiResponse(true)); return Ok(new ApiResponse(true));
} }
catch (Exception ex)
{ /// <summary>
logger.LogError(ex, "An error occured logging out."); /// Compares the passwords in constant time (by comparing hashes, so differing lengths don't leak either).
return BadRequest(new ApiResponse("An error occured logging out.")); /// </summary>
} private static bool PasswordMatches(string? provided, string expected)
{
byte[] providedHash = SHA256.HashData(Encoding.UTF8.GetBytes(provided ?? string.Empty));
byte[] expectedHash = SHA256.HashData(Encoding.UTF8.GetBytes(expected));
return CryptographicOperations.FixedTimeEquals(providedHash, expectedHash);
} }
} }
} }
@@ -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
{ List<Person> people = await context.People.ToListAsync();
// Return all people return Ok(new ApiResponse(people));
List<Person> people = await context.People.ToListAsync();
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)
await context.AddAsync(newPerson);
await context.SaveChangesAsync();
// Return the newly created person
return Ok(new ApiResponse(newPerson));
}
catch (Exception ex)
{ {
logger.LogError(ex, "An error occured creating the person."); return BadRequest(new ApiResponse("The name is required and must be 100 characters or fewer."));
return BadRequest(new ApiResponse("An error occured creating the person."));
} }
if (!PhoneNumberRegex().IsMatch(phoneNumber))
{
return BadRequest(new ApiResponse("The phone number must be in international format, e.g. +61400000000."));
}
// Create a new person and add them
Person newPerson = new() { Name = name, PhoneNumber = phoneNumber };
await context.AddAsync(newPerson);
await context.SaveChangesAsync();
// Return the newly created person
return Ok(new ApiResponse(newPerson));
} }
[HttpDelete("{id}")] [HttpDelete("{id}")]
public async Task<IActionResult> DeletePerson([FromRoute] int id) public async Task<IActionResult> DeletePerson([FromRoute] int id)
{ {
try // Ensure the person exists
Person? person = await context.People.FindAsync(id);
if (person is null)
{ {
// Ensure the person exists return NotFound(new ApiResponse("Person not found."));
Person person = await context.People.FindAsync(id) ?? throw new Exception("Person not found.");
// Remove the person
context.Remove(person);
await context.SaveChangesAsync();
// Return the newly removed 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."));
} }
// Remove the person
context.Remove(person);
await context.SaveChangesAsync();
// Return the removed person
return Ok(new ApiResponse(person));
} }
} }
} }
+54 -86
View File
@@ -23,119 +23,87 @@ namespace YaleAccess.Controllers
[HttpGet("codes")] [HttpGet("codes")]
public async Task<IActionResult> GetUserCodes() public async Task<IActionResult> GetUserCodes()
{ {
try // Get the home code first
YaleUserCode homeCode = await yaleAccessor.GetCodeInformationAsync(codeOptions.Value.Home);
homeCode.IsHome = true;
// Get the guest codes
List<YaleUserCode> guestCodes = new();
foreach (int code in Enumerable.Range(codeOptions.Value.GuestCodeRangeStart, codeOptions.Value.GuestCodeRangeCount))
{ {
// Get the home code first guestCodes.Add(await yaleAccessor.GetCodeInformationAsync(code));
YaleUserCode homeCode = await yaleAccessor.GetCodeInformationAsync(codeOptions.Value.Home);
homeCode.IsHome = true;
// Get the guest codes
List<YaleUserCode> guestCodes = new();
foreach (int code in Enumerable.Range(codeOptions.Value.GuestCodeRangeStart, codeOptions.Value.GuestCodeRangeCount))
{
guestCodes.Add(await yaleAccessor.GetCodeInformationAsync(code));
}
// Add the home code to the list
guestCodes.Add(homeCode);
// Return the codes
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."));
} }
// Add the home code to the list
guestCodes.Add(homeCode);
// Return the codes
return Ok(new ApiResponse(guestCodes));
} }
[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
string validCode = YaleAccessor.ValidateCode(newCode);
if (validCode != string.Empty)
{ {
// First validate the user code return BadRequest(new ApiResponse(validCode));
string validCode = YaleAccessor.ValidateCode(newCode);
if (validCode != string.Empty)
{
return BadRequest(new ApiResponse(validCode));
}
// Set the new code
bool result = await yaleAccessor.SetUserCode(id, newCode);
// Return the result
if (result)
{
logger.LogInformation("Updated code for user {id} to {code}", id, newCode);
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)
// Set the new code (the code itself is never logged)
bool result = await yaleAccessor.SetUserCode(id, newCode);
if (!result)
{ {
logger.LogError(ex, "An error occurred setting the code."); logger.LogWarning("Failed to update code for user {Id}", id);
return BadRequest(new ApiResponse("An error occurred setting the code.")); 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));
} }
[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
string validCode = YaleAccessor.ValidateClearCode(id, codeOptions.Value.Home);
if (validCode != string.Empty)
{ {
// First validate the user code return BadRequest(new ApiResponse(validCode));
string validCode = YaleAccessor.ValidateClearCode(id, codeOptions.Value.Home);
if (validCode != string.Empty)
{
return BadRequest(new ApiResponse(validCode));
}
// Set the available status
bool result = await yaleAccessor.SetCodeAsAvailable(id);
// Return the result
if (result)
{
logger.LogInformation("Updated code status for user {id} to available", id);
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)
// Set the available status
bool result = await yaleAccessor.SetCodeAsAvailable(id);
if (!result)
{ {
logger.LogError(ex, "An error occurred setting the code status."); logger.LogWarning("Failed to update code status for user {Id} to available", id);
return BadRequest(new ApiResponse("An error occurred setting the code status.")); 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));
} }
[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
{ YaleUserCode userCode = await yaleAccessor.GetCodeInformationAsync(id);
// Get the user code
YaleUserCode userCode = await yaleAccessor.GetCodeInformationAsync(id);
// Send the code via SMS to the phone number // There is nothing to send if the code isn't set
await smsService.SendCodeViaSMSAsync(userCode.Code, phoneNumber); if (string.IsNullOrEmpty(userCode.Code))
// Return success
return Ok(new ApiResponse(true));
}
catch (Exception ex)
{ {
logger.LogError(ex, "An error occurred sending the code."); return BadRequest(new ApiResponse("This code is not set, so it cannot be sent."));
return BadRequest(new ApiResponse("An error occurred sending the code."));
} }
// Send the code via SMS to the phone number
await smsService.SendCodeViaSMSAsync(userCode.Code, phoneNumber);
// Return success
return Ok(new ApiResponse(true));
} }
} }
} }
+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.";
} }
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
-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>
@@ -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,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>
@@ -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';