Files
web/apps/partner-sas/app/[lang]/SessionRefresher.tsx
Joakim Jäderberg 9294f0958b Merged in feat/SW-3639-autologin-sas (pull request #3245)
Feat/SW-3639 autologin sas

* wip

* cleanup

* remove commented code and default lang to EN


Approved-by: Anton Gunnarsson
2025-11-28 13:00:42 +00:00

58 lines
1.4 KiB
TypeScript

"use client"
import { signIn, signOut, useSession } from "next-auth/react"
import { useEffect, useState } from "react"
import { useLocalStorage } from "usehooks-ts"
export function SessionRefresher() {
useSilentAuth()
useHandleRefreshError()
return null
}
function useHandleRefreshError() {
const session = useSession()
if (session.data?.error === "RefreshAccessTokenError") {
signOut({ redirect: false })
}
}
const SILENT_AUTH_KEY = "silent-auth"
const SILENT_AUTH_EXPIRY = 6 * 60 * 1000 // 6 hours
function useSilentAuth() {
const { status } = useSession()
const [silentAuthTimestamp, setSilentAuthTimestamp] = useLocalStorage<
string | undefined
>(SILENT_AUTH_KEY, undefined)
const [isLoading, setLoading] = useState(() => status === "unauthenticated")
const hasCompletedSilentSignin =
!!silentAuthTimestamp &&
Date.now() - Number(silentAuthTimestamp) < SILENT_AUTH_EXPIRY
useEffect(() => {
if (status !== "unauthenticated") return
if (hasCompletedSilentSignin) return
setLoading(true)
try {
signIn(
"sas",
{},
{
prompt: "none",
}
)
} finally {
setSilentAuthTimestamp(Date.now().toString())
setLoading(false)
}
}, [hasCompletedSilentSignin, setSilentAuthTimestamp, status])
return { isLoading: status !== "authenticated" && isLoading }
}