Migrate frontend to Nuxt UI, harden backend, add tests #3
No files matched your search
@@ -1,13 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
useHead({
|
||||
bodyAttrs: {
|
||||
class: 'bg-black'
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<NuxtLayout>
|
||||
<NuxtPage />
|
||||
</NuxtLayout>
|
||||
<UApp>
|
||||
<NuxtLayout>
|
||||
<NuxtPage />
|
||||
</NuxtLayout>
|
||||
</UApp>
|
||||
</template>
|
||||
@@ -0,0 +1,2 @@
|
||||
@import "tailwindcss";
|
||||
@import "@nuxt/ui";
|
||||
@@ -1,26 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
|
||||
const runtimeConfig = useRuntimeConfig();
|
||||
const healthResult = ref<string>("Fetching health check...");
|
||||
const config = useRuntimeConfig()
|
||||
const healthResult = ref('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;
|
||||
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 class="text-slate-300">
|
||||
<h1>Health Check</h1>
|
||||
<div>
|
||||
<h1 class="text-xl font-semibold">Health Check</h1>
|
||||
<p>{{ healthResult }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,67 +1,61 @@
|
||||
<script setup lang='ts'>
|
||||
import { ref } from 'vue';
|
||||
import { type ApiResponse } from '~/types/api-response';
|
||||
<script setup lang="ts">
|
||||
const api = useApi()
|
||||
const authenticated = useCookie<boolean>('authenticated')
|
||||
|
||||
const password = ref('');
|
||||
const passwordError = ref('');
|
||||
const authenticated = useCookie<boolean>('authenticated');
|
||||
const runtimeConfig = useRuntimeConfig();
|
||||
const password = ref('')
|
||||
const showPassword = ref(false)
|
||||
const error = ref('')
|
||||
const loading = ref(false)
|
||||
|
||||
const handleLogin = async (event: Event) => {
|
||||
// Prevent default form submission
|
||||
event.preventDefault();
|
||||
const handleLogin = async () => {
|
||||
error.value = ''
|
||||
loading.value = true
|
||||
|
||||
// Reset the error
|
||||
passwordError.value = '';
|
||||
const response = await api.post<boolean>('/api/Authentication/login', password.value)
|
||||
loading.value = false
|
||||
|
||||
// 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';
|
||||
}
|
||||
if (response.success) {
|
||||
authenticated.value = true
|
||||
await navigateTo('/')
|
||||
} else {
|
||||
error.value = response.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>
|
||||
<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>
|
||||
|
||||
<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>
|
||||
<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>
|
||||
|
||||
<style>
|
||||
.hr {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.hr::after {
|
||||
content: '';
|
||||
display: block;
|
||||
border-top: 2px solid theme('colors.slate.300');
|
||||
margin-top: .1rem;
|
||||
}
|
||||
</style>
|
||||
@@ -1,132 +1,109 @@
|
||||
<script setup lang="ts">
|
||||
import { type Person } from '@/types/yale';
|
||||
import { onMounted, ref } from 'vue';
|
||||
import type { ApiResponse } from '~/types/api-response';
|
||||
import type { FormError, TableColumn } from '@nuxt/ui'
|
||||
import type { Person } from '~/types/yale'
|
||||
|
||||
const people = ref([] as Person[]);
|
||||
const person = ref({ id: 0, name: '', phoneNumber: '' } as Person);
|
||||
const loading = ref(true);
|
||||
const runtimeConfig = useRuntimeConfig();
|
||||
const api = useApi()
|
||||
const toast = useToast()
|
||||
|
||||
const addModal = ref(false);
|
||||
const people = ref<Person[]>([])
|
||||
const loading = ref(true)
|
||||
const saving = ref(false)
|
||||
const addOpen = ref(false)
|
||||
const newPerson = reactive({ name: '', phoneNumber: '' })
|
||||
|
||||
// When the component is mounted, load the people
|
||||
onMounted(async () => {
|
||||
await loadPeople();
|
||||
loading.value = false;
|
||||
});
|
||||
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 () => {
|
||||
// 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;
|
||||
loading.value = true
|
||||
const response = await api.get<Person[]>('/api/People')
|
||||
if (response.success) {
|
||||
people.value = response.data ?? []
|
||||
} else {
|
||||
alert(apiResponse.error ?? 'An error occurred');
|
||||
toast.add({ title: 'Could not load people', description: response.error, color: 'error' })
|
||||
}
|
||||
|
||||
// Close the modal and reset the person
|
||||
loading.value = false;
|
||||
person.value = { id: 0, name: '', phoneNumber: '' };
|
||||
|
||||
// Set the loading status
|
||||
loading.value = false;
|
||||
loading.value = false
|
||||
}
|
||||
|
||||
const handleDeletePerson = async (id: number) => {
|
||||
// Set the loading status
|
||||
loading.value = true;
|
||||
onMounted(loadPeople)
|
||||
|
||||
// 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');
|
||||
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
|
||||
}
|
||||
|
||||
// Set the loading status
|
||||
loading.value = false;
|
||||
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>
|
||||
<!-- 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>
|
||||
<div class="flex justify-end mb-4">
|
||||
<UButton icon="i-lucide-user-plus" @click="addOpen = true">Add Person</UButton>
|
||||
</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>
|
||||
<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>
|
||||
@@ -1,300 +1,228 @@
|
||||
<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';
|
||||
<script setup lang="ts">
|
||||
import type { TableColumn } from '@nuxt/ui'
|
||||
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();
|
||||
type ModalKind = 'show' | 'edit' | 'clear' | 'send'
|
||||
|
||||
// Modals
|
||||
const showModal = ref(false);
|
||||
const editModal = ref(false);
|
||||
const clearModal = ref(false);
|
||||
const sendModal = ref(false);
|
||||
const api = useApi()
|
||||
const toast = useToast()
|
||||
|
||||
// Form Fields
|
||||
const newCode = ref('');
|
||||
const newCodeError = ref('');
|
||||
const userCodes = ref<YaleUserCode[]>([])
|
||||
const people = ref<{ label: string, value: string }[]>([])
|
||||
const loading = ref(true)
|
||||
const saving = ref(false)
|
||||
|
||||
// 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;
|
||||
});
|
||||
// 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 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' });
|
||||
const columns: TableColumn<YaleUserCode>[] = [
|
||||
{ accessorKey: 'id', header: 'Code ID' },
|
||||
{ accessorKey: 'status', header: 'Status' },
|
||||
{ id: 'actions', header: 'Actions' }
|
||||
]
|
||||
|
||||
// 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 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 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 modalOpen = (kind: ModalKind) => activeModal.value === kind
|
||||
const setModalOpen = (open: boolean) => {
|
||||
if (!open) activeModal.value = null
|
||||
}
|
||||
|
||||
const confirmUpdateCode = async (id: number, code: string) => {
|
||||
// Reset the error
|
||||
newCodeError.value = '';
|
||||
const loadAll = async () => {
|
||||
loading.value = true
|
||||
const [codes, peopleResponse] = await Promise.all([
|
||||
api.get<YaleUserCode[]>('/api/Yale/codes'),
|
||||
api.get<Person[]>('/api/People')
|
||||
])
|
||||
|
||||
// Validate the new code first
|
||||
if (!/^\d{4,6}$/.test(code)) {
|
||||
newCodeError.value = 'Code must be 4, 5 or 6 digits long';
|
||||
return;
|
||||
}
|
||||
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' })
|
||||
}
|
||||
|
||||
// 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;
|
||||
if (peopleResponse.success) {
|
||||
people.value = (peopleResponse.data ?? []).map(x => ({ label: x.name, value: x.phoneNumber }))
|
||||
}
|
||||
loading.value = false
|
||||
}
|
||||
|
||||
const confirmClearCode = async (id: number) => {
|
||||
// Set the loading status
|
||||
loading.value = true;
|
||||
onMounted(loadAll)
|
||||
|
||||
// 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 openModal = (kind: ModalKind, code: YaleUserCode) => {
|
||||
activeCode.value = code
|
||||
newCode.value = ''
|
||||
newCodeError.value = ''
|
||||
personNumber.value = undefined
|
||||
activeModal.value = kind
|
||||
}
|
||||
|
||||
const handleShowCode = (id: number) => {
|
||||
// Get the user code to show
|
||||
const code = userCodes.value.find(x => x.id === id);
|
||||
const confirmUpdateCode = async () => {
|
||||
const code = activeCode.value
|
||||
if (!code) return
|
||||
newCodeError.value = ''
|
||||
|
||||
// If the code is not found then show an error to the user
|
||||
if (!code) {
|
||||
alert('Code not found');
|
||||
return;
|
||||
}
|
||||
if (!/^\d{4,6}$/.test(newCode.value)) {
|
||||
newCodeError.value = 'Code must be 4, 5 or 6 digits long'
|
||||
return
|
||||
}
|
||||
|
||||
// Set the user code to show
|
||||
userCode.value = code;
|
||||
saving.value = true
|
||||
const response = await api.post<boolean>(`/api/Yale/code/${code.id}`, newCode.value)
|
||||
saving.value = false
|
||||
|
||||
// Show the show-modal
|
||||
showModal.value = true;
|
||||
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 handleUpdateCode = (id: number) => {
|
||||
// Get the user code to update
|
||||
const code = userCodes.value.find(x => x.id === id);
|
||||
const confirmClearCode = async () => {
|
||||
const code = activeCode.value
|
||||
if (!code) return
|
||||
|
||||
// If the code is not found then show an error to the user
|
||||
if (!code) {
|
||||
alert('Code not found');
|
||||
return;
|
||||
}
|
||||
saving.value = true
|
||||
const response = await api.post<boolean>(`/api/Yale/code/${code.id}/status`)
|
||||
saving.value = false
|
||||
|
||||
// Set the user code to update
|
||||
userCode.value = code;
|
||||
|
||||
// Show the edit-modal
|
||||
editModal.value = true;
|
||||
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 handleClearCode = (id: number) => {
|
||||
// Get the user code to clear
|
||||
const code = userCodes.value.find(x => x.id === id);
|
||||
const confirmSendCode = async () => {
|
||||
const code = activeCode.value
|
||||
if (!code || !personNumber.value) return
|
||||
|
||||
// If the code is not found then show an error to the user
|
||||
if (!code) {
|
||||
alert('Code not found');
|
||||
return;
|
||||
}
|
||||
saving.value = true
|
||||
const response = await api.post<boolean>(`/api/Yale/code/${code.id}/send`, personNumber.value)
|
||||
saving.value = false
|
||||
|
||||
// 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;
|
||||
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>
|
||||
<!-- 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>
|
||||
<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>
|
||||
|
||||
<!-- Show modal -->
|
||||
<Modal v-if="showModal" @close="showModal = false">
|
||||
<template #title>
|
||||
User Code # {{ userCode.id }}
|
||||
</template>
|
||||
<template #default>
|
||||
Code: {{ userCode.code }}
|
||||
</template>
|
||||
</Modal>
|
||||
<template #status-cell="{ row }">
|
||||
<UBadge
|
||||
:color="statusDisplay[row.original.status]?.color ?? 'neutral'"
|
||||
variant="subtle"
|
||||
>
|
||||
{{ statusDisplay[row.original.status]?.label ?? 'Unknown' }}
|
||||
</UBadge>
|
||||
</template>
|
||||
|
||||
<!-- 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>
|
||||
<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>
|
||||
|
||||
<!-- 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>
|
||||
<!-- 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>
|
||||
|
||||
<!-- 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>
|
||||
<!-- 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')
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<div class="text-slate-300">
|
||||
<slot />
|
||||
</div>
|
||||
<div class="min-h-screen flex items-center justify-center p-4">
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,6 +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>
|
||||
<Navbar />
|
||||
<div class="text-slate-300 container mx-auto px-4">
|
||||
<slot />
|
||||
</div>
|
||||
<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>
|
||||
@@ -1,9 +1,15 @@
|
||||
const anonymousRoutes = ['/login', '/health'];
|
||||
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');
|
||||
}
|
||||
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('/')
|
||||
}
|
||||
})
|
||||
@@ -1,3 +1,5 @@
|
||||
<template>
|
||||
<UContainer class="py-6">
|
||||
<HealthCheck />
|
||||
</UContainer>
|
||||
</template>
|
||||
@@ -1,5 +1,8 @@
|
||||
<template>
|
||||
<YalePanel heading="User Code List">
|
||||
<UserCodeList />
|
||||
</YalePanel>
|
||||
<UCard>
|
||||
<template #header>
|
||||
<h2 class="text-lg font-semibold">User Codes</h2>
|
||||
</template>
|
||||
<UserCodeList />
|
||||
</UCard>
|
||||
</template>
|
||||
@@ -5,7 +5,5 @@ definePageMeta({
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="h-screen flex items-center justify-center w-11/12 md:w-auto mx-auto">
|
||||
<LoginForm />
|
||||
</div>
|
||||
<LoginForm />
|
||||
</template>
|
||||
@@ -1,5 +1,8 @@
|
||||
<template>
|
||||
<YalePanel title="People">
|
||||
<UCard>
|
||||
<template #header>
|
||||
<h2 class="text-lg font-semibold">People</h2>
|
||||
</template>
|
||||
<PeopleList />
|
||||
</YalePanel>
|
||||
</UCard>
|
||||
</template>
|
||||
@@ -1,7 +1,10 @@
|
||||
// https://nuxt.com/docs/api/configuration/nuxt-config
|
||||
export default defineNuxtConfig({
|
||||
modules: [ '@nuxtjs/tailwindcss' ],
|
||||
modules: ['@nuxt/ui'],
|
||||
css: ['~/assets/css/main.css'],
|
||||
colorMode: { preference: 'dark', fallback: 'dark' },
|
||||
devtools: { enabled: true },
|
||||
compatibilityDate: '2025-07-15',
|
||||
runtimeConfig: {
|
||||
public: {
|
||||
apiBaseUrl: 'https://localhost:7069'
|
||||
|
||||
@@ -7,15 +7,26 @@
|
||||
"dev": "nuxt dev",
|
||||
"generate": "nuxt generate",
|
||||
"preview": "nuxt preview",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"typecheck": "nuxt typecheck",
|
||||
"postinstall": "nuxt prepare"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nuxt/devtools": "latest",
|
||||
"@nuxtjs/tailwindcss": "^6.11.3",
|
||||
"nuxt": "^3.9.1",
|
||||
"vue": "^3.4.10",
|
||||
"vue-router": "^4.2.5"
|
||||
"@iconify-json/lucide": "^1.2.155",
|
||||
"@nuxt/ui": "^4.12.0",
|
||||
"nuxt": "^4.6.4",
|
||||
"tailwindcss": "^4.3.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"
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,4 @@
|
||||
allowBuilds:
|
||||
esbuild: true
|
||||
vue-demi: false
|
||||
|
||||
|
Before Width: | Height: | Size: 128 KiB After Width: | Height: | Size: 88 KiB |
|
Before Width: | Height: | Size: 124 KiB After Width: | Height: | Size: 81 KiB |
|
Before Width: | Height: | Size: 128 KiB After Width: | Height: | Size: 96 KiB |
|
Before Width: | Height: | Size: 75 KiB After Width: | Height: | Size: 37 KiB |