migrate unlock page to composition API and typescript

This commit is contained in:
MaysWind
2025-01-14 23:36:31 +08:00
parent cd2e6c1aae
commit 29c09cb10a
7 changed files with 387 additions and 396 deletions
+2 -2
View File
@@ -35,7 +35,7 @@ interface WebAuthnRegisterResponse {
} }
interface WebAuthnVerifyResponse { interface WebAuthnVerifyResponse {
readonly id: string | null; readonly id: string;
readonly userName: string; readonly userName: string;
readonly userSecret: string; readonly userSecret: string;
readonly clientData: ClientData; readonly clientData: ClientData;
@@ -198,7 +198,7 @@ export function verifyWebAuthnCredential(userInfo: UserBasicInfo, credentialId:
clientData && clientData.type === 'webauthn.get' && challengeFromClientData === challenge && clientData && clientData.type === 'webauthn.get' && challengeFromClientData === challenge &&
userIdParts && userIdParts.length === 2 && userIdParts[0] === userInfo.username) { userIdParts && userIdParts.length === 2 && userIdParts[0] === userInfo.username) {
const ret: WebAuthnVerifyResponse = { const ret: WebAuthnVerifyResponse = {
id: base64encode(rawCredential.rawId), id: base64encode(rawCredential.rawId) as string,
userName: userIdParts[0], userName: userIdParts[0],
userSecret: userIdParts[1], userSecret: userIdParts[1],
clientData: clientData, clientData: clientData,
+16 -46
View File
@@ -1,6 +1,6 @@
import moment from 'moment-timezone'; import moment from 'moment-timezone';
import { DEFAULT_LANGUAGE, allLanguages } from '@/locales/index.ts'; import { DEFAULT_LANGUAGE, ALL_LANGUAGES } from '@/locales/index.ts';
import { Month, WeekDay, MeridiemIndicator, LongDateFormat, ShortDateFormat, LongTimeFormat, ShortTimeFormat, DateRange, LANGUAGE_DEFAULT_DATE_TIME_FORMAT_VALUE } from '@/core/datetime.ts'; import { Month, WeekDay, MeridiemIndicator, LongDateFormat, ShortDateFormat, LongTimeFormat, ShortTimeFormat, DateRange, LANGUAGE_DEFAULT_DATE_TIME_FORMAT_VALUE } from '@/core/datetime.ts';
import { TimezoneTypeForStatistics } from '@/core/timezone.ts'; import { TimezoneTypeForStatistics } from '@/core/timezone.ts';
@@ -70,12 +70,12 @@ function getLanguageDisplayName(translateFn, languageName) {
function getAllLanguageInfoArray(translateFn, includeSystemDefault) { function getAllLanguageInfoArray(translateFn, includeSystemDefault) {
const ret = []; const ret = [];
for (const languageTag in allLanguages) { for (const languageTag in ALL_LANGUAGES) {
if (!Object.prototype.hasOwnProperty.call(allLanguages, languageTag)) { if (!Object.prototype.hasOwnProperty.call(ALL_LANGUAGES, languageTag)) {
continue; continue;
} }
const languageInfo = allLanguages[languageTag]; const languageInfo = ALL_LANGUAGES[languageTag];
let displayName = languageInfo.displayName; let displayName = languageInfo.displayName;
let languageNameInCurrentLanguage = getLanguageDisplayName(translateFn, languageInfo.name); let languageNameInCurrentLanguage = getLanguageDisplayName(translateFn, languageInfo.name);
@@ -104,7 +104,7 @@ function getAllLanguageInfoArray(translateFn, includeSystemDefault) {
} }
function getLanguageInfo(locale) { function getLanguageInfo(locale) {
return allLanguages[locale]; return ALL_LANGUAGES[locale];
} }
function getDefaultLanguage() { function getDefaultLanguage() {
@@ -118,7 +118,7 @@ function getDefaultLanguage() {
return DEFAULT_LANGUAGE; return DEFAULT_LANGUAGE;
} }
if (!allLanguages[browserLocale]) { if (!ALL_LANGUAGES[browserLocale]) {
const locale = getLocaleFromLanguageAlias(browserLocale); const locale = getLocaleFromLanguageAlias(browserLocale);
if (locale) { if (locale) {
@@ -126,11 +126,11 @@ function getDefaultLanguage() {
} }
} }
if (!allLanguages[browserLocale] && browserLocale.split('-').length > 1) { // maybe language-script-region if (!ALL_LANGUAGES[browserLocale] && browserLocale.split('-').length > 1) { // maybe language-script-region
const localeParts = browserLocale.split('-'); const localeParts = browserLocale.split('-');
browserLocale = localeParts[0] + '-' + localeParts[1]; browserLocale = localeParts[0] + '-' + localeParts[1];
if (!allLanguages[browserLocale]) { if (!ALL_LANGUAGES[browserLocale]) {
const locale = getLocaleFromLanguageAlias(browserLocale); const locale = getLocaleFromLanguageAlias(browserLocale);
if (locale) { if (locale) {
@@ -138,7 +138,7 @@ function getDefaultLanguage() {
} }
} }
if (!allLanguages[browserLocale]) { if (!ALL_LANGUAGES[browserLocale]) {
browserLocale = localeParts[0]; browserLocale = localeParts[0];
const locale = getLocaleFromLanguageAlias(browserLocale); const locale = getLocaleFromLanguageAlias(browserLocale);
@@ -148,7 +148,7 @@ function getDefaultLanguage() {
} }
} }
if (!allLanguages[browserLocale]) { if (!ALL_LANGUAGES[browserLocale]) {
return DEFAULT_LANGUAGE; return DEFAULT_LANGUAGE;
} }
@@ -156,8 +156,8 @@ function getDefaultLanguage() {
} }
function getLocaleFromLanguageAlias(alias) { function getLocaleFromLanguageAlias(alias) {
for (let locale in allLanguages) { for (let locale in ALL_LANGUAGES) {
if (!Object.prototype.hasOwnProperty.call(allLanguages, locale)) { if (!Object.prototype.hasOwnProperty.call(ALL_LANGUAGES, locale)) {
continue; continue;
} }
@@ -165,7 +165,7 @@ function getLocaleFromLanguageAlias(alias) {
return locale; return locale;
} }
const lang = allLanguages[locale]; const lang = ALL_LANGUAGES[locale];
const aliases = lang.aliases; const aliases = lang.aliases;
if (!aliases || aliases.length < 1) { if (!aliases || aliases.length < 1) {
@@ -1122,11 +1122,11 @@ function getAllSupportedImportFileTypes(i18nGlobal, translateFn) {
if (fileType.document.supportMultiLanguages === true) { if (fileType.document.supportMultiLanguages === true) {
document.language = getCurrentLanguageTag(i18nGlobal); document.language = getCurrentLanguageTag(i18nGlobal);
document.anchor = translateFn(`document.anchor.export_and_import.${fileType.document.anchor}`); document.anchor = translateFn(`document.anchor.export_and_import.${fileType.document.anchor}`);
} else if (isString(fileType.document.supportMultiLanguages) && allLanguages[fileType.document.supportMultiLanguages]) { } else if (isString(fileType.document.supportMultiLanguages) && ALL_LANGUAGES[fileType.document.supportMultiLanguages]) {
document.language = fileType.document.supportMultiLanguages; document.language = fileType.document.supportMultiLanguages;
if (document.language !== getCurrentLanguageTag(i18nGlobal)) { if (document.language !== getCurrentLanguageTag(i18nGlobal)) {
document.displayLanguageName = getLanguageDisplayName(translateFn, allLanguages[fileType.document.supportMultiLanguages].name); document.displayLanguageName = getLanguageDisplayName(translateFn, ALL_LANGUAGES[fileType.document.supportMultiLanguages].name);
} }
document.anchor = fileType.document.anchor; document.anchor = fileType.document.anchor;
@@ -1373,34 +1373,6 @@ function setLanguage(i18nGlobal, locale, force) {
}; };
} }
function setTimeZone(timezone) {
if (timezone) {
moment.tz.setDefault(timezone);
} else {
moment.tz.setDefault();
}
}
function initLocale(i18nGlobal, lastUserLanguage, timezone) {
let localeDefaultSettings = null;
if (lastUserLanguage && getLanguageInfo(lastUserLanguage)) {
logger.info(`Last user language is ${lastUserLanguage}`);
localeDefaultSettings = setLanguage(i18nGlobal, lastUserLanguage, true);
} else {
localeDefaultSettings = setLanguage(i18nGlobal, null, true);
}
if (timezone) {
logger.info(`Current timezone is ${timezone}`);
setTimeZone(timezone);
} else {
logger.info(`No timezone is set, use browser default ${getTimezoneOffset()} (maybe ${moment.tz.guess(true)})`);
}
return localeDefaultSettings;
}
export function translateError(message, translateFn) { export function translateError(message, translateFn) {
let parameters = {}; let parameters = {};
@@ -1487,8 +1459,6 @@ export function i18nFunctions(i18nGlobal) {
getCategorizedAccountsWithDisplayBalance: (allVisibleAccounts, showAccountBalance, defaultCurrency, settingsStore, userStore, exchangeRatesStore) => getCategorizedAccountsWithDisplayBalance(allVisibleAccounts, showAccountBalance, defaultCurrency, userStore, settingsStore, exchangeRatesStore, i18nGlobal.t), getCategorizedAccountsWithDisplayBalance: (allVisibleAccounts, showAccountBalance, defaultCurrency, settingsStore, userStore, exchangeRatesStore) => getCategorizedAccountsWithDisplayBalance(allVisibleAccounts, showAccountBalance, defaultCurrency, userStore, settingsStore, exchangeRatesStore, i18nGlobal.t),
getServerTipContent: (tipConfig) => getServerTipContent(tipConfig, i18nGlobal), getServerTipContent: (tipConfig) => getServerTipContent(tipConfig, i18nGlobal),
joinMultiText: (textArray) => joinMultiText(textArray, i18nGlobal.t), joinMultiText: (textArray) => joinMultiText(textArray, i18nGlobal.t),
setLanguage: (locale, force) => setLanguage(i18nGlobal, locale, force), setLanguage: (locale, force) => setLanguage(i18nGlobal, locale, force)
setTimeZone: (timezone) => setTimeZone(timezone),
initLocale: (lastUserLanguage, timezone) => initLocale(i18nGlobal, lastUserLanguage, timezone)
}; };
} }
+56 -15
View File
@@ -1,9 +1,9 @@
import { useI18n as useVueI18n } from 'vue-i18n'; import { useI18n as useVueI18n } from 'vue-i18n';
import moment from 'moment-timezone'; import moment from 'moment-timezone';
import type {TypeAndName, TypeAndDisplayName, LocalizedSwitchOption } from '@/core/base.ts'; import type { TypeAndName, TypeAndDisplayName, LocalizedSwitchOption } from '@/core/base.ts';
import { type LanguageInfo, allLanguages, DEFAULT_LANGUAGE } from '@/locales/index.ts'; import { type LanguageInfo, type LanguageOption, ALL_LANGUAGES, DEFAULT_LANGUAGE } from '@/locales/index.ts';
import { import {
type DateFormat, type DateFormat,
@@ -136,12 +136,12 @@ export function getI18nOptions(): object {
messages: (function () { messages: (function () {
const messages: Record<string, object> = {}; const messages: Record<string, object> = {};
for (const languageKey in allLanguages) { for (const languageKey in ALL_LANGUAGES) {
if (!Object.prototype.hasOwnProperty.call(allLanguages, languageKey)) { if (!Object.prototype.hasOwnProperty.call(ALL_LANGUAGES, languageKey)) {
continue; continue;
} }
const languageInfo = allLanguages[languageKey]; const languageInfo = ALL_LANGUAGES[languageKey];
messages[languageKey] = languageInfo.content; messages[languageKey] = languageInfo.content;
} }
@@ -158,7 +158,11 @@ export function useI18n() {
// private functions // private functions
function getLanguageInfo(languageKey: string): LanguageInfo | undefined { function getLanguageInfo(languageKey: string): LanguageInfo | undefined {
return allLanguages[languageKey]; return ALL_LANGUAGES[languageKey];
}
function getLanguageDisplayName(languageName: string): string {
return t(`language.${languageName}`);
} }
function getDefaultLanguage(): string { function getDefaultLanguage(): string {
@@ -172,7 +176,7 @@ export function useI18n() {
return DEFAULT_LANGUAGE; return DEFAULT_LANGUAGE;
} }
if (!allLanguages[browserLanguage]) { if (!ALL_LANGUAGES[browserLanguage]) {
const languageKey = getLanguageKeyFromLanguageAlias(browserLanguage); const languageKey = getLanguageKeyFromLanguageAlias(browserLanguage);
if (languageKey) { if (languageKey) {
@@ -180,11 +184,11 @@ export function useI18n() {
} }
} }
if (!allLanguages[browserLanguage] && browserLanguage.split('-').length > 1) { // maybe language-script-region if (!ALL_LANGUAGES[browserLanguage] && browserLanguage.split('-').length > 1) { // maybe language-script-region
const languageTagParts = browserLanguage.split('-'); const languageTagParts = browserLanguage.split('-');
browserLanguage = languageTagParts[0] + '-' + languageTagParts[1]; browserLanguage = languageTagParts[0] + '-' + languageTagParts[1];
if (!allLanguages[browserLanguage]) { if (!ALL_LANGUAGES[browserLanguage]) {
const languageKey = getLanguageKeyFromLanguageAlias(browserLanguage); const languageKey = getLanguageKeyFromLanguageAlias(browserLanguage);
if (languageKey) { if (languageKey) {
@@ -192,7 +196,7 @@ export function useI18n() {
} }
} }
if (!allLanguages[browserLanguage]) { if (!ALL_LANGUAGES[browserLanguage]) {
browserLanguage = languageTagParts[0]; browserLanguage = languageTagParts[0];
const languageKey = getLanguageKeyFromLanguageAlias(browserLanguage); const languageKey = getLanguageKeyFromLanguageAlias(browserLanguage);
@@ -202,7 +206,7 @@ export function useI18n() {
} }
} }
if (!allLanguages[browserLanguage]) { if (!ALL_LANGUAGES[browserLanguage]) {
return DEFAULT_LANGUAGE; return DEFAULT_LANGUAGE;
} }
@@ -210,8 +214,8 @@ export function useI18n() {
} }
function getLanguageKeyFromLanguageAlias(alias: string): string | null { function getLanguageKeyFromLanguageAlias(alias: string): string | null {
for (const languageKey in allLanguages) { for (const languageKey in ALL_LANGUAGES) {
if (!Object.prototype.hasOwnProperty.call(allLanguages, languageKey)) { if (!Object.prototype.hasOwnProperty.call(ALL_LANGUAGES, languageKey)) {
continue; continue;
} }
@@ -219,7 +223,7 @@ export function useI18n() {
return languageKey; return languageKey;
} }
const langInfo = allLanguages[languageKey]; const langInfo = ALL_LANGUAGES[languageKey];
const aliases = langInfo.aliases; const aliases = langInfo.aliases;
if (!aliases || aliases.length < 1) { if (!aliases || aliases.length < 1) {
@@ -545,6 +549,42 @@ export function useI18n() {
return t('default.firstDayOfWeek'); return t('default.firstDayOfWeek');
} }
function getAllLanguageOptions(includeSystemDefault: boolean): LanguageOption[] {
const ret: LanguageOption[] = [];
for (const languageTag in ALL_LANGUAGES) {
if (!Object.prototype.hasOwnProperty.call(ALL_LANGUAGES, languageTag)) {
continue;
}
const languageInfo = ALL_LANGUAGES[languageTag];
let displayName = languageInfo.displayName;
const languageNameInCurrentLanguage = getLanguageDisplayName(languageInfo.name);
if (languageNameInCurrentLanguage && languageNameInCurrentLanguage !== displayName) {
displayName = `${languageNameInCurrentLanguage} (${displayName})`;
}
ret.push({
languageTag: languageTag,
displayName: displayName
});
}
ret.sort(function (lang1, lang2) {
return lang1.languageTag.localeCompare(lang2.languageTag);
});
if (includeSystemDefault) {
ret.splice(0, 0, {
languageTag: '',
displayName: t('System Default')
});
}
return ret;
}
function getAllEnableDisableOptions(): LocalizedSwitchOption[] { function getAllEnableDisableOptions(): LocalizedSwitchOption[] {
return [{ return [{
value: true, value: true,
@@ -1167,7 +1207,7 @@ export function useI18n() {
} }
} }
function initLocale(lastUserLanguage: string, timezone: string): LocaleDefaultSettings | null { function initLocale(lastUserLanguage?: string, timezone?: string): LocaleDefaultSettings | null {
let localeDefaultSettings: LocaleDefaultSettings | null = null; let localeDefaultSettings: LocaleDefaultSettings | null = null;
if (lastUserLanguage && getLanguageInfo(lastUserLanguage)) { if (lastUserLanguage && getLanguageInfo(lastUserLanguage)) {
@@ -1201,6 +1241,7 @@ export function useI18n() {
getDefaultCurrency, getDefaultCurrency,
getDefaultFirstDayOfWeek, getDefaultFirstDayOfWeek,
// get all localized info of specified type // get all localized info of specified type
getAllLanguageOptions,
getAllEnableDisableOptions, getAllEnableDisableOptions,
getAllMeridiemIndicators, getAllMeridiemIndicators,
getAllLongMonthNames, getAllLongMonthNames,
+6 -1
View File
@@ -10,10 +10,15 @@ export interface LanguageInfo {
readonly content: object; readonly content: object;
} }
export interface LanguageOption {
readonly languageTag: string;
readonly displayName: string;
}
export const DEFAULT_LANGUAGE: string = 'en'; export const DEFAULT_LANGUAGE: string = 'en';
// To add new languages, please refer to https://ezbookkeeping.mayswind.net/translating // To add new languages, please refer to https://ezbookkeeping.mayswind.net/translating
export const allLanguages: Record<string, LanguageInfo> = { export const ALL_LANGUAGES: Record<string, LanguageInfo> = {
'en': { 'en': {
name: 'English', name: 'English',
displayName: 'English', displayName: 'English',
+91
View File
@@ -0,0 +1,91 @@
import { ref, computed } from 'vue';
import { useI18n } from '@/locales/helpers.ts';
// @ts-expect-error the above file is migrating to ts
import { useRootStore } from '@/stores/index.js';
import { useSettingsStore } from '@/stores/setting.ts';
import { useUserStore } from '@/stores/user.ts';
import { useTokensStore } from '@/stores/token.ts';
// @ts-expect-error the above file is migrating to ts
import { useTransactionsStore } from '@/stores/transaction.js';
import { useExchangeRatesStore } from '@/stores/exchangeRates.ts';
import { isWebAuthnSupported } from '@/lib/webauthn.ts';
import { hasWebAuthnConfig } from '@/lib/userstate.ts';
import { getVersion } from '@/lib/version.ts';
import { setExpenseAndIncomeAmountColor } from '@/lib/ui/common.ts';
export function useUnlockPageBase() {
const { setLanguage, initLocale } = useI18n();
const rootStore = useRootStore();
const settingsStore = useSettingsStore();
const userStore = useUserStore();
const tokensStore = useTokensStore();
const transactionsStore = useTransactionsStore();
const exchangeRatesStore = useExchangeRatesStore();
const version: string = `v${getVersion()}`;
const pinCode = ref<string>('');
const isWebAuthnAvailable = computed<boolean>(() => {
return settingsStore.appSettings.applicationLockWebAuthn
&& hasWebAuthnConfig()
&& isWebAuthnSupported();
});
function isPinCodeValid(pinCode: string): boolean {
return !!pinCode && pinCode.length === 6;
}
function changeLanguage(locale: string): void {
const localeDefaultSettings = setLanguage(locale);
settingsStore.updateLocalizedDefaultSettings(localeDefaultSettings);
}
function doAfterUnlocked(): void {
transactionsStore.initTransactionDraft();
tokensStore.refreshTokenAndRevokeOldToken().then(response => {
if (response.user) {
const localeDefaultSettings = setLanguage(response.user.language);
settingsStore.updateLocalizedDefaultSettings(localeDefaultSettings);
setExpenseAndIncomeAmountColor(response.user.expenseAmountColor, response.user.incomeAmountColor);
}
if (response.notificationContent) {
rootStore.setNotificationContent(response.notificationContent);
}
});
if (settingsStore.appSettings.autoUpdateExchangeRatesData) {
exchangeRatesStore.getLatestExchangeRates({ silent: true, force: false });
}
}
function doRelogin(): void {
rootStore.forceLogout();
settingsStore.clearAppSettings();
const localeDefaultSettings = initLocale(userStore.currentUserLanguage, settingsStore.appSettings.timeZone);
settingsStore.updateLocalizedDefaultSettings(localeDefaultSettings);
setExpenseAndIncomeAmountColor(userStore.currentUserExpenseAmountColor, userStore.currentUserIncomeAmountColor);
}
return {
// constants
version,
// states
pinCode,
// computed states
isWebAuthnAvailable,
// methods
isPinCodeValid,
changeLanguage,
doAfterUnlocked,
doRelogin
};
}
+109 -166
View File
@@ -2,8 +2,8 @@
<div class="layout-wrapper"> <div class="layout-wrapper">
<router-link to="/"> <router-link to="/">
<div class="auth-logo d-flex align-start gap-x-3"> <div class="auth-logo d-flex align-start gap-x-3">
<img alt="logo" class="login-page-logo" :src="ezBookkeepingLogoPath" /> <img alt="logo" class="login-page-logo" :src="APPLICATION_LOGO_PATH" />
<h1 class="font-weight-medium leading-normal text-2xl">{{ $t('global.app.title') }}</h1> <h1 class="font-weight-medium leading-normal text-2xl">{{ tt('global.app.title') }}</h1>
</div> </div>
</router-link> </router-link>
<v-row no-gutters class="auth-wrapper"> <v-row no-gutters class="auth-wrapper">
@@ -22,9 +22,9 @@
<div class="d-flex align-center justify-center h-100"> <div class="d-flex align-center justify-center h-100">
<v-card variant="flat" class="w-100 mt-0 px-4 pt-12" max-width="500"> <v-card variant="flat" class="w-100 mt-0 px-4 pt-12" max-width="500">
<v-card-text> <v-card-text>
<h4 class="text-h4 mb-2">{{ $t('Unlock Application') }}</h4> <h4 class="text-h4 mb-2">{{ tt('Unlock Application') }}</h4>
<p class="mb-0" v-if="isWebAuthnAvailable">{{ $t('Please enter your PIN code or use WebAuthn to unlock application') }}</p> <p class="mb-0" v-if="isWebAuthnAvailable">{{ tt('Please enter your PIN code or use WebAuthn to unlock application') }}</p>
<p class="mb-0" v-else-if="!isWebAuthnAvailable">{{ $t('Please enter your PIN code to unlock application') }}</p> <p class="mb-0" v-else-if="!isWebAuthnAvailable">{{ tt('Please enter your PIN code to unlock application') }}</p>
</v-card-text> </v-card-text>
<v-card-text class="pb-0 mb-6"> <v-card-text class="pb-0 mb-6">
@@ -39,22 +39,22 @@
<v-col cols="12"> <v-col cols="12">
<v-btn block :disabled="!isPinCodeValid(pinCode) || verifyingByWebAuthn" <v-btn block :disabled="!isPinCodeValid(pinCode) || verifyingByWebAuthn"
@click="unlockByPin(pinCode)"> @click="unlockByPin(pinCode)">
{{ $t('Unlock with PIN Code') }} {{ tt('Unlock with PIN Code') }}
</v-btn> </v-btn>
</v-col> </v-col>
<v-col cols="12" v-if="isWebAuthnAvailable"> <v-col cols="12" v-if="isWebAuthnAvailable">
<v-btn block variant="tonal" :disabled="verifyingByWebAuthn" <v-btn block variant="tonal" :disabled="verifyingByWebAuthn"
@click="unlockByWebAuthn"> @click="unlockByWebAuthn">
{{ $t('Unlock with WebAuthn') }} {{ tt('Unlock with WebAuthn') }}
<v-progress-circular indeterminate size="22" class="ml-2" v-if="verifyingByWebAuthn"></v-progress-circular> <v-progress-circular indeterminate size="22" class="ml-2" v-if="verifyingByWebAuthn"></v-progress-circular>
</v-btn> </v-btn>
</v-col> </v-col>
<v-col cols="12" class="text-center"> <v-col cols="12" class="text-center">
<span class="me-1">{{ $t('Can\'t Unlock?') }}</span> <span class="me-1">{{ tt('Can\'t Unlock?') }}</span>
<a class="text-primary" href="javascript:void(0);" @click="relogin"> <a class="text-primary" href="javascript:void(0);" @click="relogin">
{{ $t('Re-login') }} {{ tt('Re-login') }}
</a> </a>
</v-col> </v-col>
</v-row> </v-row>
@@ -106,16 +106,21 @@
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import ConfirmDialog from '@/components/desktop/ConfirmDialog.vue';
import SnackBar from '@/components/desktop/SnackBar.vue';
import { ref, computed, useTemplateRef } from 'vue';
import { useRouter } from 'vue-router';
import { useTheme } from 'vuetify'; import { useTheme } from 'vuetify';
import { mapStores } from 'pinia'; import type { LanguageOption } from '@/locales/index.ts';
import { useRootStore } from '@/stores/index.js'; import { useI18n } from '@/locales/helpers.ts';
import { useUnlockPageBase } from '@/views/base/UnlockPageBase.ts';
import { useSettingsStore } from '@/stores/setting.ts'; import { useSettingsStore } from '@/stores/setting.ts';
import { useUserStore } from '@/stores/user.ts'; import { useUserStore } from '@/stores/user.ts';
import { useTokensStore } from '@/stores/token.ts';
import { useTransactionsStore } from '@/stores/transaction.js';
import { useExchangeRatesStore } from '@/stores/exchangeRates.ts';
import { APPLICATION_LOGO_PATH } from '@/consts/asset.ts'; import { APPLICATION_LOGO_PATH } from '@/consts/asset.ts';
import { ThemeType } from '@/core/theme.ts'; import { ThemeType } from '@/core/theme.ts';
@@ -129,165 +134,103 @@ import {
hasWebAuthnConfig, hasWebAuthnConfig,
getWebAuthnCredentialId getWebAuthnCredentialId
} from '@/lib/userstate.ts'; } from '@/lib/userstate.ts';
import { setExpenseAndIncomeAmountColor } from '@/lib/ui/common.ts';
import logger from '@/lib/logger.ts'; import logger from '@/lib/logger.ts';
export default { type ConfirmDialogType = InstanceType<typeof ConfirmDialog>;
data() { type SnackBarType = InstanceType<typeof SnackBar>;
return {
pinCode: '', const router = useRouter();
verifyingByWebAuthn: false const theme = useTheme();
};
}, const { tt, getCurrentLanguageDisplayName, getAllLanguageOptions } = useI18n();
computed: { const { version, pinCode, isWebAuthnAvailable, isPinCodeValid, changeLanguage, doAfterUnlocked, doRelogin } = useUnlockPageBase();
...mapStores(useRootStore, useSettingsStore, useUserStore, useTokensStore, useTransactionsStore, useExchangeRatesStore),
ezBookkeepingLogoPath() { const settingsStore = useSettingsStore();
return APPLICATION_LOGO_PATH; const userStore = useUserStore();
},
version() { const confirmDialog = useTemplateRef<ConfirmDialogType>('confirmDialog');
return 'v' + this.$version; const snackbar = useTemplateRef<SnackBarType>('snackbar');
},
allLanguages() { const verifyingByWebAuthn = ref<boolean>(false);
return this.$locale.getAllLanguageInfoArray(false);
}, const allLanguages = computed<LanguageOption[]>(() => getAllLanguageOptions(false));
isWebAuthnAvailable() { const isDarkMode = computed<boolean>(() => theme.global.name.value === ThemeType.Dark);
return this.settingsStore.appSettings.applicationLockWebAuthn const currentLanguageName = computed<string>(() => getCurrentLanguageDisplayName());
&& hasWebAuthnConfig()
&& isWebAuthnSupported(); function unlockByWebAuthn(): void {
}, const webAuthnCredentialId = getWebAuthnCredentialId();
isDarkMode() {
return this.globalTheme.global.name.value === ThemeType.Dark; if (!userStore.currentUserBasicInfo || !webAuthnCredentialId) {
}, snackbar.value?.showMessage('An error occurred');
currentLanguageName() { return;
return this.$locale.getCurrentLanguageDisplayName(); }
if (!settingsStore.appSettings.applicationLockWebAuthn || !hasWebAuthnConfig()) {
snackbar.value?.showMessage('WebAuthn is not enabled');
return;
}
if (!isWebAuthnSupported()) {
snackbar.value?.showMessage('WebAuth is not supported on this device');
return;
}
verifyingByWebAuthn.value = true;
verifyWebAuthnCredential(
userStore.currentUserBasicInfo,
webAuthnCredentialId
).then(({ id, userName, userSecret }) => {
verifyingByWebAuthn.value = false;
unlockTokenByWebAuthn(id, userName, userSecret);
doAfterUnlocked();
router.replace('/');
}).catch(error => {
verifyingByWebAuthn.value = false;
logger.error('failed to use webauthn to verify', error);
if (error.notSupported) {
snackbar.value?.showMessage('WebAuth is not supported on this device');
} else if (error.name === 'NotAllowedError') {
snackbar.value?.showMessage('User has canceled authentication');
} else if (error.invalid) {
snackbar.value?.showMessage('Failed to authenticate with WebAuthn');
} else {
snackbar.value?.showMessage('User has canceled or this device does not support WebAuthn');
} }
}, });
setup() { }
const theme = useTheme();
return { function unlockByPin(pinCode: string): void {
globalTheme: theme if (!isPinCodeValid(pinCode)) {
}; return;
}, }
methods: {
unlockByWebAuthn() {
const self = this;
if (!self.settingsStore.appSettings.applicationLockWebAuthn || !hasWebAuthnConfig()) { const user = userStore.currentUserBasicInfo;
self.$refs.snackbar.showMessage('WebAuthn is not enabled');
return;
}
if (!isWebAuthnSupported()) { if (!user || !user.username) {
self.$refs.snackbar.showMessage('WebAuth is not supported on this device'); snackbar.value?.showMessage('An error occurred');
return; return;
} }
self.verifyingByWebAuthn = true; try {
unlockTokenByPinCode(user.username, pinCode);
doAfterUnlocked();
verifyWebAuthnCredential( router.replace('/');
self.userStore.currentUserBasicInfo, } catch (ex) {
getWebAuthnCredentialId() logger.error('failed to unlock with pin code', ex);
).then(({ id, userName, userSecret }) => { snackbar.value?.showMessage('Incorrect PIN code');
self.verifyingByWebAuthn = false;
unlockTokenByWebAuthn(id, userName, userSecret);
self.transactionsStore.initTransactionDraft();
self.tokensStore.refreshTokenAndRevokeOldToken().then(response => {
if (response.user) {
const localeDefaultSettings = self.$locale.setLanguage(response.user.language);
self.settingsStore.updateLocalizedDefaultSettings(localeDefaultSettings);
setExpenseAndIncomeAmountColor(response.user.expenseAmountColor, response.user.incomeAmountColor);
}
if (response.notificationContent) {
self.rootStore.setNotificationContent(response.notificationContent);
}
});
if (self.settingsStore.appSettings.autoUpdateExchangeRatesData) {
self.exchangeRatesStore.getLatestExchangeRates({ silent: true, force: false });
}
self.$router.replace('/');
}).catch(error => {
self.verifyingByWebAuthn = false;
logger.error('failed to use webauthn to verify', error);
if (error.notSupported) {
self.$refs.snackbar.showMessage('WebAuth is not supported on this device');
} else if (error.name === 'NotAllowedError') {
self.$refs.snackbar.showMessage('User has canceled authentication');
} else if (error.invalid) {
self.$refs.snackbar.showMessage('Failed to authenticate with WebAuthn');
} else {
self.$refs.snackbar.showMessage('User has canceled or this device does not support WebAuthn');
}
});
},
unlockByPin(pinCode) {
const self = this;
if (!self.isPinCodeValid(pinCode)) {
return;
}
const user = self.userStore.currentUserBasicInfo;
if (!user || !user.username) {
self.$refs.snackbar.showMessage('An error occurred');
return;
}
try {
unlockTokenByPinCode(user.username, pinCode);
self.transactionsStore.initTransactionDraft();
self.tokensStore.refreshTokenAndRevokeOldToken().then(response => {
if (response.user) {
const localeDefaultSettings = self.$locale.setLanguage(response.user.language);
self.settingsStore.updateLocalizedDefaultSettings(localeDefaultSettings);
setExpenseAndIncomeAmountColor(response.user.expenseAmountColor, response.user.incomeAmountColor);
}
if (response.notificationContent) {
self.rootStore.setNotificationContent(response.notificationContent);
}
});
if (self.settingsStore.appSettings.autoUpdateExchangeRatesData) {
self.exchangeRatesStore.getLatestExchangeRates({ silent: true, force: false });
}
self.$router.replace('/');
} catch (ex) {
logger.error('failed to unlock with pin code', ex);
self.$refs.snackbar.showMessage('Incorrect PIN code');
}
},
relogin() {
const self = this;
self.$refs.confirmDialog.open('Are you sure you want to re-login?').then(() => {
self.rootStore.forceLogout();
self.settingsStore.clearAppSettings();
const localeDefaultSettings = self.$locale.initLocale(self.userStore.currentUserLanguage, self.settingsStore.appSettings.timeZone);
self.settingsStore.updateLocalizedDefaultSettings(localeDefaultSettings);
setExpenseAndIncomeAmountColor(self.userStore.currentUserExpenseAmountColor, self.userStore.currentUserIncomeAmountColor);
self.$router.replace('/login');
});
},
isPinCodeValid(pinCode) {
return pinCode && pinCode.length === 6;
},
changeLanguage(locale) {
const localeDefaultSettings = this.$locale.setLanguage(locale);
this.settingsStore.updateLocalizedDefaultSettings(localeDefaultSettings);
}
} }
} }
function relogin(): void {
confirmDialog.value?.open('Are you sure you want to re-login?').then(() => {
doRelogin();
router.replace('/login');
});
}
</script> </script>
+107 -166
View File
@@ -1,14 +1,14 @@
<template> <template>
<f7-page no-navbar no-swipeback login-screen hide-toolbar-on-scroll> <f7-page no-navbar no-swipeback login-screen hide-toolbar-on-scroll>
<f7-login-screen-title> <f7-login-screen-title>
<img alt="logo" class="login-page-logo" :src="ezBookkeepingLogoPath" /> <img alt="logo" class="login-page-logo" :src="APPLICATION_LOGO_PATH" />
<f7-block class="login-page-tile margin-vertical-half">{{ $t('global.app.title') }}</f7-block> <f7-block class="login-page-tile margin-vertical-half">{{ tt('global.app.title') }}</f7-block>
</f7-login-screen-title> </f7-login-screen-title>
<f7-list form> <f7-list form>
<f7-list-item class="no-padding no-margin"> <f7-list-item class="no-padding no-margin">
<template #inner> <template #inner>
<div class="display-flex justify-content-center full-line">{{ $t('Unlock Application') }}</div> <div class="display-flex justify-content-center full-line">{{ tt('Unlock Application') }}</div>
</template> </template>
</f7-list-item> </f7-list-item>
<f7-list-item class="list-item-pincode-input padding-horizontal margin-horizontal"> <f7-list-item class="list-item-pincode-input padding-horizontal margin-horizontal">
@@ -17,10 +17,10 @@
</f7-list> </f7-list>
<f7-list> <f7-list>
<f7-list-button :class="{ 'disabled': !isPinCodeValid(pinCode) }" :text="$t('Unlock with PIN Code')" @click="unlockByPin"></f7-list-button> <f7-list-button :class="{ 'disabled': !isPinCodeValid(pinCode) }" :text="tt('Unlock with PIN Code')" @click="unlockByPin"></f7-list-button>
<f7-list-button v-if="isWebAuthnAvailable" :text="$t('Unlock with WebAuthn')" @click="unlockByWebAuthn"></f7-list-button> <f7-list-button v-if="isWebAuthnAvailable" :text="tt('Unlock with WebAuthn')" @click="unlockByWebAuthn"></f7-list-button>
<f7-block-footer> <f7-block-footer>
<f7-link :text="$t('Re-login')" @click="relogin"></f7-link> <f7-link :text="tt('Re-login')" @click="relogin"></f7-link>
</f7-block-footer> </f7-block-footer>
<f7-block-footer class="padding-bottom"> <f7-block-footer class="padding-bottom">
</f7-block-footer> </f7-block-footer>
@@ -64,14 +64,17 @@
</f7-page> </f7-page>
</template> </template>
<script> <script setup lang="ts">
import { mapStores } from 'pinia'; import { computed } from 'vue';
import { useRootStore } from '@/stores/index.js'; import type { Router } from 'framework7/types';
import type { LanguageOption } from '@/locales/index.ts';
import { useI18n } from '@/locales/helpers.ts';
import { useI18nUIComponents, showLoading, hideLoading } from '@/lib/ui/mobile.ts';
import { useUnlockPageBase } from '@/views/base/UnlockPageBase.ts';
import { useSettingsStore } from '@/stores/setting.ts'; import { useSettingsStore } from '@/stores/setting.ts';
import { useUserStore } from '@/stores/user.ts'; import { useUserStore } from '@/stores/user.ts';
import { useTokensStore } from '@/stores/token.ts';
import { useTransactionsStore } from '@/stores/transaction.js';
import { useExchangeRatesStore } from '@/stores/exchangeRates.ts';
import { APPLICATION_LOGO_PATH } from '@/consts/asset.ts'; import { APPLICATION_LOGO_PATH } from '@/consts/asset.ts';
import { import {
@@ -84,170 +87,108 @@ import {
hasWebAuthnConfig, hasWebAuthnConfig,
getWebAuthnCredentialId getWebAuthnCredentialId
} from '@/lib/userstate.ts'; } from '@/lib/userstate.ts';
import { setExpenseAndIncomeAmountColor } from '@/lib/ui/common.ts';
import { isModalShowing } from '@/lib/ui/mobile.ts'; import { isModalShowing } from '@/lib/ui/mobile.ts';
import logger from '@/lib/logger.ts'; import logger from '@/lib/logger.ts';
export default { const { tt, getCurrentLanguageTag, getCurrentLanguageDisplayName, getAllLanguageOptions } = useI18n();
props: [ const { showToast, showConfirm } = useI18nUIComponents();
'f7router' const { version, pinCode, isWebAuthnAvailable, isPinCodeValid, changeLanguage, doAfterUnlocked, doRelogin } = useUnlockPageBase();
],
data() { const settingsStore = useSettingsStore();
return { const userStore = useUserStore();
pinCode: ''
const props = defineProps<{
f7router: Router.Router;
}>();
const allLanguages = computed<LanguageOption[]>(() => getAllLanguageOptions(false));
const currentLanguageCode = computed<string>(() => getCurrentLanguageTag());
const currentLanguageName = computed<string>(() => getCurrentLanguageDisplayName());
function unlockByWebAuthn(): void {
const router = props.f7router;
const webAuthnCredentialId = getWebAuthnCredentialId();
if (!userStore.currentUserBasicInfo || !webAuthnCredentialId) {
showToast('An error occurred');
return;
}
if (!settingsStore.appSettings.applicationLockWebAuthn || !hasWebAuthnConfig()) {
showToast('WebAuthn is not enabled');
return;
}
if (!isWebAuthnSupported()) {
showToast('WebAuth is not supported on this device');
return;
}
showLoading();
verifyWebAuthnCredential(
userStore.currentUserBasicInfo,
webAuthnCredentialId
).then(({ id, userName, userSecret }) => {
hideLoading();
unlockTokenByWebAuthn(id, userName, userSecret);
doAfterUnlocked();
router.refreshPage();
}).catch(error => {
hideLoading();
logger.error('failed to use webauthn to verify', error);
if (error.notSupported) {
showToast('WebAuth is not supported on this device');
} else if (error.name === 'NotAllowedError') {
showToast('User has canceled authentication');
} else if (error.invalid) {
showToast('Failed to authenticate with WebAuthn');
} else {
showToast('User has canceled or this device does not support WebAuthn');
} }
}, });
computed: { }
...mapStores(useRootStore, useSettingsStore, useUserStore, useTokensStore, useTransactionsStore, useExchangeRatesStore),
ezBookkeepingLogoPath() {
return APPLICATION_LOGO_PATH;
},
version() {
return 'v' + this.$version;
},
allLanguages() {
return this.$locale.getAllLanguageInfoArray(false);
},
isWebAuthnAvailable() {
return this.settingsStore.appSettings.applicationLockWebAuthn
&& hasWebAuthnConfig()
&& isWebAuthnSupported();
},
currentLanguageCode() {
return this.$locale.getCurrentLanguageTag();
},
currentLanguageName() {
return this.$locale.getCurrentLanguageDisplayName();
}
},
methods: {
unlockByWebAuthn() {
const self = this;
const router = self.f7router;
if (!self.settingsStore.appSettings.applicationLockWebAuthn || !hasWebAuthnConfig()) { function unlockByPin(pinCode: string): void {
self.$toast('WebAuthn is not enabled'); if (!isPinCodeValid(pinCode)) {
return; return;
} }
if (!isWebAuthnSupported()) { if (isModalShowing()) {
self.$toast('WebAuth is not supported on this device'); return;
return; }
}
self.$showLoading(); const router = props.f7router;
const user = userStore.currentUserBasicInfo;
verifyWebAuthnCredential( if (!user || !user.username) {
self.userStore.currentUserBasicInfo, showToast('An error occurred');
getWebAuthnCredentialId() return;
).then(({ id, userName, userSecret }) => { }
self.$hideLoading();
unlockTokenByWebAuthn(id, userName, userSecret); try {
self.transactionsStore.initTransactionDraft(); unlockTokenByPinCode(user.username, pinCode);
self.tokensStore.refreshTokenAndRevokeOldToken().then(response => { doAfterUnlocked();
if (response.user) {
const localeDefaultSettings = self.$locale.setLanguage(response.user.language);
self.settingsStore.updateLocalizedDefaultSettings(localeDefaultSettings);
setExpenseAndIncomeAmountColor(response.user.expenseAmountColor, response.user.incomeAmountColor); router.refreshPage();
} } catch (ex) {
logger.error('failed to unlock with pin code', ex);
if (response.notificationContent) { showToast('Incorrect PIN code');
self.rootStore.setNotificationContent(response.notificationContent);
}
});
if (self.settingsStore.appSettings.autoUpdateExchangeRatesData) {
self.exchangeRatesStore.getLatestExchangeRates({ silent: true, force: false });
}
router.refreshPage();
}).catch(error => {
self.$hideLoading();
logger.error('failed to use webauthn to verify', error);
if (error.notSupported) {
self.$toast('WebAuth is not supported on this device');
} else if (error.name === 'NotAllowedError') {
self.$toast('User has canceled authentication');
} else if (error.invalid) {
self.$toast('Failed to authenticate with WebAuthn');
} else {
self.$toast('User has canceled or this device does not support WebAuthn');
}
});
},
unlockByPin(pinCode) {
const self = this;
if (!self.isPinCodeValid(pinCode)) {
return;
}
if (isModalShowing()) {
return;
}
const router = self.f7router;
const user = self.userStore.currentUserBasicInfo;
if (!user || !user.username) {
self.$alert('An error occurred');
return;
}
try {
unlockTokenByPinCode(user.username, pinCode);
self.transactionsStore.initTransactionDraft();
self.tokensStore.refreshTokenAndRevokeOldToken().then(response => {
if (response.user) {
const localeDefaultSettings = self.$locale.setLanguage(response.user.language);
self.settingsStore.updateLocalizedDefaultSettings(localeDefaultSettings);
setExpenseAndIncomeAmountColor(response.user.expenseAmountColor, response.user.incomeAmountColor);
}
if (response.notificationContent) {
self.rootStore.setNotificationContent(response.notificationContent);
}
});
if (self.settingsStore.appSettings.autoUpdateExchangeRatesData) {
self.exchangeRatesStore.getLatestExchangeRates({ silent: true, force: false });
}
router.refreshPage();
} catch (ex) {
logger.error('failed to unlock with pin code', ex);
self.$toast('Incorrect PIN code');
}
},
relogin() {
const self = this;
const router = self.f7router;
self.$confirm('Are you sure you want to re-login?', () => {
self.rootStore.forceLogout();
self.settingsStore.clearAppSettings();
const localeDefaultSettings = self.$locale.initLocale(self.userStore.currentUserLanguage, self.settingsStore.appSettings.timeZone);
self.settingsStore.updateLocalizedDefaultSettings(localeDefaultSettings);
setExpenseAndIncomeAmountColor(self.userStore.currentUserExpenseAmountColor, self.userStore.currentUserIncomeAmountColor);
router.navigate('/login', {
clearPreviousHistory: true
});
});
},
isPinCodeValid(pinCode) {
return pinCode && pinCode.length === 6;
},
changeLanguage(locale) {
const localeDefaultSettings = this.$locale.setLanguage(locale);
this.settingsStore.updateLocalizedDefaultSettings(localeDefaultSettings);
}
} }
} }
function relogin(): void {
const router = props.f7router;
showConfirm('Are you sure you want to re-login?', () => {
doRelogin();
router.navigate('/login', {
clearPreviousHistory: true
});
});
}
</script> </script>