import { computed, watch } from 'vue' import router from '@/router' import { authenticateWithFingerprint, getToken, isIphone, removeToken } from '@/utils' import { useUserStore } from '@/store/userStore' import { useWalletStore } from '@/store/walletStore' import type { NavigationGuardNext, RouteLocationNormalized } from 'vue-router' import { useAuthStore } from '@/store/useAuthStore' import { clearFingerTimeout, getFingerPosition, getHasFingerPrint, setFingerPosition, setFingerTimeOut, setHasFingerPrint } from '@/app/authBoot' export function setupRouterGuards() { const userStore = useUserStore() const walletStore = useWalletStore() const authStore = useAuthStore() const isApple: boolean = isIphone() let isFirst = true const currentRoute = computed(() => router.currentRoute.value.fullPath) async function start() { if (!getToken()) { return } const tasks: Promise[] = [ walletStore.getLimitedPrice(), walletStore.getLimitedBuyGold(), ] if (!userStore.userInfo) { tasks.push(userStore.getMyInfo()) } await Promise.all(tasks) } function goToLogin(to: RouteLocationNormalized, next: NavigationGuardNext) { if (to.name === 'buyProduct' || to.name === 'productDetail' || to.name === 'about' || to.name === 'cart') { return next() } if (to.name !== 'login') { return next({ name: 'login' }) } return next() } function goToHome(to: RouteLocationNormalized, next: NavigationGuardNext) { if (to.name !== 'buyProduct') { return next({ name: 'buyProduct' }) } return next() } router.beforeEach(async (to, from, next) => { authStore.setLoading(true) clearFingerTimeout() setFingerTimeOut(to) if (isFirst) { isFirst = false if (getToken()) { await userStore.getMyInfo() const finger_print = userStore.userInfo.finger_print setHasFingerPrint(finger_print) if (isApple && finger_print) { removeToken() goToLogin(to, next) } else if (!isApple && finger_print) { setFingerPosition(await authenticateWithFingerprint()) if (!getFingerPosition()) { goToLogin(to, next) } } else { if (to.name == 'login') { goToHome(to, next) } return next() } } else { if (['login', '404', 'buyProduct', 'productDetail', 'about', 'cart'].includes(to.name as string)) { return next() } goToLogin(to, next) } } else { if (getFingerPosition()) { if (getToken()) { if (to.name === 'login') { return next({ name: from.name || 'buyProduct' }) } return next() } if (['login', '404', 'buyProduct', 'productDetail', 'about', 'cart'].includes(to.name as string)) { return next() } return next({ name: 'login' }) } if (getToken() && !getHasFingerPrint()) { next() } else { goToLogin(to, next) } } }) watch(currentRoute, async () => (userStore.userInfo ? '' : await start())) }