fix: expire invalid CMS sessions cleanly
This commit is contained in:
+13
-2
@@ -22,6 +22,11 @@ const SIDEBAR = [
|
||||
|
||||
function useAuth(){
|
||||
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 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()
|
||||
@@ -33,11 +38,17 @@ function useAuth(){
|
||||
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||{})}
|
||||
if(token) headers['Authorization']='Bearer '+token
|
||||
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> = {
|
||||
|
||||
Reference in New Issue
Block a user