Add useSettings composable for managing and persisting settings
This commit is contained in:
63
src/composables/useSettings.ts
Normal file
63
src/composables/useSettings.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { ref, watch } from 'vue';
|
||||
import { useStore } from './useStore.ts';
|
||||
import { useCrypto } from './useCrypto.ts';
|
||||
|
||||
export type Settings = {
|
||||
username: string,
|
||||
password: string,
|
||||
}
|
||||
|
||||
const settingsDefault: Settings = {
|
||||
username: '',
|
||||
password: '',
|
||||
};
|
||||
|
||||
export function useSettings() {
|
||||
const { setValue, getValue } = useStore();
|
||||
const { encrypt, decrypt } = useCrypto();
|
||||
const settings = ref<Settings>({ ...settingsDefault });
|
||||
|
||||
const loadSettings = async () => {
|
||||
const readSettings = await getValue<Settings>('settings');
|
||||
if (!readSettings) {
|
||||
settings.value = { ...settingsDefault };
|
||||
return;
|
||||
}
|
||||
|
||||
let password = readSettings.password ?? '';
|
||||
if (password) {
|
||||
try {
|
||||
password = decrypt(password);
|
||||
} catch (error) {
|
||||
console.warn('Failed to decrypt stored password:', error);
|
||||
}
|
||||
}
|
||||
|
||||
settings.value = {
|
||||
username: readSettings.username ?? '',
|
||||
password,
|
||||
};
|
||||
};
|
||||
|
||||
const saveSettings = async () => {
|
||||
const encryptedPassword = settings.value.password
|
||||
? encrypt(settings.value.password)
|
||||
: '';
|
||||
|
||||
await setValue<Settings>('settings', {
|
||||
username: settings.value.username,
|
||||
password: encryptedPassword,
|
||||
});
|
||||
};
|
||||
|
||||
watch(settings, () => {
|
||||
void saveSettings();
|
||||
}, { deep: true });
|
||||
|
||||
void loadSettings();
|
||||
|
||||
return {
|
||||
settings,
|
||||
loadSettings,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user