fix(auth): fixed bug where users are logged out automatically if the token refresh didn't succeed
Build and Push Docker image / build-and-push (push) Successful in 1m56s Details

This commit is contained in:
Valentin Kolb 2024-05-28 19:35:49 +02:00
parent d1569bce55
commit 5a00293157
1 changed files with 37 additions and 5 deletions

View File

@ -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])