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 {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 ms from "ms";
import {useQuery} from "@tanstack/react-query"; import {useQuery} from "@tanstack/react-query";
import {TypedPocketBase} from "@/models"; import {TypedPocketBase} from "@/models";
@ -8,6 +14,7 @@ import {UserModal} from "@/models/AuthTypes.ts";
import {Alert, List} from "@mantine/core"; import {Alert, List} from "@mantine/core";
import {IconAlertTriangle} from "@tabler/icons-react"; import {IconAlertTriangle} from "@tabler/icons-react";
import {showSuccessNotification} from "@/components/util.tsx"; 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({}) const PocketContext = createContext({})
@ -72,10 +79,15 @@ const PocketData = () => {
refetchInterval: oneMinuteInMs refetchInterval: oneMinuteInMs
}) })
const refreshUserQuery = useQuery({ useQuery({
queryKey: ["refreshUser"], queryKey: ["refreshAuthToken"],
queryFn: async () => { queryFn: async () => {
try { 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({ const {record, token} = await pb.collection(PB_USER_COLLECTION).authRefresh({
expand: "memberOf" expand: "memberOf"
}) })
@ -86,6 +98,27 @@ const PocketData = () => {
return null 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 refetchInterval: oneMinuteInMs
}) })
@ -115,7 +148,6 @@ const PocketData = () => {
await pb.collection("users").authWithPassword(usernameOrEmail, password).then(res => { await pb.collection("users").authWithPassword(usernameOrEmail, password).then(res => {
pb.authStore.clear() pb.authStore.clear()
pb.authStore.save(res.token, res.record) pb.authStore.save(res.token, res.record)
console.log(res.record)
}) })
}, [pb]) }, [pb])