diff --git a/app/lib/hooks/useGit.ts b/app/lib/hooks/useGit.ts index dd3b75f..3c8c61b 100644 --- a/app/lib/hooks/useGit.ts +++ b/app/lib/hooks/useGit.ts @@ -1,35 +1,38 @@ import type { WebContainer } from '@webcontainer/api'; import { useCallback, useEffect, useRef, useState, type MutableRefObject } from 'react'; import { webcontainer as webcontainerPromise } from '~/lib/webcontainer'; -import git, { type PromiseFsClient } from 'isomorphic-git'; +import git, { type GitAuth, type PromiseFsClient } from 'isomorphic-git'; import http from 'isomorphic-git/http/web'; import Cookies from 'js-cookie'; import { toast } from 'react-toastify'; +const lookupSavedPassword = (url: string) => { + const domain = url.split('/')[2]; + const gitCreds = Cookies.get(`git:${domain}`); + + if (!gitCreds) { + return null; + } + + try { + const { username, password } = JSON.parse(gitCreds || '{}'); + return { username, password }; + } catch (error) { + console.log(`Failed to parse Git Cookie ${error}`); + return null; + } +}; + +const saveGitAuth = (url: string, auth: GitAuth) => { + const domain = url.split('/')[2]; + Cookies.set(`git:${domain}`, JSON.stringify(auth)); +}; + export function useGit() { const [ready, setReady] = useState(false); const [webcontainer, setWebcontainer] = useState(); const [fs, setFs] = useState(); const fileData = useRef>({}); - const lookupSavedPassword: (url: string) => any | null = (url: string) => { - try { - // Save updated API keys to cookies with 30 day expiry and secure settings - const creds = Cookies.get(`git:${url}`); - - if (creds) { - const parsedCreds = JSON.parse(creds); - - if (typeof parsedCreds === 'object' && parsedCreds !== null) { - return parsedCreds; - } - } - - return null; - } catch (error) { - console.error('Error saving API keys to cookies:', error); - return null; - } - }; useEffect(() => { webcontainerPromise.then((container) => { fileData.current = {}; @@ -76,6 +79,9 @@ export function useGit() { onAuthFailure: (url, _auth) => { toast.error(`Error Authenticating with ${url.split('/')[2]}`); }, + onAuthSuccess: (url, auth) => { + saveGitAuth(url, auth); + }, }); const data: Record = {};