diff --git a/src/components/SocialAuth/GoogleButton.tsx b/src/components/SocialAuth/GoogleButton.tsx new file mode 100644 index 000000000..d9908375e --- /dev/null +++ b/src/components/SocialAuth/GoogleButton.tsx @@ -0,0 +1,92 @@ +import { useEffect, useState } from 'preact/hooks'; + +import GoogleIcon from '../../icons/google.svg'; +import SpinnerIcon from '../../icons/spinner.svg'; +import { TOKEN_COOKIE_NAME } from '../../lib/constants'; +import Cookies from 'js-cookie'; + +type GoogleButtonProps = {}; + +export function GoogleButton(props: GoogleButtonProps) { + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(''); + const icon = isLoading ? SpinnerIcon : GoogleIcon; + + useEffect(() => { + const urlParams = new URLSearchParams(window.location.search); + const code = urlParams.get('code'); + const state = urlParams.get('state'); + const provider = urlParams.get('provider'); + + if (!code || !state || provider !== 'google') { + return; + } + + setIsLoading(true); + fetch( + `${import.meta.env.PUBLIC_API_URL}/v1-google-callback${ + window.location.search + }`, + { + method: 'GET', + credentials: 'include', + } + ) + .then((res) => res.json()) + .then((data: any) => { + if (!data.token) { + setError('Something went wrong. Please try again later.'); + setIsLoading(false); + } else { + Cookies.set(TOKEN_COOKIE_NAME, data.token); + window.location.href = '/'; + } + }) + .catch((err) => { + setError('Something went wrong. Please try again later.'); + setIsLoading(false); + }); + }, []); + + const handleClick = () => { + setIsLoading(true); + fetch(`${import.meta.env.PUBLIC_API_URL}/v1-google-login`, { + credentials: 'include', + redirect: 'follow', + }) + .then((res) => res.json()) + .then((data: any) => { + // @todo proper typing for API response + if (data.loginUrl) { + window.location.href = data.loginUrl; + } else { + setError('Something went wrong. Please try again later.'); + setIsLoading(false); + } + }) + .catch((err) => { + setError('Something went wrong. Please try again later.'); + setIsLoading(false); + }); + }; + + return ( + <> + + {error && ( +
{error}
+ )} + > + ); +} diff --git a/src/pages/[roadmapId]/index.astro b/src/pages/[roadmapId]/index.astro index e316f6f2e..9b3b9ec72 100644 --- a/src/pages/[roadmapId]/index.astro +++ b/src/pages/[roadmapId]/index.astro @@ -105,7 +105,5 @@ const contentContributionLink = `https://github.com/kamranahmedse/developer-road