aboutsummaryrefslogtreecommitdiff
path: root/front-end/src
diff options
context:
space:
mode:
Diffstat (limited to 'front-end/src')
-rw-r--r--front-end/src/App.vue155
-rw-r--r--front-end/src/buttons.scss48
-rw-r--r--front-end/src/components/Alerts.vue117
-rw-r--r--front-end/src/components/Bookmarks.vue583
-rw-r--r--front-end/src/components/Boomarks/AddOrUpdateForm.vue68
-rw-r--r--front-end/src/components/Boomarks/util.ts61
-rw-r--r--front-end/src/components/BottomMenuItem.vue46
-rw-r--r--front-end/src/components/Login.vue111
-rw-r--r--front-end/src/components/Login/PkiLogin.vue50
-rw-r--r--front-end/src/components/Login/UserPass.vue118
-rw-r--r--front-end/src/components/Settings.vue64
-rw-r--r--front-end/src/components/Settings/Oauth2Apps.vue85
-rw-r--r--front-end/src/components/Settings/PasswordReset.vue156
-rw-r--r--front-end/src/components/Settings/PkiSettings.vue216
-rw-r--r--front-end/src/components/Settings/TotpSettings.vue169
-rw-r--r--front-end/src/components/SideMenuItem.vue42
-rw-r--r--front-end/src/components/global/ConfirmPrompt.vue65
-rw-r--r--front-end/src/components/global/Dialog.vue61
-rw-r--r--front-end/src/components/global/OtpInput.vue54
-rw-r--r--front-end/src/components/global/PasswordPrompt.vue118
-rw-r--r--front-end/src/index.scss32
-rw-r--r--front-end/src/main.ts77
-rw-r--r--front-end/src/store/bookmarks.ts249
-rw-r--r--front-end/src/store/index.ts94
-rw-r--r--front-end/src/store/mfaSettingsPlugin.ts80
-rw-r--r--front-end/src/store/oauthAppsPlugin.ts174
-rw-r--r--front-end/src/store/socialMfaPlugin.ts85
-rw-r--r--front-end/src/store/userProfile.ts97
-rw-r--r--front-end/src/vite-env.d.ts1
29 files changed, 3276 insertions, 0 deletions
diff --git a/front-end/src/App.vue b/front-end/src/App.vue
new file mode 100644
index 0000000..a0d1416
--- /dev/null
+++ b/front-end/src/App.vue
@@ -0,0 +1,155 @@
+<script setup lang="ts">
+import { storeToRefs } from 'pinia';
+import { useStore, TabId } from './store';
+import { defineAsyncComponent } from 'vue';
+import { apiCall } from '@vnuge/vnlib.browser';
+import { isEqual } from 'lodash-es';
+import { useDark } from '@vueuse/core';
+import SideMenuItem from './components/SideMenuItem.vue';
+import Bookmarks from './components/Bookmarks.vue';
+import BottomMenuItem from './components/BottomMenuItem.vue';
+const Settings = defineAsyncComponent(() => import('./components/Settings.vue'));
+const Confirm = defineAsyncComponent(() => import('./components/global/ConfirmPrompt.vue'));
+const Alerts = defineAsyncComponent(() => import('./components/Alerts.vue'));
+const Login = defineAsyncComponent(() => import('./components/Login.vue'));
+const PasswordPrompt = defineAsyncComponent(() => import('./components/global/PasswordPrompt.vue'));
+
+const store = useStore();
+const { activeTab, siteTitle, loggedIn, userName } = storeToRefs(store);
+const darkMode = useDark()
+
+store.setSiteTitle('Simple Bookmark')
+
+const logout = () => {
+ apiCall(async () => {
+ const { logout } = await store.socialOauth()
+ await logout()
+ })
+}
+
+const showIf = (tabId: TabId, active: TabId) => isEqual(tabId, active)
+
+</script>
+
+<template>
+ <head>
+ <title>{{ siteTitle }}</title>
+ </head>
+ <body>
+ <div id="app" class="min-h-screen pb-16 text-gray-700 bg-gray-100 dark:bg-gray-900 dark:text-white sm:pb-0">
+
+ <div class="relative">
+ <div class="absolute z-50 right-10 top-10">
+ <Alerts />
+ </div>
+ </div>
+
+ <Confirm />
+ <PasswordPrompt />
+
+ <aside id="logo-sidebar" class="fixed top-0 left-0 z-10 w-64 h-screen transition-transform -translate-x-full sm:translate-x-0" aria-label="Sidebar">
+ <div class="flex flex-col h-full px-3 py-4 overflow-y-auto bg-white dark:bg-gray-800">
+ <div class="flex-auto">
+ <a href="/" class="flex items-center ps-2.5 mb-5">
+ <span class="p-2 mr-2 bg-blue-500 rounded-full">
+ <svg class="w-5 h-5 text-white" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 14 20">
+ <path d="M13 20a1 1 0 0 1-.64-.231L7 15.3l-5.36 4.469A1 1 0 0 1 0 19V2a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v17a1 1 0 0 1-1 1Z"/>
+ </svg>
+ </span>
+ <span class="self-center text-xl font-semibold whitespace-nowrap dark:text-white">{{ siteTitle }}</span>
+ </a>
+
+ <ul class="space-y-2 font-medium">
+ <SideMenuItem :disabled="!loggedIn" :tab="TabId.Bookmarks" name="Bookmarks">
+ <template #icon>
+ <path d="M13 20a1 1 0 0 1-.64-.231L7 15.3l-5.36 4.469A1 1 0 0 1 0 19V2a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v17a1 1 0 0 1-1 1Z"/>
+ </template>
+ </SideMenuItem>
+
+ <SideMenuItem :disabled="!loggedIn" :tab="TabId.Profile" name="Profile">
+ <template #icon>
+ <path d="M18 0H2a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2ZM6.5 3a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5ZM3.014 13.021l.157-.625A3.427 3.427 0 0 1 6.5 9.571a3.426 3.426 0 0 1 3.322 2.805l.159.622-6.967.023ZM16 12h-3a1 1 0 0 1 0-2h3a1 1 0 0 1 0 2Zm0-3h-3a1 1 0 1 1 0-2h3a1 1 0 1 1 0 2Zm0-3h-3a1 1 0 1 1 0-2h3a1 1 0 1 1 0 2Z"/>
+ </template>
+ </SideMenuItem>
+
+ <SideMenuItem :disabled="!loggedIn" :tab="TabId.Settings" name="Settings">
+ <template #icon>
+ <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7.75 4H19M7.75 4a2.25 2.25 0 0 1-4.5 0m4.5 0a2.25 2.25 0 0 0-4.5 0M1 4h2.25m13.5 6H19m-2.25 0a2.25 2.25 0 0 1-4.5 0m4.5 0a2.25 2.25 0 0 0-4.5 0M1 10h11.25m-4.5 6H19M7.75 16a2.25 2.25 0 0 1-4.5 0m4.5 0a2.25 2.25 0 0 0-4.5 0M1 16h2.25"/>
+ </template>
+ </SideMenuItem>
+
+ <SideMenuItem :tab="TabId.Login" :name="loggedIn ? 'Logout' : 'Login'">
+ <template #icon>
+ <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M1 7.5h11m0 0L8 3.786M12 7.5l-4 3.714M12 1h3c.53 0 1.04.196 1.414.544.375.348.586.82.586 1.313v9.286c0 .492-.21.965-.586 1.313A2.081 2.081 0 0 1 15 14h-3"/>
+ </template>
+ </SideMenuItem>
+ </ul>
+ <ul class="pt-2 mt-2 space-y-2 font-medium border-t dark:border-gray-700">
+ <li v-if="userName" class="text-sm text-center text-wrap">
+ Welcome back
+ <span class="text-blue-500">
+ {{ userName }}
+ </span>
+ </li>
+ </ul>
+ </div>
+ <div class="flex flex-row gap-3 pb-3 mx-auto text-sm font-bold text-gray-500 w-fit dark:text-gray-200">
+ <button @click="darkMode = false" class="block" :class="{'opacity-50':!darkMode }">Light</button>
+ <button @click="darkMode = true" class="block" :class="{'opacity-50':darkMode}">Dark</button>
+ </div>
+ <div class="">
+ <p class="text-xs text-center text-gray-500 dark:text-gray-400">
+ Copyright © Vaughn Nugent<br/>
+ Licensed under the GNU AGPLv3 license.
+ </p>
+ </div>
+ </div>
+ </aside>
+
+ <div class="h-full py-6 md:p-6 sm:ml-64">
+ <div v-if="showIf(TabId.Bookmarks, activeTab)" class="flex flex-col w-full h-full">
+ <Bookmarks />
+ </div>
+
+ <div v-if="showIf(TabId.Login, activeTab)" class="flex w-full h-full">
+ <Login />
+ </div>
+
+ <div v-if="showIf(TabId.Settings, activeTab)" class="flex w-full h-full">
+ <Settings />
+ </div>
+ </div>
+
+ <div class="fixed bottom-0 left-0 z-50 w-full h-16 bg-white border-t border-gray-200 sm:hidden dark:bg-gray-700 dark:border-gray-600">
+ <div class="grid h-full max-w-lg grid-cols-4 mx-auto font-medium">
+
+ <BottomMenuItem :disabled="!loggedIn" :tab="TabId.Bookmarks" name="Bookmarks">
+ <template #icon>
+ <path d="M13 20a1 1 0 0 1-.64-.231L7 15.3l-5.36 4.469A1 1 0 0 1 0 19V2a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v17a1 1 0 0 1-1 1Z"/>
+ </template>
+ </BottomMenuItem>
+
+ <BottomMenuItem :disabled="!loggedIn" :tab="TabId.Profile" name="Profile">
+ <template #icon>
+ <path d="M18 0H2a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2ZM6.5 3a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5ZM3.014 13.021l.157-.625A3.427 3.427 0 0 1 6.5 9.571a3.426 3.426 0 0 1 3.322 2.805l.159.622-6.967.023ZM16 12h-3a1 1 0 0 1 0-2h3a1 1 0 0 1 0 2Zm0-3h-3a1 1 0 1 1 0-2h3a1 1 0 1 1 0 2Zm0-3h-3a1 1 0 1 1 0-2h3a1 1 0 1 1 0 2Z"/>
+ </template>
+ </BottomMenuItem>
+
+ <BottomMenuItem :disabled="!loggedIn" :tab="TabId.Settings" name="Settings">
+ <template #icon>
+ <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7.75 4H19M7.75 4a2.25 2.25 0 0 1-4.5 0m4.5 0a2.25 2.25 0 0 0-4.5 0M1 4h2.25m13.5 6H19m-2.25 0a2.25 2.25 0 0 1-4.5 0m4.5 0a2.25 2.25 0 0 0-4.5 0M1 10h11.25m-4.5 6H19M7.75 16a2.25 2.25 0 0 1-4.5 0m4.5 0a2.25 2.25 0 0 0-4.5 0M1 16h2.25"/>
+ </template>
+ </BottomMenuItem>
+
+ <BottomMenuItem :tab="TabId.Login" :name="loggedIn ? 'Logout' : 'Login'">
+ <template #icon>
+ <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M1 7.5h11m0 0L8 3.786M12 7.5l-4 3.714M12 1h3c.53 0 1.04.196 1.414.544.375.348.586.82.586 1.313v9.286c0 .492-.21.965-.586 1.313A2.081 2.081 0 0 1 15 14h-3"/>
+ </template>
+ </BottomMenuItem>
+
+ </div>
+ </div>
+
+ </div>
+ </body>
+</template> \ No newline at end of file
diff --git a/front-end/src/buttons.scss b/front-end/src/buttons.scss
new file mode 100644
index 0000000..409f405
--- /dev/null
+++ b/front-end/src/buttons.scss
@@ -0,0 +1,48 @@
+.btn{
+ @apply focus:ring-2 focus:outline-none font-medium rounded text-sm px-4 py-2 text-center me-2 text-white;
+
+ &.round{
+ @apply rounded-full;
+ }
+
+ &.blue{
+ @apply bg-blue-700 hover:bg-blue-800 focus:ring-blue-300 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800;
+ }
+
+ &.red{
+ @apply bg-red-700 hover:bg-red-800 focus:ring-red-300 dark:bg-red-600 dark:hover:bg-red-700 dark:focus:ring-red-800;
+ }
+
+ &.green{
+ @apply bg-green-700 hover:bg-green-800 focus:ring-green-300 dark:bg-green-600 dark:hover:bg-green-700 dark:focus:ring-green-800;
+ }
+
+ &.yellow{
+ @apply bg-yellow-700 hover:bg-yellow-800 focus:ring-yellow-300 dark:bg-yellow-600 dark:hover:bg-yellow-700 dark:focus:ring-yellow-800;
+ }
+
+ &.purple{
+ @apply bg-purple-700 hover:bg-purple-800 focus:ring-purple-300 dark:bg-purple-600 dark:hover:bg-purple-700 dark:focus:ring-purple-800;
+ }
+
+ &.pink{
+ @apply bg-pink-700 hover:bg-pink-800 focus:ring-pink-300 dark:bg-pink-600 dark:hover:bg-pink-700 dark:focus:ring-pink-800;
+ }
+
+ &.indigo{
+ @apply bg-indigo-700 hover:bg-indigo-800 focus:ring-indigo-300 dark:bg-indigo-600 dark:hover:bg-indigo-700 dark:focus:ring-indigo-800;
+ }
+
+ &.gray{
+ @apply bg-gray-700 hover:bg-gray-800 focus:ring-gray-300 dark:bg-gray-600 dark:hover:bg-gray-700 dark:focus:ring-gray-800;
+ }
+
+ &.orange{
+ @apply bg-orange-700 hover:bg-orange-800 focus:ring-orange-300 dark:bg-orange-600 dark:hover:bg-orange-700 dark:focus:ring-orange-800;
+ }
+
+ &.light{
+ @apply text-gray-500 border bg-white hover:bg-gray-100 focus:ring-blue-300 border-gray-200 hover:text-gray-900 dark:bg-gray-700 dark:text-gray-300 dark:border-gray-500 dark:hover:text-white dark:hover:bg-gray-600 dark:focus:ring-gray-600;
+ }
+
+}
diff --git a/front-end/src/components/Alerts.vue b/front-end/src/components/Alerts.vue
new file mode 100644
index 0000000..e9177bc
--- /dev/null
+++ b/front-end/src/components/Alerts.vue
@@ -0,0 +1,117 @@
+<script setup lang="ts">
+import { configureNotifier } from '@vnuge/vnlib.browser';
+import { get, set } from '@vueuse/core';
+import { remove } from 'lodash-es';
+import { ref } from 'vue';
+
+type NotificationType = 'success' | 'error' | 'warning' | 'info';
+
+interface Notification{
+ id: string;
+ title: string;
+ text: string;
+ type: NotificationType;
+ duration?: number;
+ dismiss: () => void;
+}
+
+const notifications = ref<Notification[]>([]);
+
+const close = (id: string) => {
+ const current = get(notifications);
+ remove(current, n => n.id === id);
+ set(notifications, current);
+}
+
+const notify = (notification: Partial<Notification>) => {
+ const current = get(notifications);
+ const id = Math.random().toString(36).substring(7);
+ const newNotification = {
+ id,
+ title: notification.title ?? '',
+ text: notification.text ?? '',
+ type: notification.type ?? 'info',
+ dismiss: () => close(id),
+ }
+
+ set(notifications, [newNotification, ...current]);
+
+ //set timeout to close notification
+ setTimeout(() => close(id), notification.duration || 7000);
+}
+
+//configure global notifier
+configureNotifier({ notify, close })
+</script>
+
+<template>
+ <ul id="toaster" class="">
+
+ <li v-for="n in notifications" :key="n.id">
+ <Transition :duration="100" appear-from-class="-mr-20" appear-to-class="mr-10">
+ <div :id="n.id" class="alert" role="alert" :class="[n.type]">
+ <div class="flex items-center">
+ <svg class="flex-shrink-0 w-4 h-4 me-2" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 20 20">
+ <path d="M10 .5a9.5 9.5 0 1 0 9.5 9.5A9.51 9.51 0 0 0 10 .5ZM9.5 4a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3ZM12 15H8a1 1 0 0 1 0-2h1v-3H8a1 1 0 0 1 0-2h2a1 1 0 0 1 1 1v4h1a1 1 0 0 1 0 2Z" />
+ </svg>
+ <span class="sr-only">{{ n.type }}</span>
+ <h3 class="m-0 text-base font-medium">{{ n.title }}</h3>
+ </div>
+ <div v-if="n.text" class="mt-2 mb-2 text-sm">
+ {{ n.text }}
+ </div>
+ <div v-show="n.text" class="flex justify-end">
+ <button @click.prevent="n.dismiss()" type="button" data-dismiss-target="#alert-additional-content-1"
+ aria-label="Close">
+ Dismiss
+ </button>
+ </div>
+ </div>
+ </Transition>
+ </li>
+ </ul>
+</template>
+
+<style lang="scss">
+#toaster{
+ .alert {
+ @apply p-3 mb-4 border rounded;
+
+ button {
+ @apply bg-transparent border focus:ring-4 focus:outline-none font-medium rounded-lg text-xs px-3 py-1.5 text-center;
+ }
+
+ &.error {
+ @apply text-red-800 border-red-300 dark:text-red-400 dark:border-red-800 bg-red-50 dark:bg-transparent;
+
+ button {
+ @apply text-red-800 border-red-800 hover:bg-red-900 hover:text-white focus:ring-red-300 dark:hover:bg-red-600 dark:border-red-600 dark:text-red-500 dark:hover:text-white dark:focus:ring-red-800
+ }
+ }
+
+ &.success {
+ @apply text-green-800 border-green-300 dark:text-green-400 dark:border-green-800 dark:bg-transparent bg-green-100;
+
+ button {
+ @apply text-green-800 border-green-800 hover:bg-green-900 hover:text-white focus:ring-green-300 dark:hover:bg-green-600 dark:border-green-600 dark:text-green-400 dark:hover:text-white dark:focus:ring-green-800;
+ }
+ }
+
+ &.warning {
+ @apply text-yellow-800 border-yellow-300 dark:text-yellow-300 dark:border-yellow-800 dark:bg-transparent bg-yellow-100;
+
+ button {
+ @apply text-yellow-800 border-yellow-800 hover:bg-yellow-900 hover:text-white focus:ring-yellow-300 dark:hover:bg-yellow-300 dark:border-yellow-300 dark:text-yellow-300 dark:hover:text-gray-800 dark:focus:ring-yellow-800;
+ }
+ }
+
+ &.info {
+ @apply text-blue-800 border-blue-300 dark:text-blue-400 dark:border-blue-800 dark:bg-transparent bg-blue-100;
+
+ button {
+ @apply text-blue-800 border-blue-800 hover:bg-blue-900 hover:text-white focus:ring-blue-300 dark:hover:bg-blue-600 dark:border-blue-600 dark:text-blue-500 dark:hover:text-white dark:focus:ring-blue-800;
+ }
+ }
+ }
+}
+</style>
diff --git a/front-end/src/components/Bookmarks.vue b/front-end/src/components/Bookmarks.vue
new file mode 100644
index 0000000..7aa3eb0
--- /dev/null
+++ b/front-end/src/components/Bookmarks.vue
@@ -0,0 +1,583 @@
+<script setup lang="ts">
+import { MaybeRef, Ref, computed, defineAsyncComponent, ref, shallowRef, watch } from 'vue';
+import { useQuery, useStore } from '../store';
+import { get, set, formatTimeAgo, useToggle, useTimestamp, useFileDialog, asyncComputed, toReactive } from '@vueuse/core';
+import { useVuelidate } from '@vuelidate/core';
+import { required, maxLength, minLength, helpers } from '@vuelidate/validators';
+import { apiCall, useConfirm, useGeneralToaster, useVuelidateWrapper, useWait } from '@vnuge/vnlib.browser';
+import { clone, cloneDeep, join, defaultTo, every, filter, includes, isEmpty, isEqual, first, isString, chunk, map } from 'lodash-es';
+import { Menu, MenuButton, MenuItems, MenuItem } from '@headlessui/vue'
+import { parseNetscapeBookmarkString } from './Boomarks/util.ts';
+import type { Bookmark, BookmarkError } from '../store/bookmarks';
+import AddOrUpdateForm from './Boomarks/AddOrUpdateForm.vue';
+const Dialog = defineAsyncComponent(() => import('./global/Dialog.vue'));
+
+const store = useStore();
+const { waiting } = useWait();
+const { reveal } = useConfirm();
+const toaster = useGeneralToaster();
+const bookmarks = computed(() => store.bookmarks.list);
+const tags = computed(() => store.bookmarks.allTags);
+const now = useTimestamp({interval: 1000});
+const selectedTags = computed(() => store.bookmarks.tags);
+const localSearch = shallowRef<string>(store.bookmarks.query);
+const nextPageAvailable = computed(() => isEqual(bookmarks.value?.length, get(store.bookmarks.pages.currentPageSize)));
+
+//Refresh on page load
+store.bookmarks.refresh();
+
+const safeNameRegex = /^[a-zA-Z0-9_\-\|\. ]*$/;
+const safeUrlRegex = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/;
+const safeTagRegex = /^[a-zA-Z0-9-_]*$/;
+
+const addOrEditValidator = (buffer: Ref<Partial<Bookmark>>) => {
+
+ const rules = computed(() => ({
+ Name: {
+ required: helpers.withMessage('Name cannot be empty', required),
+ safeName: helpers.withMessage('Bookmark name contains illegal characters', (value: string) => safeNameRegex.test(value)),
+ minLength: helpers.withMessage('Name must be at least 1 characters', minLength(1)),
+ maxLength: helpers.withMessage('Name must have less than 128 characters', maxLength(128))
+ },
+ Url: {
+ required: helpers.withMessage('Url cannot be empty', required),
+ safeUrl: helpers.withMessage('Url contains illegal characters or is not a valid URL', (value: string) => safeUrlRegex.test(value)),
+ minLength: helpers.withMessage('Url must be at least 1 characters', minLength(1)),
+ maxLength: helpers.withMessage('Url must have less than 128 characters', maxLength(128))
+ },
+ Description: {
+ maxLength: helpers.withMessage('Description must have less than 512 characters', maxLength(512))
+ },
+ Tags: {
+ maxLength: helpers.withMessage('Tags must have less than 32 characters', (tags: string[]) => every(tags, tag => tag.length < 32)),
+ safeTag: helpers.withMessage('Tags contains illegal characters', (tags: string[]) => every(tags, tag => safeTagRegex.test(tag)))
+ }
+ }));
+
+ return useVuelidate(rules, buffer as Ref<Bookmark>);
+}
+
+const toggleTag = (tag: string) => {
+ const selected = defaultTo(get(selectedTags), []);
+
+ if(isTagSelected(tag, selected)){
+ const without = filter(selected, t => t !== tag);
+ store.bookmarks.tags = clone(without);
+ }else{
+ selected.push(tag);
+ store.bookmarks.tags = clone(selected);
+ }
+}
+
+const clear = () => {
+ store.bookmarks.tags = [];
+ store.bookmarks.query = '';
+ set(localSearch, '');
+}
+
+const bmDelete = async (bookmark: Bookmark) => {
+ const { isCanceled } = await reveal({
+ title: 'Delete bookmark',
+ text: `Are you sure you want to delete ${bookmark.Name} ?`,
+ })
+
+ if(isCanceled) return;
+
+ apiCall(async ({ toaster }) => {
+
+ await store.bookmarks.api.delete(bookmark);
+
+ toaster.general.success({
+ title: 'Bookmark deleted',
+ text: 'Bookmark has been deleted successfully'
+ });
+
+ store.bookmarks.refresh();
+ })
+}
+
+const isTagSelected = (tag: string, currentTags: MaybeRef<string[]>) => includes(get(currentTags), tag);
+const execSearch = () => store.bookmarks.query = get(localSearch);
+const percentToWith = (percent: number) => ({ width: `${percent}%` });
+const printErroMessage = (error: BookmarkError) => {
+ const errorMessages = map(error.errors, e=> e.message);
+ return `${error.subject.Url} - ${errorMessages.join(', ')}`
+}
+
+const edit = (() => {
+
+ const editBuffer = ref<Partial<Bookmark>>({});
+
+ const v$ = addOrEditValidator(editBuffer);
+ const { validate } = useVuelidateWrapper(v$ as any);
+
+ const editBookmark = (bookmark: Bookmark) => {
+ //always edit a clone
+ const clone = cloneDeep(bookmark);
+ set(editBuffer, clone);
+ }
+
+ const cancel = () => {
+ set(editBuffer, {});
+ v$.value.$reset();
+ }
+
+ const submit = async () => {
+ if (!await validate()) return
+
+ apiCall(async ({ toaster }) => {
+ //set the existing bookmark metadata
+ await store.bookmarks.api.set(get(editBuffer) as Bookmark);
+
+ toaster.general.success({
+ title: 'Bookmark updated',
+ text: 'Bookmark has been updated successfully'
+ });
+
+ store.bookmarks.refresh();
+ cancel();
+ })
+ }
+
+ const isOpen = computed(() => !isEmpty(editBuffer.value.Id));
+
+ return {
+ v$,
+ isOpen,
+ editBookmark,
+ cancel,
+ submit
+ }
+})()
+
+const add = (() => {
+
+ /**
+ * The following query arguments are used to import a
+ * bookmark from a url the import dialog can be opened
+ * externally by passing the url and title as query arguments
+ */
+ const importUrl = useQuery('url');
+ const title = useQuery('title');
+ const editBuffer = ref<Partial<Bookmark>>({});
+
+ const v$ = addOrEditValidator(editBuffer);
+ const { validate } = useVuelidateWrapper(v$ as any);
+
+ const [isOpen, toggleOpen] = useToggle(false)
+
+ //Clear buffer when dialog is closed
+ watch(isOpen, open => {
+ if (!open) {
+ set(editBuffer, {})
+ v$.value.$reset()
+
+ importUrl.value = null;
+ title.value = null;
+ }
+ })
+
+ //only run on initial load
+ if(importUrl.value) {
+ set(editBuffer, {
+ Name: title.value!,
+ Url: importUrl.value!
+ });
+ //Open dialog
+ toggleOpen(true);
+ }
+
+ const cancel = () => toggleOpen(false);
+ const open = () => toggleOpen(true);
+
+ const submit = async () => {
+ if (!await validate()) return
+
+ apiCall(async ({ toaster }) => {
+ //set the existing bookmark metadata
+ await store.bookmarks.api.add(get(editBuffer) as Bookmark);
+
+ toaster.general.success({
+ title: 'Bookmark added',
+ text: 'Bookmark has been added successfully'
+ });
+
+ store.bookmarks.refresh();
+ cancel();
+ })
+ }
+
+ return {
+ v$,
+ isOpen,
+ open,
+ cancel,
+ submit
+ }
+})()
+
+const upload = (() => {
+
+ const { open, reset, files } = useFileDialog({ 'accept': '.html', multiple: false });
+
+ const file = computed(() => first(files.value));
+ const ignoreErrors = ref(false);
+ const errors = ref<BookmarkError[]>([]);
+ const progress = ref<string[]>([]);
+ const progressPercent = ref(0);
+
+ //Automatically parse the file when it is selected
+ const foundBookmarks = asyncComputed(async () => {
+ if(!file.value) return [];
+ try{
+ //read to the text into mempry
+ const text = await file.value!.text()
+ //parse the text into bookmarks
+ return parseNetscapeBookmarkString(text);
+ }
+ catch{
+ toaster.error({
+ title: 'Error reading file',
+ text: 'There was an error reading the bookmarks HTML file'
+ });
+ return [];
+ }
+ })
+
+ const isOpen = computed(() => !isEmpty(foundBookmarks.value));
+
+ const cancel = () =>{
+ reset();
+ set(errors, []);
+ set(progress, []);
+ set(progressPercent, 0);
+ }
+
+ const submit = async () => {
+ await apiCall(async () => {
+
+ //parse the text into bookmarks
+ const bms = get(foundBookmarks);
+
+ const chunks = chunk(bms, 20);
+
+ for(let i = 0; i < chunks.length; i++){
+
+ progress.value[i] = `Uploading batch ${i+1} of ${chunks.length}`;
+
+ //Exec the upload
+ const result = await store.bookmarks.api.addMany(chunks[i],!get(ignoreErrors));
+ let isError = false
+
+ //See if an error occured
+ if(!isString(result) && 'invalid' in result){
+ //add errors to the error list
+ errors.value.push(...result.invalid);
+ isError = true;
+ }
+
+ if(isError){
+ const is = errors.value.length === 1 ? 'error' : 'errors';
+ progress.value[i] = `Failed to upload batch ${i+1} of ${chunks.length} with ${ errors.value.length } ${ is }`
+ }
+ else{
+ progress.value[i] = `Uploaded batch ${i+1} of ${chunks.length}: ${result}`;
+ }
+
+ //update the progress bar
+ progressPercent.value = Math.round((i+1) / chunks.length * 100);
+
+ //refresh the bookmarks
+ store.bookmarks.refresh();
+ }
+ })
+
+ //Force set progress once complete regardless of errors
+ progressPercent.value = 100;
+ progress.value.push('Upload complete');
+ }
+
+ return toReactive({
+ file,
+ isOpen,
+ open,
+ cancel,
+ submit,
+ foundBookmarks,
+ progressPercent,
+ errors,
+ progress,
+ ignoreErrors
+ })
+})()
+
+</script>
+<template>
+ <div class="w-full h-full px-2">
+ <div class="flex flex-row items-center mx-auto w-fit">
+
+ <div class="xl:min-w-[40rem]">
+
+ <form @click.prevent="execSearch()" class="flex items-center">
+ <label for="simple-search" class="sr-only">Search</label>
+ <div class="relative w-full">
+ <div class="absolute inset-y-0 flex items-center pointer-events-none start-0 ps-3">
+ <svg class="w-4 h-4 text-gray-500 dark:text-gray-400" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 18 20">
+ <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m13 19-6-5-6 5V2a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v17Z"/>
+ </svg>
+ </div>
+ <input type="text" id="simple-search" v-model="localSearch" class="search" placeholder="Search bookmarks">
+ <span @click.prevent="clear()" class="absolute inset-y-0 flex items-center cursor-pointer end-0 pe-3">
+ <svg class="w-3 h-3 text-gray-500 dark:text-gray-400" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 14 14">
+ <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6"/>
+ </svg>
+ </span>
+ </div>
+ <button type="submit" class="search" :disabled="waiting">
+ <svg class="w-4 h-4" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20">
+ <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m19 19-4-4m0-7A7 7 0 1 1 1 8a7 7 0 0 1 14 0Z"/>
+ </svg>
+ <span class="sr-only">Search</span>
+ </button>
+ </form>
+
+ </div>
+
+ <div class="relative ml-3 md:ml-10">
+ <Menu>
+ <MenuButton class="flex items-center gap-3 btn blue">
+ <svg class="w-5 h-5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 18 18">
+ <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 1v16M1 9h16"/>
+ </svg>
+ <span class="hidden lg:inline">New bookmark</span>
+ </MenuButton>
+ <transition
+ enter-active-class="transition duration-100 ease-out"
+ enter-from-class="transform scale-95 opacity-0"
+ enter-to-class="transform scale-100 opacity-100"
+ leave-active-class="transition duration-75 ease-out"
+ leave-from-class="transform scale-100 opacity-100"
+ leave-to-class="transform scale-95 opacity-0"
+ >
+ <MenuItems class="absolute z-10 bg-white divide-y divide-gray-100 rounded-b shadow right-2 lg:left-0 min-w-32 lg:end-0 dark:bg-gray-700">
+ <ul class="py-2 text-sm text-gray-700 dark:text-gray-200" aria-labelledby="dropdownDefaultButton">
+ <!-- Use the `active` state to conditionally style the active item. -->
+ <MenuItem as="template" v-slot="{ active }">
+ <li>
+ <button @click="add.open()" class="block w-full px-4 py-2 text-left hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white">
+ Manual
+ </button>
+ </li>
+ </MenuItem>
+ <MenuItem as="template" v-slot="{ active }">
+ <li>
+ <button @click="upload.open()" class="block w-full px-4 py-2 text-left hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white">
+ Upload html
+ </button>
+ </li>
+ </MenuItem>
+ </ul>
+ </MenuItems>
+ </transition>
+ </Menu>
+
+ <!-- Dropdown menu -->
+ <div id="dropdown" class="z-10 hidden bg-white divide-y divide-gray-100 rounded-lg shadow w-44 dark:bg-gray-700">
+ <ul class="py-2 text-sm text-gray-700 dark:text-gray-200" aria-labelledby="dropdownDefaultButton">
+ <li>
+ <a href="#" class="block px-4 py-2 hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white">Dashboard</a>
+ </li>
+ <li>
+ <a href="#" class="block px-4 py-2 hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white">Settings</a>
+ </li>
+ <li>
+ <a href="#" class="block px-4 py-2 hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white">Earnings</a>
+ </li>
+ <li>
+ <a href="#" class="block px-4 py-2 hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white">Sign out</a>
+ </li>
+ </ul>
+ </div>
+
+ </div>
+ </div>
+ <div class="grid flex-auto grid-cols-4 gap-8 mt-4 max-w-[60rem] mx-auto w-full">
+
+ <div class="col-span-4 lg:col-span-3">
+
+ <div role="status" class="mx-auto mt-2 w-fit" :class="{'opacity-0': !waiting }">
+ <svg aria-hidden="true" class="inline w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="currentColor"/>
+ <path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentFill"/>
+ </svg>
+ <span class="sr-only">Loading...</span>
+ </div>
+
+ <div class="mx-auto mt-2">
+ <div class="grid h-full grid-cols-1 gap-1 leading-tight md:leading-normal">
+
+ <div v-for="bm in bookmarks" :key="bm.Id" :id="join(['bm', bm.Id], '-')" class="w-full p-1">
+ <div class="">
+ <a class="bl-link" :href="bm.Url" target="_blank">
+ {{ bm.Name }}
+ </a>
+ </div>
+ <div class="flex flex-row items-center">
+ <span v-for="tag in bm.Tags">
+ <span class="mr-1 text-sm text-teal-500 cursor-pointer dark:text-teal-300" @click="toggleTag(tag)">
+ #{{ tag }}
+ </span>
+ </span>
+ <p class="ml-2 text-sm text-gray-500 truncate dark:text-gray-400 text-ellipsis">
+ {{ bm.Description }}
+ </p>
+ </div>
+ <div class="">
+ <span class="text-xs text-gray-500 dark:text-gray-400">
+ {{ formatTimeAgo(new Date(bm.Created), {}, now) }}
+ </span>
+ |
+ <span class="inline-flex gap-1.5">
+ <button class="text-xs text-gray-700 dark:text-gray-400" @click="edit.editBookmark(bm)">
+ Edit
+ </button>
+ <button class="text-xs text-gray-700 dark:text-gray-400" @click="bmDelete(bm)">
+ Delete
+ </button>
+ </span>
+ </div>
+ </div>
+ </div>
+ <div class="pr-4 mt-5 mb-10 ml-auto w-fit">
+ <div class="flex flex-col items-center">
+ <div class="text-sm">
+ Page {{ store.bookmarks.pages.currentPage }}
+ </div>
+ <!-- Buttons -->
+ <div class="inline-flex mt-1 xs:mt-0">
+ <button
+ @click="store.bookmarks.pages.prev()"
+ class="flex items-center justify-center h-8 px-3 text-sm font-medium text-white bg-gray-800 rounded-s hover:bg-gray-900 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white">
+ Prev
+ </button>
+ <button
+ :disabled="!nextPageAvailable"
+ @click="store.bookmarks.pages.next()"
+ class="flex items-center justify-center h-8 px-3 text-sm font-medium text-white bg-gray-800 border-0 border-gray-700 border-s rounded-e hover:bg-gray-900 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white">
+ Next
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div class="hidden lg:block">
+ <div class="mt-10">
+ <ul class="grid grid-cols-2">
+ <li v-for="tag in tags" :key="tag" class="text-sm">
+ <span
+ class="mr-1 text-teal-500 cursor-pointer dark:text-teal-300" @click="toggleTag(tag)"
+ :class="{ 'selected': isTagSelected(tag, selectedTags) }"
+ >
+ {{ tag }}
+ </span>
+ </li>
+ </ul>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <Dialog :open="get(edit.isOpen)" title="Edit Bookmark" @cancel="edit.cancel">
+ <template #body>
+ <AddOrUpdateForm :v$="edit.v$" @submit="edit.submit" />
+ </template>
+ </Dialog>
+
+ <Dialog :open="get(add.isOpen)" title="New Bookmark" @cancel="add.cancel">
+ <template #body>
+ <AddOrUpdateForm :v$="add.v$" @submit="add.submit" />
+ </template>
+ </Dialog>
+
+ <Dialog :open="upload.isOpen" title="Upload Bookmarks" @cancel="upload.cancel">
+ <template #body>
+ <div class="p-4 text-gray-700 dark:text-gray-200">
+ <div v-if="upload.progress.length > 0" >
+ <h5>
+ Progress
+ </h5>
+ <div class="py-3">
+ <div class="w-full bg-gray-200 rounded-full dark:bg-gray-700">
+ <div
+ class="bg-blue-600 text-xs font-medium text-blue-100 text-center p-0.5 leading-none rounded-full"
+ :style="percentToWith(upload.progressPercent)"
+
+ >{{upload.progressPercent}}%
+ </div>
+ </div>
+ </div>
+ <div class="p-2 bg-gray-100 dark:bg-transparent border dark:border-gray-400 rounded max-h-[14rem] overflow-y-auto">
+ <div v-for="p in upload.progress" class="text-sm">
+ {{ p }}
+ </div>
+ </div>
+ <h5 class="my-2">
+ Errors
+ </h5>
+ <div class="p-2 bg-gray-100 dark:bg-transparent border dark:border-gray-400 rounded max-h-[14rem] overflow-y-auto">
+ <div v-for="e in upload.errors" class="text-sm text-red-500 whitespace-nowrap">
+ {{ printErroMessage(e) }}
+ </div>
+ </div>
+ </div>
+ <div v-else>
+ <form class="" @submit.prevent="upload.submit()">
+ <div class="text-left">
+ <div class="">
+ Reading files
+ <span class="font-semibold text-white">
+ {{ upload.file?.name }}
+ </span>
+ </div>
+ <div class="">
+ Found {{ upload.foundBookmarks.length }} bookmarks to add
+ </div>
+ </div>
+ <div class="flex flex-row items-center justify-between my-3 ">
+ <div>
+ <div class="flex items-center">
+ <input id="ignore-errors" type="checkbox" v-model="upload.ignoreErrors" class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded cursor-pointer focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600">
+ <label for="ignore-errors" class="text-sm font-medium ms-2">Ignore Errors</label>
+ </div>
+ </div>
+ <button type="submit" class="btn blue">
+ Upload
+ </button>
+ </div>
+ <div class="">
+
+ </div>
+ </form>
+ </div>
+ </div>
+ </template>
+ </Dialog>
+
+</template>
+
+<style scoped lang="scss">
+ input.search{
+ @apply ps-10 p-2.5 border block w-full text-sm rounded pe-10;
+ @apply bg-gray-50 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 border-gray-300 text-gray-900 focus:ring-blue-500 focus:border-blue-500 ;
+ }
+
+ button.search{
+ @apply p-2.5 ms-2 text-sm font-medium text-white bg-blue-700 rounded border border-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800
+ }
+
+ .selected{
+ @apply text-red-500 dark:text-red-400 font-bold;
+ }
+
+</style> \ No newline at end of file
diff --git a/front-end/src/components/Boomarks/AddOrUpdateForm.vue b/front-end/src/components/Boomarks/AddOrUpdateForm.vue
new file mode 100644
index 0000000..a4a3f1d
--- /dev/null
+++ b/front-end/src/components/Boomarks/AddOrUpdateForm.vue
@@ -0,0 +1,68 @@
+<script setup lang="ts">
+import { computed, toRefs } from 'vue';
+import { join, split } from 'lodash-es';
+
+const emit = defineEmits(['submit'])
+const props = defineProps<{
+ v$:any
+}>()
+
+const { v$ } = toRefs(props)
+
+//Convert tags array to string
+const tags = computed({
+ get: () => join(v$.value.Tags.$model, ','),
+ set: (value:string) => v$.value.Tags.$model = split(value, ',')
+})
+
+</script>
+<template>
+ <form class="grid grid-cols-1 gap-4 p-4" @submit.prevent="emit('submit')">
+ <fieldset>
+ <label for="url" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">URL</label>
+ <input type="text" id="url" class="input" placeholder="https://www.example.com"
+ v-model="v$.Url.$model"
+ :class="{'dirty': v$.Url.$dirty, 'error': v$.Url.$invalid}"
+ required
+ >
+ </fieldset>
+ <fieldset>
+ <label for="name" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Title</label>
+ <input type="text" id="Name" class="input" placeholder="Hello World"
+ v-model="v$.Name.$model"
+ :class="{'dirty': v$.Name.$dirty, 'error': v$.Name.$invalid}"
+ required
+ >
+ </fieldset>
+ <fieldset>
+ <label for="tags" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Tags</label>
+ <input type="text" id="tags" class="input" placeholder="tag1,tag2,tag3"
+ v-model="tags"
+ :class="{'dirty': v$.Tags.$dirty, 'error': v$.Tags.$invalid}"
+ >
+ </fieldset>
+ <fieldset>
+ <label for="description" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Description</label>
+ <textarea type="text" id="description" rows="5" class="input" placeholder="This is a bookmark"
+ v-model="v$.Description.$model"
+ :class="{'dirty': v$.Description.$dirty, 'error': v$.Description.$invalid}"
+ />
+ </fieldset>
+
+ <div class="flex justify-end">
+ <button type="submit" class="btn blue">
+ Submit
+ </button>
+ </div>
+ </form>
+</template>
+
+<style scoped lang="scss">input.search {
+ @apply ps-10 p-2.5 border block w-full text-sm rounded;
+ @apply bg-gray-50 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 border-gray-300 text-gray-900 focus:ring-blue-500 focus:border-blue-500;
+}
+
+button.search {
+ @apply p-2.5 ms-2 text-sm font-medium text-white bg-blue-700 rounded border border-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800
+}
+</style> \ No newline at end of file
diff --git a/front-end/src/components/Boomarks/util.ts b/front-end/src/components/Boomarks/util.ts
new file mode 100644
index 0000000..669be46
--- /dev/null
+++ b/front-end/src/components/Boomarks/util.ts
@@ -0,0 +1,61 @@
+// Copyright (C) 2024 Vaughn Nugent
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+import type { Bookmark } from '../../store/bookmarks'
+import { split, first, includes, map, filter, nth, isEmpty } from 'lodash-es'
+
+export const parseNetscapeBookmarkString = (bookmarkString: string) : Bookmark[] => {
+ const lines = split(bookmarkString, '\n');
+ //remove any empty lines
+ const elements = filter(lines, l => l.length > 0)
+
+ const header = first(elements);
+ if(!includes(header, 'NETSCAPE-Bookmark-file-1')) {
+ throw new Error('Invalid bookmark file');
+ }
+
+ const bookmarks = map(elements, (line, index): Partial<Bookmark> => {
+
+ //Search for required html components in the line
+ const Url = line.match(/HREF="([^"]*)"/)?.[1];
+ const tags = line.match(/TAGS="(.*)"/)?.[1];
+ const Name = line.match(/">(.*)<\/A/)?.[1];
+ const date = line.match(/ADD_DATE="([^"]*)"/)?.[1];
+ //Next line should be the description
+ const descriptionEl = nth(elements, index + 1);
+ const Description = split(descriptionEl, '<DD>')?.[1];
+
+ const Tags = filter(split(tags, ','), t => !isEmpty(t));
+
+ const bookmark: Partial<Bookmark> = {
+ Name,
+ Url,
+ Description,
+ }
+
+ //Only set tags if there are any
+ if(!isEmpty(Tags)) {
+ bookmark.Tags = Tags;
+ }
+
+ if (date){
+ bookmark.Created = new Date(parseInt(date) * 1000).toISOString();
+ }
+ return bookmark;
+ });
+
+ //Filter any empty entires
+ return filter(bookmarks, b => b.Name && b.Url) as Bookmark[];
+} \ No newline at end of file
diff --git a/front-end/src/components/BottomMenuItem.vue b/front-end/src/components/BottomMenuItem.vue
new file mode 100644
index 0000000..5a5a668
--- /dev/null
+++ b/front-end/src/components/BottomMenuItem.vue
@@ -0,0 +1,46 @@
+<script setup lang="ts">
+import { storeToRefs } from 'pinia';
+import { useStore, TabId } from '../store';
+import { toRefs } from 'vue';
+import { noop } from 'lodash-es';
+import { get, set } from '@vueuse/core';
+
+const props = defineProps<{
+ tab: TabId;
+ name: String,
+ disabled?: Boolean
+}>()
+
+const store = useStore()
+const { activeTab } = storeToRefs(store)
+const { name, disabled, tab } = toRefs(props)
+
+//const isActive = (tab: TabId, activeTab: TabId) => isEqual(activeTab, tab);
+const setActiveTab = (tab: TabId) => get(disabled) ? noop() : set(activeTab, tab)
+
+</script>
+
+<template>
+ <button type="button" class="bm group" @click="setActiveTab(tab)">
+ <svg class="group-hover:text-blue-600 dark:group-hover:text-blue-500" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 20 20">
+ <slot name="icon" />
+ </svg>
+ <span class="group-hover:text-blue-600 dark:group-hover:text-blue-500">
+ {{ name }}
+ </span>
+ </button>
+</template>
+
+<style scoped lang="scss">
+button.bm {
+ @apply inline-flex flex-col items-center justify-center px-5 border-gray-200 border-x hover:bg-gray-50 dark:hover:bg-gray-800 dark:border-gray-600;
+
+ svg {
+ @apply w-5 h-5 mb-2 text-gray-500 dark:text-gray-400;
+ }
+
+ span {
+ @apply text-sm text-gray-500 dark:text-gray-400;
+ }
+}
+</style> \ No newline at end of file
diff --git a/front-end/src/components/Login.vue b/front-end/src/components/Login.vue
new file mode 100644
index 0000000..7de86cb
--- /dev/null
+++ b/front-end/src/components/Login.vue
@@ -0,0 +1,111 @@
+<script setup lang="ts">
+import { apiCall, useWait } from '@vnuge/vnlib.browser'
+import { storeToRefs } from 'pinia'
+import { useStore } from '../store'
+import { TabGroup, TabList, Tab, TabPanels, TabPanel } from '@headlessui/vue'
+import UserPass from './Login/UserPass.vue'
+import PkiLogin from './Login/PkiLogin.vue'
+
+const { waiting } = useWait();
+const store = useStore();
+const { loggedIn, siteTitle } = storeToRefs(store);
+
+const logout = () => {
+ apiCall(async () => {
+ const { logout } = await store.socialOauth()
+ await logout()
+ })
+}
+
+</script>
+<template>
+ <section id="login-page" class="flex-auto">
+ <div class="flex flex-col items-center justify-center px-6 py-8 mx-auto lg:py-24">
+ <div class="flex items-center mb-6 text-2xl font-semibold text-gray-900 dark:text-white">
+ <span class="p-2 mr-2 bg-blue-500 rounded-full">
+ <svg class="w-5 h-5 text-white" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 14 20">
+ <path d="M13 20a1 1 0 0 1-.64-.231L7 15.3l-5.36 4.469A1 1 0 0 1 0 19V2a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v17a1 1 0 0 1-1 1Z"/>
+ </svg>
+ </span>
+ <span class="self-center font-semibold whitespace-nowrap">{{ siteTitle }}</span>
+ </div>
+ <div class="w-full bg-white rounded shadow dark:border md:mt-0 sm:max-w-md xl:p-0 dark:bg-gray-800 dark:border-gray-700">
+ <div class="p-6 space-y-4 md:space-y-6 sm:p-8">
+
+ <div v-if="!loggedIn">
+ <!-- password/username login -->
+ <h1 class="text-xl font-bold leading-tight tracking-tight text-center text-gray-900 md:text-2xl dark:text-white">
+ Sign in to your account
+ </h1>
+
+ <TabGroup class="w-full" as="div">
+ <TabList as="ul" class="flex flex-wrap justify-center -mb-px text-sm font-medium text-center text-gray-500 dark:text-gray-400">
+ <Tab as="template" v-slot="{ selected }" class="cursor-pointer me-2">
+ <div class="tab group" :class="{ selected }">
+ <svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 20 20">
+ <path d="M10 0a10 10 0 1 0 10 10A10.011 10.011 0 0 0 10 0Zm0 5a3 3 0 1 1 0 6 3 3 0 0 1 0-6Zm0 13a8.949 8.949 0 0 1-4.951-1.488A3.987 3.987 0 0 1 9 13h2a3.987 3.987 0 0 1 3.951 3.512A8.949 8.949 0 0 1 10 18Z"/>
+ </svg>
+ Email
+ </div>
+ </Tab>
+ <Tab as="template" v-slot="{ selected }" class="cursor-pointer me-2">
+ <div class="tab group" :class="{ selected }">
+ <svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 20 20">
+ <path d="M8 18A18.55 18.55 0 0 1 0 3l8-3 8 3a18.549 18.549 0 0 1-8 15Z"/>
+ </svg>
+ Token
+ </div>
+ </Tab>
+ </TabList>
+ <TabPanels class="mt-4" as="div">
+ <TabPanel :unmount="false">
+ <UserPass />
+ </TabPanel>
+ <TabPanel>
+ <PkiLogin />
+ </TabPanel>
+ </TabPanels>
+ </TabGroup>
+
+ </div>
+
+ <div v-else class="">
+ <h1 class="text-xl font-bold leading-tight tracking-tight text-center text-gray-900 md:text-2xl dark:text-white">
+ Sign Out
+ </h1>
+
+ <div class="mt-4">
+ <button :disabled="waiting" @click="logout" class="btn">Sign Out</button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </section>
+</template>
+
+<style lang="scss">
+#login-page {
+ .tab{
+ @apply inline-flex items-center justify-center p-4 border-b-2 border-transparent rounded-t-lg hover:text-gray-600 hover:border-gray-300 dark:hover:text-gray-300;
+
+ svg{
+ @apply w-4 h-4 text-gray-400 me-2 group-hover:text-gray-500 dark:text-gray-500 dark:group-hover:text-gray-300;
+ }
+
+ &.selected{
+ @apply text-blue-600 border-b-2 border-blue-600 rounded-t-lg dark:text-blue-500 dark:border-blue-500;
+
+ svg{
+ @apply text-blue-600 me-2 dark:text-blue-500;
+ }
+ }
+ }
+
+
+ button.btn{
+ @apply w-full focus:ring-4 focus:outline-none font-medium rounded text-sm px-5 py-2.5 text-center;
+ @apply text-white bg-blue-600 hover:bg-blue-700 focus:ring-blue-300 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800;
+ }
+}
+</style> \ No newline at end of file
diff --git a/front-end/src/components/Login/PkiLogin.vue b/front-end/src/components/Login/PkiLogin.vue
new file mode 100644
index 0000000..26528c4
--- /dev/null
+++ b/front-end/src/components/Login/PkiLogin.vue
@@ -0,0 +1,50 @@
+<script setup lang="ts">
+import { isEmpty } from 'lodash-es';
+import { apiCall, debugLog, useMessage } from '@vnuge/vnlib.browser';
+import { ref } from 'vue'
+import { decodeJwt } from 'jose'
+import { useStore } from '../../store';
+
+const { setMessage } = useMessage()
+const { pkiAuth } = useStore()
+
+const otp = ref('')
+
+const onSubmit = () => {
+
+ apiCall(async () => {
+ if (isEmpty(otp.value)) {
+ setMessage('Please enter your OTP')
+ return
+ }
+ try{
+ //try to decode the jwt to confirm its form is valid
+ const jwt = decodeJwt(otp.value)
+ debugLog(jwt)
+ }
+ catch{
+ setMessage('Your OTP is not valid')
+ return
+ }
+ await pkiAuth.login(otp.value)
+ })
+}
+</script>
+
+<template>
+ <form id="pki-login-form" class="max-w-sm mx-auto" @submit.prevent="onSubmit">
+ <label for="message" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
+ Paste your one time password (OTP)
+ </label>
+ <textarea
+ id="message" rows="5"
+ v-model="otp"
+ class="block p-2.5 w-full text-sm text-gray-900 bg-gray-50 rounded border border-gray-300 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
+ placeholder="Enter your OTP"
+ >
+ </textarea>
+
+ <button type="submit" for="pki-login-form" class="mt-4 btn">Submit</button>
+
+ </form>
+</template> \ No newline at end of file
diff --git a/front-end/src/components/Login/UserPass.vue b/front-end/src/components/Login/UserPass.vue
new file mode 100644
index 0000000..b25a335
--- /dev/null
+++ b/front-end/src/components/Login/UserPass.vue
@@ -0,0 +1,118 @@
+<script setup lang="ts">
+import { ref, shallowRef, reactive, defineAsyncComponent } from 'vue'
+import { useTimeoutFn, set } from '@vueuse/core'
+import { useVuelidate } from '@vuelidate/core'
+import { isEqual } from 'lodash-es'
+import { required, maxLength, minLength, email, helpers } from '@vuelidate/validators'
+import {
+ useVuelidateWrapper, useMfaLogin, totpMfaProcessor, IMfaFlowContinuiation, MfaMethod,
+ apiCall, useMessage, useWait, debugLog, WebMessage
+} from '@vnuge/vnlib.browser'
+const OptInput = defineAsyncComponent(() => import('../global/OtpInput.vue'))
+
+const { setMessage } = useMessage();
+const { waiting } = useWait();
+
+//Setup mfa login with TOTP support
+const { login } = useMfaLogin([ totpMfaProcessor() ])
+
+const mfaUpgrade = shallowRef<IMfaFlowContinuiation | undefined>();
+
+const mfaTimeout = ref<number>(600 * 1000);
+const mfaTimer = useTimeoutFn(() => {
+ //Clear upgrade message
+ set(mfaUpgrade, undefined);
+ setMessage('Your TOTP request has expired')
+}, mfaTimeout, { immediate: false })
+
+const vState = reactive({ username: '', password: '' })
+
+const rules = {
+ username: {
+ required: helpers.withMessage('Email cannot be empty', required),
+ email: helpers.withMessage('Your email address is not valid', email),
+ maxLength: helpers.withMessage('Email address must be less than 50 characters', maxLength(50))
+ },
+ password: {
+ required: helpers.withMessage('Password cannot be empty', required),
+ minLength: helpers.withMessage('Password must be at least 8 characters', minLength(8)),
+ maxLength: helpers.withMessage('Password must have less than 128 characters', maxLength(128))
+ }
+}
+
+const v$ = useVuelidate(rules, vState)
+const { validate } = useVuelidateWrapper(v$ as any);
+
+const onSubmit = async () => {
+
+ // If the form is not valid set the error message
+ if (!await validate()) {
+ return
+ }
+
+ // Run login in an apicall wrapper
+ await apiCall(async ({ toaster }) => {
+
+ //Attempt to login
+ const response = await login(
+ v$.value.username.$model,
+ v$.value.password.$model
+ );
+
+ debugLog('Mfa-login', response);
+
+ //See if the response is a web message
+ if (response.getResultOrThrow) {
+ (response as WebMessage).getResultOrThrow();
+ }
+
+ //Try to get response as a flow continuation
+ const mfa = response as IMfaFlowContinuiation
+
+ // Response is a totp upgrade request
+ if (isEqual(mfa.type, MfaMethod.TOTP)) {
+ //Store the upgrade message
+ set(mfaUpgrade, mfa);
+ //Setup timeout timer
+ set(mfaTimeout, mfa.expires! * 1000);
+ mfaTimer.start();
+ }
+ //If login without mfa was successful
+ else if (response.success) {
+ // Push a new toast message
+ toaster.general.success({
+ title: 'Success',
+ text: 'You have been logged in',
+ })
+ }
+ })
+}
+</script>
+
+<template>
+ <form v-if="mfaUpgrade" @submit.prevent="" class="max-w-sm mx-auto">
+ <OptInput :upgrade="mfaUpgrade" />
+ <p id="helper-text-explanation" class="mt-2 text-sm text-gray-500 dark:text-gray-400">
+ Please enter your 6 digit TOTP code from your authenticator app.
+ </p>
+ </form>
+ <form v-else class="space-y-4 md:space-y-6" action="#" @submit.prevent="onSubmit" :disabled="waiting">
+ <fieldset>
+ <label for="email" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Your email</label>
+ <input type="email" name="email" id="email" class="input" placeholder="name@company.com" required
+ v-model="v$.username.$model"
+ >
+ </fieldset>
+ <fieldset>
+ <label for="password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Password</label>
+ <input type="password" name="password" id="password" class="input" placeholder="••••••••" required
+ v-model="v$.password.$model"
+ >
+ </fieldset>
+ <button type="submit" class="btn">Sign in</button>
+ </form>
+</template>
+
+<style scoped lang="scss">
+
+</style> \ No newline at end of file
diff --git a/front-end/src/components/Settings.vue b/front-end/src/components/Settings.vue
new file mode 100644
index 0000000..e03ae61
--- /dev/null
+++ b/front-end/src/components/Settings.vue
@@ -0,0 +1,64 @@
+<script setup lang="ts">
+import { useDark } from '@vueuse/core';
+import { useStore } from '../store';
+import Oauth2Apps from './Settings/Oauth2Apps.vue';
+import PasswordReset from './Settings/PasswordReset.vue';
+import PkiSettings from './Settings/PkiSettings.vue';
+import TotpSettings from './Settings/TotpSettings.vue';
+
+const store = useStore();
+const darkMode = useDark();
+
+</script>
+
+<template>
+ <div class="w-full sm:pt-10 lg:pl-[15%] sm:pl-4 px-4">
+ <h2 class="text-2xl font-bold">Settings</h2>
+ <div class="flex flex-col w-full max-w-3xl gap-10 mt-3">
+
+ <div class="">
+ <h3 class="text-xl font-bold">
+ General
+ </h3>
+ <div class="grid grid-cols-1 gap-3 p-4">
+ <div class="">
+ <label class="relative inline-flex items-center cursor-pointer">
+ <input type="checkbox" value="" class="sr-only peer" v-model="darkMode">
+ <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
+ <span class="text-sm font-medium text-gray-900 ms-3 dark:text-gray-300">Dark mode</span>
+ </label>
+ </div>
+ <div class="">
+ <label class="relative inline-flex items-center cursor-pointer">
+ <input type="checkbox" value="" class="sr-only peer" v-model="store.autoHeartbeat">
+ <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
+ <span class="text-sm font-medium text-gray-900 ms-3 dark:text-gray-300">Stay signed in</span>
+ </label>
+ </div>
+ </div>
+ </div>
+
+ <PasswordReset />
+
+ <div class="">
+ <h3 class="text-xl font-bold">Multi Factor Auth</h3>
+
+ <div class="relative mt-4 py-2.5">
+ <TotpSettings />
+ </div>
+ </div>
+
+ <PkiSettings />
+
+ <!-- Only load component if oauth2 plugin is enabled -->
+ <div v-if="store.oauth2" class="">
+ <Oauth2Apps />
+ </div>
+
+ </div>
+ </div>
+</template>
+
+<style lang="scss">
+
+</style> \ No newline at end of file
diff --git a/front-end/src/components/Settings/Oauth2Apps.vue b/front-end/src/components/Settings/Oauth2Apps.vue
new file mode 100644
index 0000000..11f5d1e
--- /dev/null
+++ b/front-end/src/components/Settings/Oauth2Apps.vue
@@ -0,0 +1,85 @@
+<script setup lang="ts">
+import { defineAsyncComponent, shallowRef } from 'vue';
+import { useStore } from '../../store';
+import { formatTimeAgo, set } from '@vueuse/core';
+import { OAuth2Application } from '../../store/userProfile';
+import { ServerDataBuffer, useDataBuffer } from '@vnuge/vnlib.browser';
+const Dialog = defineAsyncComponent(() => import('../global/Dialog.vue'));
+
+const { oauth2 } = useStore();
+
+const editBuffer = shallowRef<ServerDataBuffer<OAuth2Application, void> | undefined>();
+const editApp = (app: OAuth2Application) =>{
+ //Init new server data buffer to push updates
+ const buffer = useDataBuffer(app, ({ buffer }) => oauth2.updateMeta(buffer));
+ set(editBuffer, buffer);
+}
+
+const cancelEdit = () => set(editBuffer, undefined);
+
+</script>
+
+<template>
+ <div class="">
+ <div class="flex flex-row justify-between">
+ <h3 class="text-xl font-bold">OAuth2 Apps</h3>
+ <div class="">
+
+ <button type="button" class="btn blue" @click.prevent="">
+ <div class="flex flex-row items-center gap-1.5 ">
+ New
+ </div>
+ </button>
+
+ </div>
+ </div>
+
+ <div class="relative mt-2 overflow-x-auto shadow-md sm:rounded">
+ <table class="w-full text-sm text-left text-gray-500 rtl:text-right dark:text-gray-400">
+ <thead class="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
+ <tr>
+ <th scope="col" class="px-4 py-2">
+ Client ID
+ </th>
+ <th scope="col" class="px-4 py-2">
+ Name
+ </th>
+ <th scope="col" class="px-4 py-2">
+ Created
+ </th>
+ <th scope="col" class="px-4 py-2">
+ Action
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="app in oauth2.apps" :key="app.Id" class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
+ <th scope="row" class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
+ {{ app.client_id }}
+ </th>
+ <td class="px-4 py-3">
+ {{ app.name }}
+ </td>
+ <td class="px-4 py-3">
+ {{ formatTimeAgo(app.Created) }}
+ </td>
+ <td class="px-4 py-3">
+ <button
+ @click.prevent="editApp(app)"
+ class="font-medium text-blue-600 dark:text-blue-500 hover:underline">
+ Edit
+ </button>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <Dialog :open="editBuffer!= undefined" title="Edit App" @cancel="cancelEdit">
+ <template #body>
+ Hello world
+ </template>
+ </Dialog>
+ </div>
+</template>
+
+<style lang="scss"></style> \ No newline at end of file
diff --git a/front-end/src/components/Settings/PasswordReset.vue b/front-end/src/components/Settings/PasswordReset.vue
new file mode 100644
index 0000000..41633b7
--- /dev/null
+++ b/front-end/src/components/Settings/PasswordReset.vue
@@ -0,0 +1,156 @@
+<script setup lang="ts">
+import { computed, defineAsyncComponent, shallowReactive } from 'vue';
+import { useStore } from '../../store';
+import { get, useToggle } from '@vueuse/core';
+import { MfaMethod, apiCall, useUser, useVuelidateWrapper } from '@vnuge/vnlib.browser';
+import { includes, isEmpty, toSafeInteger } from 'lodash-es';
+import { useVuelidate } from '@vuelidate/core'
+import { required, maxLength, minLength, helpers } from '@vuelidate/validators'
+const Dialog = defineAsyncComponent(() => import('../global/Dialog.vue'));
+
+const store = useStore();
+const { resetPassword } = useUser()
+const totpEnabled = computed(() => includes(store.mfaEndabledMethods, MfaMethod.TOTP))
+
+const [ isOpen, toggleOpen ] = useToggle(false)
+const vState = shallowReactive({
+ current: '',
+ newPassword: '',
+ repeatPassword: '',
+ totpCode: ''
+})
+
+const rules = computed(() => {
+ return {
+ current: {
+ required: helpers.withMessage('Current password cannot be empty', required),
+ minLength: helpers.withMessage('Current password must be at least 8 characters', minLength(8)),
+ maxLength: helpers.withMessage('Current password must have less than 128 characters', maxLength(128))
+ },
+ newPassword: {
+ notOld: helpers.withMessage('New password cannot be the same as your current password', (value: string) => value != vState.current),
+ required: helpers.withMessage('New password cannot be empty', required),
+ minLength: helpers.withMessage('New password must be at least 8 characters', minLength(8)),
+ maxLength: helpers.withMessage('New password must have less than 128 characters', maxLength(128))
+ },
+ repeatPassword: {
+ sameAs: helpers.withMessage('Your new passwords do not match', (value: string) => value == vState.newPassword),
+ required: helpers.withMessage('Repeast password cannot be empty', required),
+ minLength: helpers.withMessage('Repeast password must be at least 8 characters', minLength(8)),
+ maxLength: helpers.withMessage('Repeast password must have less than 128 characters', maxLength(128))
+ },
+ totpCode: {
+ required: helpers.withMessage('TOTP code cannot be empty', (value: string) => get(totpEnabled) ? !isEmpty(value) : true),
+ minLength: helpers.withMessage('TOTP code must be at least 6 characters', minLength(6)),
+ maxLength: helpers.withMessage('TOTP code must have less than 12 characters', maxLength(12))
+ }
+ }
+})
+
+const v$ = useVuelidate(rules, vState)
+const { validate } = useVuelidateWrapper(v$ as any)
+
+const onSubmit = async () => {
+ if (!await validate()) return
+
+ apiCall(async ({toaster}) => {
+ //Rest password and pass totp code
+ const { getResultOrThrow } = await resetPassword(vState.current, vState.newPassword, { totp_code: toSafeInteger(vState.totpCode) })
+ getResultOrThrow()
+
+ toaster.general.success({
+ title: 'Password Reset',
+ text: 'Your password has been reset'
+ });
+
+ onCancel()
+ })
+}
+
+const onCancel = () => {
+ vState.current = ''
+ vState.newPassword = ''
+ vState.repeatPassword = ''
+ vState.totpCode = ''
+ v$.value.$reset()
+ toggleOpen(false)
+}
+
+</script>
+
+<template>
+ <div class="">
+
+ <div class="flex flex-row justify-between w-full">
+ <h3 class="text-xl font-bold">Password</h3>
+
+ <div class="flex flex-row justify-end">
+ <button class="btn blue" @click="toggleOpen(true)">Reset Password</button>
+ </div>
+ </div>
+
+ <Dialog :open="isOpen" title="Reset Password" @cancel="onCancel">
+ <template #body>
+ <div class="p-4">
+
+ <form @submit.prevent="onSubmit">
+
+ <div class="mb-4">
+ <label for="current_password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Current</label>
+ <input
+ v-model="v$.current.$model"
+ type="password"
+ id="current_password"
+ class="input"
+ :class="{ 'error': v$.current.$error, 'dirty': v$.current.$dirty }"
+ placeholder="•••••••••"
+ required
+ >
+ </div>
+ <div class="mb-4">
+ <label for="password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">New Password</label>
+ <input
+ v-model="v$.newPassword.$model"
+ type="password"
+ id="password"
+ class="input"
+ :class="{ 'error': v$.newPassword.$error, 'dirty': v$.newPassword.$dirty }"
+ placeholder="•••••••••"
+ required
+ >
+ </div>
+ <div class="mb-4">
+ <label for="confirm_password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Confirm password</label>
+ <input
+ v-model="v$.repeatPassword.$model"
+ type="password"
+ id="confirm_password"
+ class="input"
+ :class="{ 'error': v$.repeatPassword.$error, 'dirty': v$.repeatPassword.$dirty }"
+ placeholder="•••••••••"
+ required
+ >
+ </div>
+ <div v-if="totpEnabled" class="mb-4">
+ <label for="totp_code" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">TOTP Code</label>
+ <input
+ v-model="v$.totpCode.$model"
+ type="text"
+ id="totp_code"
+ class="input"
+ :class="{ 'error': v$.totpCode.$error, 'dirty': v$.totpCode.$dirty }"
+ placeholder="6 Digit Code"
+ required
+ >
+ </div>
+ <div class="ml-auto w-fit">
+ <button type="submit" class="btn blue">
+ Submit
+ </button>
+ </div>
+ </form>
+ </div>
+ </template>
+ </Dialog>
+ </div>
+</template> \ No newline at end of file
diff --git a/front-end/src/components/Settings/PkiSettings.vue b/front-end/src/components/Settings/PkiSettings.vue
new file mode 100644
index 0000000..5fa5c93
--- /dev/null
+++ b/front-end/src/components/Settings/PkiSettings.vue
@@ -0,0 +1,216 @@
+<script setup lang="ts">
+import { defineAsyncComponent, shallowRef } from 'vue';
+import { useStore } from '../../store';
+import { get, set } from '@vueuse/core';
+import { PkiPublicKey, apiCall, debugLog, useConfirm, useGeneralToaster } from '@vnuge/vnlib.browser';
+import { storeToRefs } from 'pinia';
+import { isEmpty, toLower } from 'lodash-es';
+const Dialog = defineAsyncComponent(() => import('../global/Dialog.vue'));
+
+const store = useStore();
+const { pkiPublicKeys } = storeToRefs(store);
+const { reveal } = useConfirm()
+const toaster = useGeneralToaster()
+
+const keyData = shallowRef<string | undefined>()
+const showAddKeyDialog = () => set(keyData, '');
+const hideAddKeyDialog = () => set(keyData, undefined);
+
+const removeKey = async (key: PkiPublicKey) => {
+ const { isCanceled } = await reveal({
+ title: 'Remove Key',
+ text: `Are you sure you want to remove ${key.kid}?`
+ });
+
+ if (isCanceled) return
+
+ apiCall(async ({ toaster }) => {
+ //const { getResultOrThrow } = await store.pkiConfig.removeKey(key.kid);
+ //await getResultOrThrow();
+
+ toaster.general.success({
+ title: 'Key Removed',
+ text: `${key.kid} has been successfully removed`
+ })
+ })
+}
+
+const onDisable = async () => {
+ const { isCanceled } = await reveal({
+ title: 'Are you sure?',
+ text: 'This will disable PKI authentication for your account.'
+ })
+ if (isCanceled) {
+ return;
+ }
+
+ //Delete pki
+ await apiCall(async () => {
+
+ //Disable pki
+ //TODO: require password or some upgrade to disable
+ const { success } = await store.pkiConfig.disable();
+
+ if (success) {
+ toaster.success({
+ title: 'Success',
+ text: 'PKI authentication has been disabled.'
+ })
+ }
+ else {
+ toaster.error({
+ title: 'Error',
+ text: 'PKI authentication could not be disabled.'
+ })
+ }
+
+ //Refresh the status
+ store.mfaRefreshMethods()
+ });
+}
+
+const onAddKey = async () => {
+
+ if (window.crypto.subtle == null) {
+ toaster.error({ title: "Your browser does not support PKI authentication." })
+ return;
+ }
+
+ const jwkKeyData = get(keyData)
+
+ //Validate key data
+ if (!jwkKeyData || isEmpty(jwkKeyData)) {
+ toaster.error({ title: "Please enter key data" })
+ return;
+ }
+
+ let jwk: PkiPublicKey & JsonWebKey;
+ try {
+ //Try to parse as jwk
+ jwk = JSON.parse(jwkKeyData)
+ if (isEmpty(jwk.use)
+ || isEmpty(jwk.kty)
+ || isEmpty(jwk.alg)
+ || isEmpty(jwk.kid)
+ || isEmpty(jwk.x)
+ || isEmpty(jwk.y)) {
+ throw new Error("Invalid JWK");
+ }
+ }
+ catch (e) {
+ //Write error to debug log
+ debugLog(e)
+ toaster.error({ title: "Invalid JWK", text:"The public key you entered is not a valid JWK" })
+ return;
+ }
+
+ //Send to server
+ await apiCall(async () => {
+
+ //init/update the key
+ //TODO: require password or some upgrade to disable
+ const { getResultOrThrow } = await store.pkiConfig.addOrUpdate(jwk);
+ const result = getResultOrThrow();
+
+ toaster.success({
+ title: 'Success',
+ text: result
+ })
+
+ hideAddKeyDialog()
+ })
+}
+
+</script>
+
+<template>
+ <div class="">
+ <div class="flex flex-row justify-between">
+ <h3 class="text-xl font-bold">Authentication Keys</h3>
+ <div class="">
+
+ <button type="button" class="btn blue" @click.prevent="showAddKeyDialog">
+ <div class="flex flex-row items-center gap-1.5">
+ Add
+ </div>
+ </button>
+ <button type="button" class="btn red" @click.prevent="onDisable">
+ <div class="flex flex-row items-center gap-1.5">
+ Disable
+ </div>
+ </button>
+ </div>
+ </div>
+
+ <div class="relative mt-2 overflow-x-auto shadow-md sm:rounded">
+ <table class="w-full text-sm text-left text-gray-500 rtl:text-right dark:text-gray-400">
+ <thead class="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
+ <tr>
+ <th scope="col" class="px-4 py-2">
+ KeyID
+ </th>
+ <th scope="col" class="px-4 py-2">
+ Algorithm
+ </th>
+ <th scope="col" class="px-4 py-2">
+ Curve
+ </th>
+ <th scope="col" class="px-4 py-2">
+ Action
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="key in pkiPublicKeys" :key="key.kid"
+ class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
+ <th scope="row" class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
+ {{ toLower(key.kid) }}
+ </th>
+ <td class="px-4 py-3">
+ {{ key.alg }}
+ </td>
+ <td class="px-4 py-3">
+ {{ key.crv }}
+ </td>
+ <td class="px-4 py-3">
+ <button @click.prevent="removeKey(key)"
+ class="font-medium text-red-600 dark:text-red-500 hover:underline">
+ Remove
+ </button>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+
+ </div>
+ <p class="p-3 text-sm text-gray-500 rtl:text-right dark:text-gray-400">
+ Above are your account authentication keys. You can use these keys to sign in to your account using the PKI
+ authentication method.
+ </p>
+ <Dialog :open="keyData != undefined" title="Add Key" @cancel="hideAddKeyDialog">
+ <template #body>
+ <div class="p-4">
+
+ <label for="message" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
+ Add a single Json Web Key (JWK) encoded public key to your account.
+ </label>
+
+ <textarea
+ id="add-pki-key"
+ rows="6"
+ v-model="keyData"
+ placeholder="Paste your JWK..."
+ class="block w-full text-sm text-gray-900 border border-gray-300 rounded bg-gray-50 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
+ >
+ </textarea>
+
+ <div class="flex justify-end mt-3 row">
+ <button class="btn blue" @click="onAddKey()">Add Key</button>
+ </div>
+ </div>
+ </template>
+ </Dialog>
+ </div>
+</template>
+
+<style lang="scss"></style> \ No newline at end of file
diff --git a/front-end/src/components/Settings/TotpSettings.vue b/front-end/src/components/Settings/TotpSettings.vue
new file mode 100644
index 0000000..cc8642f
--- /dev/null
+++ b/front-end/src/components/Settings/TotpSettings.vue
@@ -0,0 +1,169 @@
+<script setup lang="ts">
+import { computed, defineAsyncComponent, shallowRef } from 'vue';
+import { useStore } from '../../store';
+import { set, get } from '@vueuse/core';
+import { MfaMethod, useGeneralToaster, usePassConfirm, useSession } from '@vnuge/vnlib.browser';
+import { defaultTo, includes, isEmpty, isNil } from 'lodash-es';
+import { TOTP } from 'otpauth'
+import base32Encode from 'base32-encode'
+const QrCode = defineAsyncComponent(() => import('qrcode.vue'));
+const Dialog = defineAsyncComponent(() => import('../global/Dialog.vue'));
+const VOtpInput = defineAsyncComponent(() => import('vue3-otp-input'))
+
+interface TotpConfig {
+ secret: string;
+ readonly issuer: string;
+ readonly algorithm: string;
+ readonly digits?: number;
+ readonly period?: number;
+}
+
+const { KeyStore } = useSession()
+const { elevatedApiCall } = usePassConfirm()
+const { success, error } = useGeneralToaster()
+const store = useStore()
+const newTotpConfig = shallowRef<TotpConfig | undefined>()
+const totpEnabled = computed(() => includes(store.mfaEndabledMethods, MfaMethod.TOTP))
+
+const qrCode = computed(() => {
+
+ const m = get(newTotpConfig);
+
+ if (isNil(m)) {
+ return ''
+ }
+
+ // Build the totp qr codeurl
+ const params = new URLSearchParams()
+ params.append('secret', m.secret)
+ params.append('issuer', m.issuer)
+ params.append('algorithm', m.algorithm)
+ params.append('digits', defaultTo(m.digits, 6).toString())
+ params.append('period', defaultTo(m.period, 30).toString())
+
+ return `otpauth://totp/${m.issuer}:${store.userName}?${params.toString()}`
+})
+
+const showUpdateDialog = computed(() => !isEmpty(get(qrCode)))
+
+const disableTotp = async () => {
+
+ elevatedApiCall(async ({ password, toaster }) =>{
+ const { getResultOrThrow } = await store.mfaConfig.disableMethod(MfaMethod.TOTP, password);
+ getResultOrThrow();
+
+ toaster.general.success({
+ title: 'TOTP Disabled',
+ text: 'TOTP has been disabled for your account.'
+ })
+ })
+}
+
+const addOrUpdate = async () => {
+
+ elevatedApiCall(async ({ password }) =>{
+ const { getResultOrThrow } = await store.mfaConfig.initOrUpdateMethod<TotpConfig>(MfaMethod.TOTP, password);
+ const newConfig = getResultOrThrow();
+
+ // Decrypt the server sent secret
+ const decSecret = await KeyStore.decryptDataAsync(newConfig.secret);
+ // Encode the secret to base32
+ newConfig.secret = base32Encode(decSecret, 'RFC3548', { padding: false })
+
+ set(newTotpConfig, newConfig);
+ })
+}
+
+const onVerifyOtp = async (code: string) => {
+ // Create a new TOTP instance from the current message
+ const totp = new TOTP(get(newTotpConfig))
+
+ // validate the code
+ const valid = totp.validate({ token: code, window: 4 })
+
+ if (valid) {
+ success({
+ title: 'Success',
+ text: 'Your code is valid and TOPT has been enabled.'
+ })
+
+ //Close the dialog
+ set(newTotpConfig, undefined)
+
+ } else {
+ error({ title: 'The code you entered is invalid.'})
+ }
+}
+
+</script>
+
+<template>
+
+ <div class="flex flex-row items-center justify-between">
+ <div class="relative me-4">
+ <h4 class="text-base font-bold">
+ TOTP
+ </h4>
+ <span
+ :class="[totpEnabled ? 'visible' : 'invisible' ]"
+ class="absolute top-0 w-3 h-3 bg-green-500 border-2 border-white rounded-full -end-5 dark:border-gray-800"
+ >
+ </span>
+ </div>
+ <div v-if="totpEnabled" class="flex" @click="addOrUpdate()">
+ <button class="btn light">
+ Regenerate
+ </button>
+ <button class="btn red" @click="disableTotp()">
+ Disable
+ </button>
+ </div>
+ <div v-else>
+ <button class="btn green" @click="addOrUpdate()">
+ Enable
+ </button>
+ </div>
+ </div>
+ <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">
+ Use Time based One Time Passcodes (TOTP) to secure your account as a second factor authentication.
+ </p>
+
+ <Dialog :open="showUpdateDialog" title="TOTP Secret" @cancel="">
+ <template #body>
+ <div class="p-4 pb-8">
+ <div class="flex flex-col items-center justify-center">
+ <div>
+ <p class="text-sm text-gray-500 dark:text-gray-400">
+ Scan this QR code with your authenticator app to add this account.
+ </p>
+ </div>
+ <div class="mt-4">
+ <QrCode :size="200" level="L" :value="qrCode" />
+ </div>
+ <div class="w-full mt-4">
+ <input
+ type="text"
+ id="disabled-input-2"
+ aria-label="disabled input 2"
+ class="bg-gray-100 border border-gray-300 text-gray-900 text-sm rounded focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 cursor-not-allowed dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-gray-400 dark:focus:ring-blue-500 dark:focus:border-blue-500"
+ :value="qrCode"
+ disabled
+ readonly
+ >
+ </div>
+
+ <div class="mx-auto mt-4">
+ <VOtpInput class="otp-input" input-type="letter-numeric" separator=""
+ input-classes="rounded" :num-inputs="6" value="" @on-change=""
+ @on-complete="onVerifyOtp" />
+ </div>
+ <p class="mt-2 text-sm text-gray-500 dark:text-gray-400">
+ Enter the 6 digit code from your authenticator app to verify.
+ </p>
+ </div>
+ </div>
+ </template>
+ </Dialog>
+</template>
+
+<style lang="scss"></style> \ No newline at end of file
diff --git a/front-end/src/components/SideMenuItem.vue b/front-end/src/components/SideMenuItem.vue
new file mode 100644
index 0000000..f2ebb89
--- /dev/null
+++ b/front-end/src/components/SideMenuItem.vue
@@ -0,0 +1,42 @@
+<script setup lang="ts">
+import { storeToRefs } from 'pinia';
+import { useStore, TabId } from '../store';
+import { toRefs } from 'vue';
+import { noop } from 'lodash-es';
+import { get, set } from '@vueuse/core';
+
+const props = defineProps<{
+ tab: TabId;
+ name: String,
+ disabled?: Boolean
+}>()
+
+const store = useStore()
+const { activeTab } = storeToRefs(store)
+const { name, disabled, tab } = toRefs(props)
+
+//const isActive = (tab: TabId, activeTab: TabId) => isEqual(activeTab, tab);
+const setActiveTab = (tab: TabId) => get(disabled) ? noop() : set(activeTab, tab)
+
+</script>
+
+<template>
+ <li>
+ <a href="/" @click.prevent="setActiveTab(tab)" class="lia group" :class="{ 'pointer-events-none disabled':disabled }">
+ <svg class="w-5 h-5 text-gray-500 transition duration-75 dark:text-gray-400 group-hover:text-gray-900 dark:group-hover:text-white"
+ aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 22 21">
+ <slot name="icon" />
+ </svg>
+ <span class="ms-3">{{ name }}</span>
+ </a>
+ </li>
+</template>
+
+<style lang="scss">
+ .lia{
+ @apply flex items-center p-2 text-gray-900 rounded-lg dark:text-white hover:bg-gray-100 dark:hover:bg-gray-700;
+ &.disabled{
+ @apply opacity-50;
+ }
+ }
+</style> \ No newline at end of file
diff --git a/front-end/src/components/global/ConfirmPrompt.vue b/front-end/src/components/global/ConfirmPrompt.vue
new file mode 100644
index 0000000..c8dc944
--- /dev/null
+++ b/front-end/src/components/global/ConfirmPrompt.vue
@@ -0,0 +1,65 @@
+<script setup lang="ts">
+import { defaultTo } from 'lodash-es'
+import { ref } from 'vue'
+import { onClickOutside } from '@vueuse/core'
+import { useConfirm } from '@vnuge/vnlib.browser'
+import Dialog from './Dialog.vue'
+
+interface MessageType{
+ title: string,
+ text: string
+}
+
+//Use component side of confirm
+const { isRevealed, confirm, cancel, onReveal } = useConfirm()
+
+const dialog = ref(null)
+const message = ref<MessageType | undefined>()
+
+//Cancel prompt when user clicks outside of dialog, only when its open
+onClickOutside(dialog, () => isRevealed.value ? cancel() : null)
+
+//Set message on reveal
+onReveal(m => message.value = defaultTo(m, {}));
+
+
+</script>
+<template>
+ <!-- Main modal -->
+ <Dialog title="Confirm?" :open="isRevealed" @cancel="cancel">
+ <template #body>
+ <div class="p-4 space-y-4 md:p-5">
+ <p class="text-base leading-relaxed text-gray-500 dark:text-gray-400">
+ {{ message?.text }}
+ </p>
+ </div>
+ <!-- Modal footer -->
+ <div class="flex items-center justify-end p-4 border-t border-gray-200 rounded-b md:p-5 dark:border-gray-600">
+ <button
+ @click="confirm()"
+ type="button"
+ class="btn blue">
+ Confirm
+ </button>
+
+ <button
+ @click="cancel()"
+ type="button"
+ class="btn light">
+ Cancel
+ </button>
+ </div>
+ </template>
+ </Dialog>
+
+</template>
+
+<style scoped lang="scss">
+.modal-entry{
+ @apply hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-50 justify-center items-center w-full md:inset-0 h-[calc(100%-1rem)] max-h-full;
+}
+
+.modal-content-container{
+ @apply text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ms-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white;
+}
+</style> \ No newline at end of file
diff --git a/front-end/src/components/global/Dialog.vue b/front-end/src/components/global/Dialog.vue
new file mode 100644
index 0000000..949e750
--- /dev/null
+++ b/front-end/src/components/global/Dialog.vue
@@ -0,0 +1,61 @@
+<script setup lang="ts">
+import { noop } from 'lodash-es'
+import { ref, toRefs } from 'vue'
+import { Dialog } from '@headlessui/vue'
+import { onClickOutside, get } from '@vueuse/core'
+
+const emit = defineEmits(['cancel'])
+const props = defineProps<{ title: string | undefined, open: boolean }>()
+
+const { open, title } = toRefs(props)
+
+const dialog = ref(null)
+const cancel = () => emit('cancel')
+
+//Cancel prompt when user clicks outside of dialog, only when its open
+onClickOutside(dialog, () => get(open) ? cancel() : noop())
+
+</script>
+<template>
+ <!-- Main modal -->
+ <Dialog :open="open" id="static-modal" data-modal-backdrop="static" tabindex="-1"
+ class="overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-10 justify-center items-center w-full md:inset-0 h-[calc(100%-1rem)] max-h-full">
+ <div class="fixed inset-0 bg-black/30" aria-hidden="true" />
+
+ <div class="relative w-full max-w-xl max-h-full p-4 mx-auto mt-2 md:mt-32">
+ <!-- Modal content -->
+ <div class="relative bg-white rounded shadow dark:bg-gray-700" ref="dialog">
+ <!-- Modal header -->
+ <div class="flex items-center justify-between p-3 border-b rounded-t md:px-5 dark:border-gray-600">
+ <h3 class="text-xl font-semibold text-gray-900 dark:text-white">
+ {{ title }}
+ </h3>
+ <button @click="cancel()" type="button"
+ class="inline-flex items-center justify-center w-8 h-8 text-sm text-gray-400 bg-transparent rounded-lg hover:bg-gray-200 hover:text-gray-900 ms-auto dark:hover:bg-gray-600 dark:hover:text-white"
+ data-modal-hide="static-modal">
+ <svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none"
+ viewBox="0 0 14 14">
+ <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
+ d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6" />
+ </svg>
+ <span class="sr-only">Close modal</span>
+ </button>
+ </div>
+
+ <!-- Modal body -->
+ <slot name="body" />
+
+ </div>
+ </div>
+ </Dialog>
+</template>
+
+<style scoped lang="scss">
+.modal-entry {
+ @apply hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-50 justify-center items-center w-full md:inset-0 h-[calc(100%-1rem)] max-h-full;
+}
+
+.modal-content-container {
+ @apply text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ms-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white;
+}
+</style> \ No newline at end of file
diff --git a/front-end/src/components/global/OtpInput.vue b/front-end/src/components/global/OtpInput.vue
new file mode 100644
index 0000000..59f6fa1
--- /dev/null
+++ b/front-end/src/components/global/OtpInput.vue
@@ -0,0 +1,54 @@
+<script setup lang="ts">
+import { toRefs } from 'vue';
+import { IMfaFlowContinuiation, apiCall, useMessage, useWait } from '@vnuge/vnlib.browser';
+import { toSafeInteger } from 'lodash-es';
+import VOtpInput from 'vue3-otp-input';
+
+const emit = defineEmits(['clear'])
+
+const props = defineProps<{
+ upgrade: IMfaFlowContinuiation
+}>()
+
+const { upgrade } = toRefs(props)
+const { waiting } = useWait();
+const { onInput } = useMessage();
+
+const SubimitTotp = (code: string) => {
+
+ //If a request is still pending, do nothing
+ if (waiting.value) {
+ return
+ }
+
+ apiCall(async ({ toaster }) => {
+ //Submit totp code
+ const res = await upgrade.value.submit({ code: toSafeInteger(code) })
+ res.getResultOrThrow()
+
+ emit('clear')
+
+ // Push a new toast message
+ toaster.general.success({
+ title: 'Success',
+ text: 'You have been logged in',
+ })
+ })
+}
+
+</script>
+
+<template>
+ <div id="totp-login-form">
+ <div class="flex">
+ <div class="mx-auto mt-4">
+ <VOtpInput class="otp-input" input-type="letter-numeric" :is-disabled="waiting" separator=""
+ input-classes="primary input rounded" :num-inputs="6" value="" @on-change="onInput"
+ @on-complete="SubimitTotp" />
+ </div>
+ </div>
+ </div>
+</template>
+
+<style lang="scss">
+</style> \ No newline at end of file
diff --git a/front-end/src/components/global/PasswordPrompt.vue b/front-end/src/components/global/PasswordPrompt.vue
new file mode 100644
index 0000000..a9a5fca
--- /dev/null
+++ b/front-end/src/components/global/PasswordPrompt.vue
@@ -0,0 +1,118 @@
+<script setup lang="ts">
+import { defaultTo, noop } from 'lodash-es'
+import { reactive, ref } from 'vue'
+import { get, onClickOutside } from '@vueuse/core'
+import { usePassConfirm, useVuelidateWrapper } from '@vnuge/vnlib.browser'
+import { useVuelidate } from '@vuelidate/core'
+import { helpers, required, maxLength } from '@vuelidate/validators'
+import Dialog from './Dialog.vue'
+
+interface MessageType{
+ title: string,
+ text: string
+}
+
+//Use component side of pw prompt
+const { isRevealed, confirm, cancel, onReveal } = usePassConfirm()
+
+const dialog = ref(null)
+const message = ref<MessageType | undefined>()
+
+const pwState = reactive({ password: '' })
+
+const rules = {
+ password: {
+ required: helpers.withMessage('Please enter your password', required),
+ maxLength: helpers.withMessage('Password must be less than 100 characters', maxLength(100))
+ }
+}
+
+const v$ = useVuelidate(rules, pwState, { $lazy: true })
+
+//Wrap validator so we an display error message on validation, defaults to the form toaster
+const { validate } = useVuelidateWrapper(v$ as any);
+
+const formSubmitted = async function () {
+ //Calls validate on the vuelidate instance
+ if (!await validate()) {
+ return
+ }
+
+ //Store pw copy
+ const password = v$.value.password.$model;
+
+ //Clear the password form
+ v$.value.password.$model = '';
+ v$.value.$reset();
+
+ //Pass the password to the confirm function
+ confirm({ password });
+}
+
+const close = function () {
+ // Clear the password form
+ v$.value.password.$model = '';
+ v$.value.$reset();
+
+ //Close prompt
+ cancel(null);
+}
+
+//Cancel prompt when user clicks outside of dialog, only when its open
+onClickOutside(dialog, () => get(isRevealed) ? close() : noop())
+
+//Set message on reveal
+onReveal(m => message.value = defaultTo(m, {}));
+
+</script>
+<template>
+ <!-- Main modal -->
+ <Dialog title="Enter Password" :open="isRevealed" @cancel="cancel">
+ <template #body>
+ <div class="p-4 space-y-4 md:p-5">
+ <p class="text-base leading-relaxed text-gray-500 dark:text-gray-400">
+ Please enter your password in order to continue.
+ </p>
+ <form class="mb-6" @submit="formSubmitted">
+ <label for="password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Password</label>
+ <input
+ type="password"
+ id="password"
+ v-model.trim="v$.password.$model"
+ class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
+ placeholder="•••••••••"
+ required
+ >
+ </form>
+ </div>
+ <!-- Modal footer -->
+ <div class="flex items-center justify-end p-4 border-t border-gray-200 rounded-b md:p-5 dark:border-gray-600">
+ <button
+ @click="formSubmitted"
+ type="button"
+ class="btn blue"
+ >
+ Confirm
+ </button>
+
+ <button
+ @click="close"
+ type="button"
+ class="btn light">
+ Cancel
+ </button>
+ </div>
+ </template>
+ </Dialog>
+
+</template>
+
+<style scoped lang="scss">
+.modal-entry{
+ @apply hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-50 justify-center items-center w-full md:inset-0 h-[calc(100%-1rem)] max-h-full;
+}
+
+.modal-content-container{
+ @apply text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ms-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white;
+}
+</style> \ No newline at end of file
diff --git a/front-end/src/index.scss b/front-end/src/index.scss
new file mode 100644
index 0000000..fece9ee
--- /dev/null
+++ b/front-end/src/index.scss
@@ -0,0 +1,32 @@
+@tailwind base;
+@tailwind components;
+@tailwind utilities;
+
+@import './buttons.scss';
+
+.otp-input {
+ @apply rounded-sm gap-2;
+
+ input {
+ @apply w-12 h-12 p-2 text-center text-2xl;
+ @apply dark:bg-gray-700 border dark:text-white;
+ appearance: none;
+ -webkit-appearance: none;
+ }
+}
+
+ .input {
+ @apply bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded focus:ring-blue-500 focus:border-blue-500 block w-full p-2 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500;
+
+ &.dirty{
+ @apply bg-green-50 border-green-500 text-green-900 dark:text-green-400 placeholder-green-700 dark:placeholder-green-500 focus:ring-green-500 focus:border-green-500 dark:bg-gray-700 dark:border-green-500;
+ }
+
+ &.dirty.error{
+ @apply bg-red-50 border-red-500 text-red-900 placeholder-red-700 focus:ring-red-500 dark:bg-gray-700 focus:border-red-500 dark:text-red-500 dark:placeholder-red-500 dark:border-red-500;
+ }
+}
+
+.bl-link{
+ @apply text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-500 hover:underline duration-75 ease-linear;
+} \ No newline at end of file
diff --git a/front-end/src/main.ts b/front-end/src/main.ts
new file mode 100644
index 0000000..30c3f10
--- /dev/null
+++ b/front-end/src/main.ts
@@ -0,0 +1,77 @@
+// Copyright (C) 2024 Vaughn Nugent
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+
+//Get the create app from boostrap dir
+import { configureApi } from '@vnuge/vnlib.browser'
+import { createApp } from "vue";
+import { useDark } from "@vueuse/core";
+import { createPinia } from "pinia";
+import { oauth2AppsPlugin } from './store/oauthAppsPlugin'
+
+import App from './App.vue'
+//Import your main style file
+import './index.scss'
+
+import { profilePlugin } from './store/userProfile'
+import { mfaSettingsPlugin } from './store/mfaSettingsPlugin'
+import { socialMfaPlugin } from './store/socialMfaPlugin'
+import { bookmarkPlugin } from './store/bookmarks'
+
+//Setup the vnlib api
+configureApi({
+ session: {
+ //The identifier of the login cookie, see Essentials.Accounts docs
+ loginCookieName: import.meta.env.VITE_LOGIN_COOKIE_ID,
+ browserIdSize: 32,
+ },
+ user: {
+ accountBasePath: '/account',
+ },
+ axios: {
+ //The base url to make api requests against
+ baseURL: import.meta.env.VITE_API_URL,
+ withCredentials: import.meta.env.VITE_CORS_ENABLED === 'true',
+ //See Essentials.Accounts docs
+ tokenHeader: import.meta.env.VITE_WEB_TOKEN_HEADER,
+ },
+ storage: localStorage
+})
+
+//Import vuetify stuff
+
+const store = createPinia();
+
+//Enable dark mode support
+useDark({
+ selector: 'html',
+ valueDark: 'dark',
+ valueLight: 'light',
+});
+
+//User-profile plugin
+store.use(profilePlugin('/account/profile'))
+ //Enable mfa with totp settings plugin (optional pki config)
+ .use(mfaSettingsPlugin('/account/mfa', '/account/pki'))
+ //Setup social mfa plugin
+ .use(socialMfaPlugin())
+ //Add the oauth2 apps plugin
+ .use(bookmarkPlugin('/bookmarks'))
+ //Setup oauth apps plugin (disabled for now)
+ //.use(oauth2AppsPlugin('/oauth/apps', '/oauth/scopes'))
+
+createApp(App)
+ .use(store) //Add pinia to the app
+ .mount('#app') //Mount the app to the #app element \ No newline at end of file
diff --git a/front-end/src/store/bookmarks.ts b/front-end/src/store/bookmarks.ts
new file mode 100644
index 0000000..a49937b
--- /dev/null
+++ b/front-end/src/store/bookmarks.ts
@@ -0,0 +1,249 @@
+// Copyright (C) 2024 Vaughn Nugent
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+import 'pinia'
+import { MaybeRef, shallowRef, watch, computed, Ref, ref } from 'vue';
+import { apiCall, useAxios, WebMessage } from '@vnuge/vnlib.browser';
+import { useToggle, get, set, useOffsetPagination, watchDebounced, syncRef } from '@vueuse/core';
+import { PiniaPluginContext, PiniaPlugin, storeToRefs } from 'pinia'
+import { isArray, join, map, split, sortBy } from 'lodash-es';
+import { useQuery } from './index';
+
+export interface Bookmark{
+ readonly Id: string
+ Name: string
+ Url: string
+ Tags: string[]
+ Description: string
+ Created: string
+ LastModified: string
+}
+
+export interface BatchUploadResult{
+ readonly invalid: BookmarkError[]
+}
+
+export interface BookmarkError{
+ readonly subject: Bookmark
+ readonly errors: Array<{
+ readonly message: string
+ readonly property: string
+ }>
+}
+
+export interface BookmarkApi{
+ list: (page: number, limit: number, search: BookmarkSearch) => Promise<Bookmark[]>
+ add: (bookmark: Bookmark) => Promise<void>
+ addMany: (bookmarks: Bookmark[], failOnValidationError: boolean) => Promise<BatchUploadResult | string>
+ set: (bookmark: Bookmark) => Promise<void>
+ getTags: () => Promise<string[]>
+ delete: (bookmark: Bookmark | Bookmark[]) => Promise<void>
+ count: () => Promise<number>
+}
+
+export interface BookmarkSearch{
+ query: string | undefined | null
+ tags: string[]
+}
+
+declare module 'pinia' {
+ export interface PiniaCustomProperties {
+ bookmarks:{
+ api: BookmarkApi
+ query: string
+ tags: string[]
+ allTags: string[]
+ list: Bookmark[]
+ pages: ReturnType<typeof useOffsetPagination>
+ refresh: () => void
+ }
+ }
+}
+
+const useBookmarkApi = (endpoint: MaybeRef<string>): BookmarkApi => {
+
+ const axios = useAxios(null)
+
+ const listBookmarks = async (page: number, limit: number, search: BookmarkSearch) => {
+ const query = get(search.query)
+ const tagQuery = join(get(search.tags), ' ')
+
+ const params = new URLSearchParams()
+ params.append('page', (page - 1).toString())
+ params.append('limit', limit.toString())
+ params.append('t', tagQuery)
+
+ //Add query if defined
+ if(query){
+ params.append('q', query)
+ }
+
+ const { data } = await axios.get<Bookmark[]>(`${get(endpoint)}?${params.toString()}`)
+ return data;
+ }
+
+ const addBookmark = async (bookmark: Bookmark) => {
+ const { data } = await axios.post<WebMessage>(`${get(endpoint)}`, bookmark)
+ data.getResultOrThrow();
+ }
+
+ const setBookmark = async (bookmark: Bookmark) => {
+ const { data } = await axios.patch<WebMessage<Bookmark>>(`${get(endpoint)}`, bookmark)
+ data.getResultOrThrow();
+ }
+
+ const deleteBookmark = async (bookmark: Bookmark | Bookmark[]) => {
+ if(isArray(bookmark)){
+ //Delete multiple bookmarks with comma separated ids
+ const bookmarIds = join(map(bookmark, b => b.Id), ',')
+ const { data } = await axios.delete<WebMessage<Bookmark>>(`${get(endpoint)}?ids=${bookmarIds}`)
+ data.getResultOrThrow();
+ }
+ else {
+ //Delete a single bookmark
+ const { data } = await axios.delete<WebMessage<Bookmark>>(`${get(endpoint)}?id=${bookmark.Id}`)
+ data.getResultOrThrow();
+ }
+ }
+
+ const getItemsCount = async () => {
+ const { data } = await axios.get<WebMessage<number>>(`${get(endpoint)}?count=true`)
+ return data.getResultOrThrow();
+ }
+
+ const getTags = async () => {
+ const { data } = await axios.get<string[]>(`${get(endpoint)}?getTags=true`)
+ return sortBy(data);
+ }
+
+ const addMany = async (bookmarks: Bookmark[], failOnValidationError: boolean): Promise<BatchUploadResult | string> => {
+ let params = ''
+
+ if(failOnValidationError){
+ params = '?failOnInvalid=true'
+ }
+
+ //Exec request, ignore a validation error on a 20x response
+ const { data } = await axios.put<WebMessage<BatchUploadResult>>(`${get(endpoint)}${params}`, bookmarks);
+ return data.result;
+ }
+
+ return {
+ list: listBookmarks,
+ add: addBookmark,
+ set: setBookmark,
+ delete: deleteBookmark,
+ count: getItemsCount,
+ addMany,
+ getTags
+ }
+}
+
+const urlPagiation = (p: Ref<number>, l: Ref<number>) => {
+ const page = useQuery('page')
+ const limit = useQuery('limit')
+
+ const currentPage = computed({
+ get: () => page.value ? parseInt(page.value) : 1,
+ set: (value) => set(page, value.toString())
+ })
+
+ const currentPageSize = computed({
+ get: () => limit.value ? parseInt(limit.value) : 20,
+ set: (value) => set(limit, value.toString())
+ })
+
+ //Sync current page and limit with the provided refs
+ syncRef(currentPage, p, { immediate: true })
+ syncRef(currentPageSize, l, { immediate: true })
+}
+
+const searchQuery = (search: Ref<string | null>, tags: Ref<string[]>) => {
+
+ const query = useQuery('q')
+ const tagQuery = useQuery('t')
+
+ const currentTags = computed({
+ get: () => split(tagQuery.value, ' '),
+ set: (value) => set(tagQuery, join(value, ' '))
+ })
+
+ //Sync current page and limit with the provided refs
+ syncRef(query, search, { immediate: true })
+ syncRef(currentTags, tags, { immediate: true })
+}
+
+export const bookmarkPlugin = (bookmarkEndpoint: MaybeRef<string>): PiniaPlugin => {
+
+ return ({ store }: PiniaPluginContext) => {
+
+ const { loggedIn } = storeToRefs(store)
+ const [onRefresh, refresh] = useToggle()
+
+ const totalBookmarks = shallowRef(0)
+ const bookmarks = shallowRef<Bookmark[]>()
+ const allTags = shallowRef<string[]>([])
+
+ const pages = useOffsetPagination({ page: 1, pageSize: 20 })
+ const { currentPage, currentPageSize } = pages;
+ //Sync url query params with the pagination
+ urlPagiation(currentPage, currentPageSize)
+
+ //sync search query and tags
+ const query = ref<string | null>(null)
+ const tags = ref<string[]>([])
+ searchQuery(query, tags)
+
+ //Init api
+ const bookmarkApi = useBookmarkApi(bookmarkEndpoint)
+
+ watch([loggedIn, onRefresh], ([ li ]) => {
+ if(!li){
+ //Clear the bookmarks
+ set(totalBookmarks, 0)
+ set(bookmarks, [])
+ return
+ }
+
+ //Update the total bookmarks
+ apiCall(async () => totalBookmarks.value = await bookmarkApi.count())
+ apiCall(async () => allTags.value = await bookmarkApi.getTags())
+ })
+
+ //Watch for serach query changes
+ watchDebounced([currentPage, currentPageSize, totalBookmarks, tags, query, allTags],
+ ([ page, pageSize, _, tags, query ]) => {
+ apiCall(async () => bookmarks.value = await bookmarkApi.list(page, pageSize, { tags, query }))
+ }, { debounce: 10 })
+
+ //Watch for page changes and scroll to top
+ watch([currentPage], () => window.scrollTo({ top: 0, behavior: 'smooth' }))
+
+ //reset current page when tags change or query changes
+ watch([tags, query], () => set(currentPage, 1))
+
+ return {
+ bookmarks:{
+ list: bookmarks,
+ pages,
+ refresh,
+ query,
+ tags,
+ allTags,
+ api: bookmarkApi
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/front-end/src/store/index.ts b/front-end/src/store/index.ts
new file mode 100644
index 0000000..c13edcb
--- /dev/null
+++ b/front-end/src/store/index.ts
@@ -0,0 +1,94 @@
+// Copyright (C) 2024 Vaughn Nugent
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+import { useSession, useAutoHeartbeat } from "@vnuge/vnlib.browser";
+import { toRefs, set, watchDebounced, useLocalStorage } from "@vueuse/core";
+import { noop, toSafeInteger, toString, defaults } from "lodash-es";
+import { defineStore } from "pinia";
+import { computed, shallowRef, watch } from "vue";
+
+export const useQuery = (name: string) => {
+
+ const getQuery = () => {
+ const url = new URL(window.location.href);
+ return url.searchParams.get(name) as string | null | undefined;
+ }
+
+ const setQuery = (value: string | null | undefined) => {
+ const url = new URL(window.location.href);
+
+ if(value){
+ url.searchParams.set(name, value);
+
+ }
+ else{
+ url.searchParams.delete(name);
+ }
+
+ window.history.replaceState({}, '', url.toString());
+ }
+
+ //configure reactive state
+ const value = shallowRef(getQuery());
+ watchDebounced(value, (value) => setQuery(value), { debounce: 20 });
+
+ return value;
+}
+
+export enum TabId{
+ Bookmarks,
+ Profile,
+ Settings,
+ Login
+}
+
+/**
+ * Loads the main store for the application
+ */
+export const useStore = defineStore('main', () => {
+
+ const { loggedIn, isLocalAccount } = useSession();
+
+ //MANAGED STATE
+ const siteTitle = shallowRef("");
+ const setSiteTitle = (title: string) => set(siteTitle, title);
+
+ //Get shared global state storage
+ const mainState = useLocalStorage("vn-state", { autoHeartbeat: false });
+ //Set defaults to avoid undefined errors from toRefs
+ defaults(mainState.value, { autoHeartbeat: false })
+ const { autoHeartbeat } = toRefs(mainState)
+
+ const tab = useQuery('tab');
+ const activeTab = computed<TabId>({
+ get: () => tab.value ? toSafeInteger(tab.value) : TabId.Bookmarks,
+ set: (value) => tab.value = toString(value)
+ })
+
+ //If not logged in, redirect to login tab
+ watch(loggedIn, (loggedIn) => loggedIn ? noop() : set(activeTab, TabId.Login), { immediate: true })
+
+ //Setup heartbeat for 5 minutes
+ useAutoHeartbeat(shallowRef(5 * 60 * 1000), autoHeartbeat)
+
+ return{
+ autoHeartbeat,
+ loggedIn,
+ isLocalAccount,
+ siteTitle,
+ setSiteTitle,
+ activeTab
+ }
+})
diff --git a/front-end/src/store/mfaSettingsPlugin.ts b/front-end/src/store/mfaSettingsPlugin.ts
new file mode 100644
index 0000000..77a145b
--- /dev/null
+++ b/front-end/src/store/mfaSettingsPlugin.ts
@@ -0,0 +1,80 @@
+// Copyright (C) 2024 Vaughn Nugent
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+import 'pinia'
+import { MaybeRef, shallowRef, watch } from 'vue';
+import { MfaMethod, PkiPublicKey, apiCall, useMfaConfig, usePkiConfig, usePkiAuth } from '@vnuge/vnlib.browser';
+import { useToggle, get } from '@vueuse/core';
+import { PiniaPluginContext, PiniaPlugin, storeToRefs } from 'pinia'
+import { defer, includes } from 'lodash-es';
+
+declare module 'pinia' {
+ export interface PiniaCustomProperties {
+ mfaEndabledMethods: MfaMethod[]
+ mfaConfig: ReturnType<typeof useMfaConfig>
+ pkiConfig: ReturnType<typeof usePkiConfig>
+ pkiAuth: ReturnType<typeof usePkiAuth>
+ pkiPublicKeys: PkiPublicKey[]
+ mfaRefreshMethods: () => void
+ }
+}
+
+export const mfaSettingsPlugin = (mfaEndpoint: MaybeRef<string>, pkiEndpoint?:MaybeRef<string>): PiniaPlugin => {
+
+ return ({ store }: PiniaPluginContext) => {
+
+ const { loggedIn } = storeToRefs(store)
+ const mfaConfig = useMfaConfig(mfaEndpoint)
+ const pkiConfig = usePkiConfig(pkiEndpoint || '/')
+ const pkiAuth = usePkiAuth(pkiEndpoint || '/')
+ const [onRefresh, mfaRefreshMethods] = useToggle()
+
+ const mfaEndabledMethods = shallowRef<MfaMethod[]>([])
+ const pkiPublicKeys = shallowRef<PkiPublicKey[]>([])
+
+ watch([loggedIn, onRefresh], ([ li ]) => {
+ if(!li){
+ mfaEndabledMethods.value = []
+ return
+ }
+
+ //load the mfa methods if the user is logged in
+ apiCall(async () => mfaEndabledMethods.value = await mfaConfig.getMethods())
+ })
+
+ //Watch for changes to mfa methods (refresh) and update the pki keys
+ watch([mfaEndabledMethods], ([ methods ]) => {
+ if(!includes(methods, 'pki' as MfaMethod) || !get(pkiEndpoint)){
+ pkiPublicKeys.value = []
+ return
+ }
+
+ //only load the pki keys if pki is enabled on the server
+ apiCall(async () => pkiPublicKeys.value = await pkiConfig.getAllKeys())
+ })
+
+ //Initial load when page loads
+ defer(mfaRefreshMethods)
+
+ return{
+ mfaRefreshMethods,
+ mfaEndabledMethods,
+ mfaConfig,
+ pkiConfig,
+ pkiAuth,
+ pkiPublicKeys
+ }
+ }
+} \ No newline at end of file
diff --git a/front-end/src/store/oauthAppsPlugin.ts b/front-end/src/store/oauthAppsPlugin.ts
new file mode 100644
index 0000000..d12eed2
--- /dev/null
+++ b/front-end/src/store/oauthAppsPlugin.ts
@@ -0,0 +1,174 @@
+// Copyright (C) 2024 Vaughn Nugent
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+import 'pinia'
+import { MaybeRef, computed, shallowRef, watch } from 'vue';
+import { apiCall, useAxios } from '@vnuge/vnlib.browser';
+import { get, set, useToggle } from '@vueuse/core';
+import { PiniaPlugin, PiniaPluginContext, storeToRefs } from 'pinia'
+import { map, sortBy, isArray, defer } from 'lodash-es';
+
+export interface OAuth2Application {
+ readonly Id: string,
+ readonly name: string,
+ readonly description: string,
+ readonly permissions: string[],
+ readonly client_id: string,
+ Created: Date,
+ readonly LastModified: Date,
+}
+
+export interface NewAppResponse {
+ readonly secret: string
+ readonly app: OAuth2Application
+}
+
+export interface OAuth2Api {
+ create(app: OAuth2Application): Promise<NewAppResponse>
+ updateSecret(app: OAuth2Application, password: string): Promise<string>
+ updateMeta(app: OAuth2Application): Promise<void>
+ deleteApp(app: OAuth2Application, password: string): Promise<void>
+}
+
+declare module 'pinia' {
+ export interface PiniaCustomProperties {
+ oauth2:{
+ apps: OAuth2Application[],
+ scopes: string[],
+ refresh(): void
+ } & OAuth2Api
+ }
+}
+
+export const oauth2AppsPlugin = (o2EndpointUrl: MaybeRef<string>, scopeEndpoint: MaybeRef<string>): PiniaPlugin => {
+
+ return ({ store }: PiniaPluginContext) => {
+
+ const axios = useAxios(null);
+ const { loggedIn } = storeToRefs(store)
+
+ const [onRefresh, refresh] = useToggle()
+
+ const _oauth2Apps = shallowRef<OAuth2Application[]>([])
+ const scopes = shallowRef<string[]>([])
+
+ /**
+ * Updates an Oauth2 application's metadata
+ */
+ const updateMeta = async (app: OAuth2Application): Promise<void> => {
+ //Update the app metadata
+ await axios.put(get(o2EndpointUrl), app)
+ }
+
+ /**
+ * Gets all of the user's oauth2 applications from the server
+ * @returns The user's oauth2 applications
+ */
+ const getApps = async () => {
+ // Get all apps
+ const { data } = await axios.get<OAuth2Application[]>(get(o2EndpointUrl));
+
+ if (!isArray(data)) {
+ throw new Error("Invalid response from server")
+ }
+
+ return map(data, (appData) => {
+ //Store the created time as a date object
+ appData.Created = new Date(appData?.Created ?? 0)
+ //create a new state manager for the user's profile
+ return appData;
+ })
+ }
+
+ /**
+ * Creates a new application from the given data
+ * @param param0 The application server buffer
+ * @returns The newly created application
+ */
+ const create = async ({ name, description, permissions }: OAuth2Application): Promise<NewAppResponse> => {
+
+ // make the post request, response is the new app data with a secret
+ const { data } = await axios.post<OAuth2Application & { raw_secret: string }>(`${get(o2EndpointUrl)}?action=create`, { name, description, permissions })
+
+ // Store secret
+ const secret = data.raw_secret
+
+ // remove secre tfrom the response
+ delete (data as any).raw_secret
+
+ return { secret, app: data }
+ }
+
+ /**
+ * Requets a new secret for an application from the server
+ * @param app The app to request a new secret for
+ * @param password The user's password
+ * @returns The new secret
+ */
+ const updateSecret = async (app: OAuth2Application, password: string): Promise<string> => {
+ const { data } = await axios.post(`${o2EndpointUrl}?action=secret`, { Id: app.Id, password })
+ return data.raw_secret
+ }
+
+ /**
+ * Deletes an application from the server
+ * @param app The application to delete
+ * @param password The user's password
+ * @returns The response from the server
+ */
+ const deleteApp = async (app: OAuth2Application, password: string): Promise<void> => {
+ await axios.post(`${o2EndpointUrl}?action=delete`, { password, Id: app.Id });
+ }
+
+ const apps = computed(() => sortBy(_oauth2Apps.value, a => a.Created))
+
+ watch([loggedIn, onRefresh], async ([li]) => {
+ if (!li) {
+ set(_oauth2Apps, [])
+ return;
+ }
+
+ //Load the user's oauth2 apps after scopes load. to make sure the plugin is enabled
+ apiCall(async () => {
+ try {
+ //Load the oauth2 scopes
+ const { data } = await axios.get<string[]>(get(scopeEndpoint))
+ set(scopes, data)
+
+ _oauth2Apps.value = await getApps();
+ }
+ catch (e: any) {
+ if (e.response?.status === 404) {
+ console.warn("OAuth2 plugin is not configured");
+ }
+ }
+ })
+ })
+
+ defer(refresh)
+
+ return {
+ oauth2:{
+ scopes,
+ apps,
+ deleteApp,
+ updateSecret,
+ updateMeta,
+ create,
+ refresh
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/front-end/src/store/socialMfaPlugin.ts b/front-end/src/store/socialMfaPlugin.ts
new file mode 100644
index 0000000..d8d7bb1
--- /dev/null
+++ b/front-end/src/store/socialMfaPlugin.ts
@@ -0,0 +1,85 @@
+// Copyright (C) 2024 Vaughn Nugent
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+import 'pinia'
+import { MaybeRef } from 'vue';
+import { useSocialOauthLogin, useUser, SocialOAuthPortal, fromPortals, useAxios } from '@vnuge/vnlib.browser'
+import { get } from '@vueuse/core';
+import { PiniaPluginContext, PiniaPlugin, storeToRefs } from 'pinia'
+import { defer } from 'lodash-es';
+
+type SocialMfaPlugin = ReturnType<typeof useSocialOauthLogin>
+
+declare module 'pinia' {
+ export interface PiniaCustomProperties {
+ socialOauth(): Promise<SocialMfaPlugin>
+ }
+}
+
+export const socialMfaPlugin = (portalEndpoint?: MaybeRef<string>): PiniaPlugin => {
+
+ return ({ store }: PiniaPluginContext) => {
+
+ const { } = storeToRefs(store)
+ const { logout } = useUser()
+
+ /**
+ * Override the logout function to default to a social logout,
+ * if the social logout fails, then we will logout the user
+ */
+ const setLogoutMethod = (socialOauth: SocialMfaPlugin) => {
+ const logoutFunc = socialOauth.logout;
+
+ (socialOauth as any).logout = async () => {
+ if (await logoutFunc() === false) {
+ await logout()
+ }
+ }
+ }
+
+ const _loadPromise = new Promise<SocialMfaPlugin>((resolve, reject) => {
+
+ if(get(portalEndpoint) == null) {
+ const socialOauth = useSocialOauthLogin([])
+ setLogoutMethod(socialOauth)
+ return resolve(socialOauth)
+ }
+
+ defer(async () => {
+ try {
+ //Get axios instance
+ const axios = useAxios(null)
+
+ //Get all enabled portals
+ const { data } = await axios.get<SocialOAuthPortal[]>(get(portalEndpoint)!);
+ //Setup social providers from server portals
+ const socialOauth = useSocialOauthLogin(fromPortals(data));
+ setLogoutMethod(socialOauth);
+
+ resolve(socialOauth)
+
+ } catch (error) {
+ reject(error)
+ }
+ })
+ })
+
+ const socialOauth = () => _loadPromise
+
+ return {
+ socialOauth,
+ }
+ }
+} \ No newline at end of file
diff --git a/front-end/src/store/userProfile.ts b/front-end/src/store/userProfile.ts
new file mode 100644
index 0000000..ed796d9
--- /dev/null
+++ b/front-end/src/store/userProfile.ts
@@ -0,0 +1,97 @@
+// Copyright (C) 2024 Vaughn Nugent
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+import 'pinia'
+import { MaybeRef, watch } from 'vue';
+import { ServerDataBuffer, ServerObjectBuffer, UserProfile, WebMessage, apiCall, useAxios, useDataBuffer, useUser } from '@vnuge/vnlib.browser';
+import { get, useToggle } from '@vueuse/core';
+import { PiniaPlugin, PiniaPluginContext, storeToRefs } from 'pinia'
+import { defer } from 'lodash-es';
+
+export interface OAuth2Application {
+ readonly Id: string,
+ readonly name: string,
+ readonly description: string,
+ readonly permissions: string[],
+ readonly client_id: string,
+ readonly Created: Date,
+ readonly LastModified: Date,
+}
+
+export interface NewAppResponse {
+ readonly secret: string
+ readonly app: ServerDataBuffer<OAuth2Application, WebMessage<string>>
+}
+
+interface ExUserProfile extends UserProfile {
+ created: string | Date
+}
+
+declare module 'pinia' {
+ export interface PiniaCustomProperties {
+ userProfile: ServerDataBuffer<ExUserProfile, WebMessage<string>>
+ userName: string | undefined
+ refreshProfile(): void;
+ }
+}
+
+export const profilePlugin = (accountsUrl:MaybeRef<string>) :PiniaPlugin => {
+
+ return ({ store }: PiniaPluginContext) => {
+
+ const { loggedIn } = storeToRefs(store)
+ const { getProfile, userName } = useUser()
+ const axios = useAxios(null)
+
+ const [onRefresh, refreshProfile] = useToggle()
+
+ const updateUserProfile = async (profile: ServerObjectBuffer<ExUserProfile>) => {
+ // Apply the buffer to the profile
+ const { data } = await axios.post<WebMessage<string>>(get(accountsUrl), profile.buffer)
+
+ //Get the new profile from the server
+ const newProfile = await getProfile() as ExUserProfile
+
+ //Apply the new profile to the buffer
+ profile.apply(newProfile)
+
+ return data;
+ }
+
+ const userProfile = useDataBuffer({} as any, updateUserProfile)
+
+ const loadProfile = async () => {
+ //Get the user profile
+ const profile = await getProfile() as ExUserProfile
+ //Apply the profile to the buffer
+ userProfile.apply(profile)
+ }
+
+ watch([loggedIn, onRefresh], ([li]) => {
+ //If the user is logged in, load the profile buffer
+ if (li) {
+ apiCall(loadProfile)
+ }
+ })
+
+ defer(refreshProfile);
+
+ return {
+ userProfile,
+ refreshProfile,
+ userName
+ }
+ }
+} \ No newline at end of file
diff --git a/front-end/src/vite-env.d.ts b/front-end/src/vite-env.d.ts
new file mode 100644
index 0000000..151aa68
--- /dev/null
+++ b/front-end/src/vite-env.d.ts
@@ -0,0 +1 @@
+/// <reference types="vite/client" /> \ No newline at end of file