From 5a002931575a743bdada7cf30241b8c09142dbd9 Mon Sep 17 00:00:00 2001 From: valentinkolb Date: Tue, 28 May 2024 19:35:49 +0200 Subject: [PATCH] fix(auth): fixed bug where users are logged out automatically if the token refresh didn't succeed --- src/lib/pocketbase.tsx | 42 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/src/lib/pocketbase.tsx b/src/lib/pocketbase.tsx index 0481e00..570ddd9 100644 --- a/src/lib/pocketbase.tsx +++ b/src/lib/pocketbase.tsx @@ -1,5 +1,11 @@ import {createContext, DependencyList, ReactNode, useCallback, useContext, useEffect, useMemo, useState} from "react" -import PocketBase, {ClientResponseError, LocalAuthStore, RecordAuthResponse, RecordSubscription} from 'pocketbase' +import PocketBase, { + ClientResponseError, + getTokenPayload, + LocalAuthStore, + RecordAuthResponse, + RecordSubscription +} from 'pocketbase' import ms from "ms"; import {useQuery} from "@tanstack/react-query"; import {TypedPocketBase} from "@/models"; @@ -8,6 +14,7 @@ import {UserModal} from "@/models/AuthTypes.ts"; import {Alert, List} from "@mantine/core"; import {IconAlertTriangle} from "@tabler/icons-react"; import {showSuccessNotification} from "@/components/util.tsx"; +import dayjs from "dayjs"; /** @@ -51,7 +58,7 @@ export const PocketBaseErrorAlert = ({error}: { error?: Error | null }) => { } -const oneMinuteInMs = ms("1 minute"); +const oneMinuteInMs = ms("1 minute") const PocketContext = createContext({}) @@ -72,10 +79,15 @@ const PocketData = () => { refetchInterval: oneMinuteInMs }) - const refreshUserQuery = useQuery({ - queryKey: ["refreshUser"], + useQuery({ + queryKey: ["refreshAuthToken"], queryFn: async () => { try { + const payload = getTokenPayload(pb.authStore.token) + // test if token expires in 2 days + if (payload.exp === null || !dayjs(payload.exp * 1000).isBefore(dayjs().add(2, "days"))) return null + + // refresh token const {record, token} = await pb.collection(PB_USER_COLLECTION).authRefresh({ expand: "memberOf" }) @@ -86,6 +98,27 @@ const PocketData = () => { return null } }, + enabled: pb.authStore.isValid, + refetchInterval: oneMinuteInMs + }) + + const refreshUserQuery = useQuery({ + queryKey: ["refreshUser"], + queryFn: async () => { + try { + const record = await pb.collection(PB_USER_COLLECTION).getOne(pb.authStore.model?.id ?? "", { + expand: "memberOf" + }) + pb.authStore.save(pb.authStore.token, record) + return record + } catch (e) { + if (e instanceof ClientResponseError && e.status === 401) { + pb.authStore.clear() + } + return null + } + }, + enabled: pb.authStore.isValid, refetchInterval: oneMinuteInMs }) @@ -115,7 +148,6 @@ const PocketData = () => { await pb.collection("users").authWithPassword(usernameOrEmail, password).then(res => { pb.authStore.clear() pb.authStore.save(res.token, res.record) - console.log(res.record) }) }, [pb])