Add shared device inactivity timeout to AuthGate
This commit is contained in:
parent
c15bff37c9
commit
0200775030
1 changed files with 33 additions and 1 deletions
|
|
@ -1,4 +1,11 @@
|
|||
import { useEffect, useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
const SHARED_TIMEOUT_MS = 10 * 60 * 1000
|
||||
|
||||
function isSharedDevice() {
|
||||
return document.cookie.split(';').some(c => c.trim() === 'hnf_shared_device=1')
|
||||
}
|
||||
|
||||
|
||||
interface User {
|
||||
email: string
|
||||
|
|
@ -17,6 +24,7 @@ export function AuthGate({ children }: Props) {
|
|||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
fetch('/api/auth/verify?app=noticeboard', { credentials: 'include' })
|
||||
|
|
@ -32,6 +40,30 @@ export function AuthGate({ children }: Props) {
|
|||
.catch(() => setState('login'))
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (state !== 'authed' || !isSharedDevice()) return
|
||||
|
||||
async function forceLogout() {
|
||||
await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }).catch(() => {})
|
||||
setUser(null)
|
||||
setState('login')
|
||||
}
|
||||
|
||||
function reset() {
|
||||
if (timerRef.current) clearTimeout(timerRef.current)
|
||||
timerRef.current = setTimeout(forceLogout, SHARED_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
const events = ['mousemove', 'keydown', 'click', 'touchstart'] as const
|
||||
events.forEach(e => window.addEventListener(e, reset, { passive: true }))
|
||||
reset()
|
||||
|
||||
return () => {
|
||||
if (timerRef.current) clearTimeout(timerRef.current)
|
||||
events.forEach(e => window.removeEventListener(e, reset))
|
||||
}
|
||||
}, [state])
|
||||
|
||||
async function login(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setLoading(true)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue