damus.io

damus.io website
git clone git://jb55.com/damus.io
Log | Files | Refs | README | LICENSE

usePurpleLoginSession.ts (1653B)


      1 import { useState, useEffect } from "react";
      2 import { useLocalStorage } from "usehooks-ts";
      3 import { AccountInfo } from "@/utils/PurpleUtils";
      4 
      5 
      6 export function usePurpleLoginSession(setError: (message: string) => void) {
      7   const [sessionToken, setSessionToken] = useLocalStorage('session_token', null);
      8   const [accountInfo, setAccountInfo] = useState<AccountInfo | undefined | null>(undefined);
      9   
     10   const logout = () => {
     11     setSessionToken(null);
     12     setAccountInfo(null);
     13   };
     14 
     15   useEffect(() => {
     16     const fetchAccountInfo = async () => {
     17       if (!sessionToken) {
     18         setAccountInfo(null);
     19         return;
     20       }
     21 
     22       try {
     23         const response = await fetch(process.env.NEXT_PUBLIC_PURPLE_API_BASE_URL + "/sessions/account", {
     24           method: 'GET',
     25           headers: {
     26             'Content-Type': 'application/json',
     27             'Authorization': 'Bearer ' + sessionToken
     28           },
     29         });
     30         
     31         if (response.status === 401) {
     32           setSessionToken(null);
     33           setAccountInfo(null);
     34           return;
     35         }
     36 
     37         if (!response.ok) {
     38           setError("Failed to get account info from our servers. Please wait a few minutes and refresh the page. If the problem persists, please contact support.");
     39           return;
     40         }
     41 
     42         const accountInfo = await response.json();
     43         setAccountInfo(accountInfo);
     44       } catch (e) {
     45         setError("Failed to get account info from our servers. Please wait a few minutes and refresh the page. If the problem persists, please contact support.");
     46       }
     47     };
     48 
     49     fetchAccountInfo();
     50   }, [sessionToken]);
     51 
     52   return { accountInfo, logout }
     53 }