normalize auth provider

This commit is contained in:
Igor Loskutov
2025-09-03 07:10:20 -04:00
parent 97f6db5556
commit 08b82c76ce
14 changed files with 80 additions and 470 deletions

View File

@@ -1,5 +1,5 @@
/**
* This is a custom hook that automatically refreshes the session when the access token is about to expire.
* This is a custom provider that automatically refreshes the session when the access token is about to expire.
* When communicating with the reflector API, we need to ensure that the access token is always valid.
*
* We could have implemented that as an interceptor on the API client, but not everything is using the
@@ -7,31 +7,29 @@
*/
"use client";
import { useSession } from "next-auth/react";
import { useEffect } from "react";
import { assertExtendedToken, CustomSession } from "./types";
import { useAuth } from "./AuthProvider";
export function SessionAutoRefresh({
children,
refreshInterval = 20 /* seconds */,
}) {
const { data: session, update } = useSession();
const accessTokenExpires = session
? assertExtendedToken(session).accessTokenExpires
: null;
const auth = useAuth();
const accessTokenExpires =
auth.status === "authenticated" ? auth.accessTokenExpires : null;
useEffect(() => {
const interval = setInterval(() => {
if (accessTokenExpires) {
const timeLeft = accessTokenExpires - Date.now();
if (timeLeft < refreshInterval * 1000) {
update();
auth.update();
}
}
}, refreshInterval * 1000);
return () => clearInterval(interval);
}, [accessTokenExpires, refreshInterval, update]);
}, [accessTokenExpires, refreshInterval, auth.update]);
return children;
}