Skip to content

Commit

Permalink
fix(OTP Generator): add query and storage for secret (so can be remem…
Browse files Browse the repository at this point in the history
…bered)

Fix #1208
  • Loading branch information
sharevb committed Aug 4, 2024
1 parent b430bae commit fdb2bff
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
33 changes: 32 additions & 1 deletion src/composable/queryParams.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { useRouteQuery } from '@vueuse/router';
import { computed } from 'vue';
import { useStorage } from '@vueuse/core';

export { useQueryParam };
export { useQueryParam, useQueryParamOrStorage };

const transformers = {
number: {
Expand All @@ -16,6 +17,12 @@ const transformers = {
fromQuery: (value: string) => value.toLowerCase() === 'true',
toQuery: (value: boolean) => (value ? 'true' : 'false'),
},
object: {
fromQuery: (value: string) => {
return JSON.parse(value);
},
toQuery: (value: object) => JSON.stringify(value),
},
};

function useQueryParam<T>({ name, defaultValue }: { name: string; defaultValue: T }) {
Expand All @@ -33,3 +40,27 @@ function useQueryParam<T>({ name, defaultValue }: { name: string; defaultValue:
},
});
}

function useQueryParamOrStorage<T>({ name, storageName, defaultValue }: { name: string; storageName: string; defaultValue: T }) {
const type = typeof defaultValue;
const transformer = transformers[type as keyof typeof transformers] ?? transformers.string;

const storageRef = useStorage(storageName, defaultValue);
const proxyDefaultValue = transformer.toQuery(defaultValue as never);
const proxy = useRouteQuery(name, proxyDefaultValue);

const r = ref(defaultValue);

watch(r,
(value) => {
proxy.value = transformer.toQuery(value as never);
storageRef.value = value as never;
},
{ deep: true });

r.value = (proxy.value && proxy.value !== proxyDefaultValue
? transformer.fromQuery(proxy.value) as unknown as T
: storageRef.value as T) as never;

return r;
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,18 @@ import TokenDisplay from './token-display.vue';
import { useStyleStore } from '@/stores/style.store';
import InputCopyable from '@/components/InputCopyable.vue';
import { computedRefreshable } from '@/composable/computedRefreshable';
import { useQueryParamOrStorage } from '@/composable/queryParams';
const now = useTimestamp();
const interval = computed(() => (now.value / 1000) % 30);
const theme = useThemeVars();
const styleStore = useStyleStore();
const secret = ref(generateSecret());
const secret = useQueryParamOrStorage({
name: 'secret',
storageName: 'otp-gen:secret',
defaultValue: generateSecret(),
});
function refreshSecret() {
secret.value = generateSecret();
Expand Down

0 comments on commit fdb2bff

Please sign in to comment.