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
This commit is contained in:
@@ -1,12 +1,57 @@
|
||||
"use client"
|
||||
|
||||
import { signOut, useSession } from "next-auth/react"
|
||||
import { signIn, signOut, useSession } from "next-auth/react"
|
||||
import { useEffect, useState } from "react"
|
||||
import { useLocalStorage } from "usehooks-ts"
|
||||
|
||||
export function SessionRefresher() {
|
||||
const session = useSession()
|
||||
if (session.data?.error === "RefreshAccessTokenError") {
|
||||
signOut({ redirect: false })
|
||||
}
|
||||
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 }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user