at main 96 lines 3.1 kB view raw
1import { useCallback, useEffect, useState } from 'react'; 2import { RoleContext, PushServerContext } from '../../context'; 3import { WhoAmI } from '../WhoAmI'; 4import { SecretPassword } from '../SecretPassword'; 5import { GetJson, PostJson } from '../Fetch'; 6import { Chrome } from './Chrome'; 7 8export function WithServerHello({ children }) { 9 const [loggingOut, setLoggingOut] = useState(null); 10 const [helloKey, setHelloKey] = useState(0); 11 const [whoamiKey, setWhoamiKey] = useState(0); 12 const [whoamiInfo, setWhoamiInfo] = useState(null); 13 14 const childrenFor = useCallback((did, role, parentChildren) => { 15 if (role === 'public') { 16 return <SecretPassword did={did} role={role} />; 17 } 18 return parentChildren; 19 }) 20 21 const reloadConnect = useCallback(e => { 22 e.preventDefault(); 23 setWhoamiKey(n => n + 1); 24 }); 25 26 const handleLogout = useCallback(async () => { 27 setLoggingOut(true); 28 try { 29 const host = import.meta.env.VITE_NOTIFICATIONS_HOST; 30 await fetch(`${host}/logout`, { 31 method: 'POST', 32 credentials: 'include', 33 }); 34 // TODO: cancel subscription, clear storage, etc 35 } catch (e) { 36 console.error('logout fail', e); 37 } 38 setLoggingOut(null); 39 setHelloKey(n => n + 1); 40 }); 41 42 if (loggingOut !== null) { 43 return <Chrome><p>Logging out&hellip;</p></Chrome>; 44 } 45 46 return ( 47 <GetJson 48 /* todo: key on login state */ 49 key={helloKey} 50 endpoint='/hello' 51 credentials 52 ok={({ whoamiHost, webPushPublicKey, role, did }) => { 53 if (role === 'anonymous') { 54 return whoamiInfo === null 55 ? ( 56 <Chrome> 57 <WhoAmI 58 key={whoamiKey} 59 origin={whoamiHost} 60 onIdentify={setWhoamiInfo} 61 /> 62 <p style={{fontSize: '0.8rem'}}> 63 <a href="#" onClick={reloadConnect}>Reload connect prompt</a> 64 </p> 65 </Chrome> 66 ) : ( 67 <PostJson 68 endpoint="/verify" 69 data={{ token: whoamiInfo.token }} 70 credentials 71 ok={({ did, role, webPushPublicKey }) => ( 72 <Chrome user={{ did, role }} onLogout={handleLogout}> 73 <PushServerContext.Provider value={webPushPublicKey}> 74 <RoleContext.Provider value={role}> 75 {childrenFor(did, role, children)} 76 </RoleContext.Provider> 77 </PushServerContext.Provider> 78 </Chrome> 79 )} 80 /> 81 ) 82 } else { 83 return ( 84 <Chrome user={{ did, role }} onLogout={handleLogout}> 85 <PushServerContext.Provider value={webPushPublicKey}> 86 <RoleContext.Provider value={role}> 87 {childrenFor(did, role, children)} 88 </RoleContext.Provider> 89 </PushServerContext.Provider> 90 </Chrome> 91 ); 92 } 93 }} 94 /> 95 ); 96}