fix: expire invalid CMS sessions cleanly

This commit is contained in:
Codex User
2026-09-09 10:47:33 +08:00
parent d8e3f55a41
commit d37493ac02
+13 -2
View File
@@ -22,6 +22,11 @@ const SIDEBAR = [
function useAuth(){ function useAuth(){
const [token,setToken]=useState(localStorage.getItem('cms_token')||'') const [token,setToken]=useState(localStorage.getItem('cms_token')||'')
useEffect(()=>{
const onUnauthorized=()=>setToken('')
window.addEventListener('cms:unauthorized',onUnauthorized)
return ()=>window.removeEventListener('cms:unauthorized',onUnauthorized)
},[])
const login=async(u:string,p:string)=>{ const login=async(u:string,p:string)=>{
const r=await fetch('/api/auth/login',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({username:u,password:p})}) const r=await fetch('/api/auth/login',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({username:u,password:p})})
const j=await r.json() const j=await r.json()
@@ -33,11 +38,17 @@ function useAuth(){
return {token,login,logout} return {token,login,logout}
} }
function api(path:string, token:string, opts:RequestInit={}){ async function api(path:string, token:string, opts:RequestInit={}){
const headers:any={...(opts.headers||{})} const headers:any={...(opts.headers||{})}
if(token) headers['Authorization']='Bearer '+token if(token) headers['Authorization']='Bearer '+token
if(!(opts.body instanceof FormData)) headers['Content-Type']='application/json' if(!(opts.body instanceof FormData)) headers['Content-Type']='application/json'
return fetch(path,{...opts, headers}).then(r=>r.json()) const response=await fetch(path,{...opts, headers})
const result=await response.json()
if(response.status===401 || result.code===401){
localStorage.removeItem('cms_token')
window.dispatchEvent(new Event('cms:unauthorized'))
}
return result
} }
const FIELD_LABELS:Record<string,string> = { const FIELD_LABELS:Record<string,string> = {