Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add google auth sign in / sign up #530

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 69 additions & 6 deletions apps/sso/components/login-card/login-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,77 @@ import { useHibiscusSupabase } from '@hibiscus/hibiscus-supabase-context';
import { MutatingDots } from 'react-loader-spinner';
import { StyledAuthCard } from '../auth-components/styled-card';
import { Input } from '../auth-components/styled-input';
import {
Button,
ColorSpanBold,
OneLinePassword,
OneLineText,
} from '@hibiscus/ui-kit-2023';
import { Button, ColorSpanBold } from '@hibiscus/ui-kit-2023';
import { AuthError, Session, User } from '@supabase/supabase-js';
import useLoadGoogle from '../../hooks/useLoadGoogle';

type SupabaseRes =
| {
user: User;
session: Session;
}
| {
user: null;
session: null;
};

export function LoginCard() {
const [hideErrorMessage, setHideErrorMessage] = useState(true);
const [errorMessage, setErrorMessage] = useState('');
const [loggedInState, setLoggedInState] = useState('');
const { supabase } = useHibiscusSupabase();

const GoogleCard = useLoadGoogle();

window.handleSignInWithGoogle = async (response) => {
console.log(response);
const { data, error } = await supabase.getClient().auth.signInWithIdToken({
provider: 'google',
token: response.credential,
});

console.log(data, error);

const email = data.user.email!;
const name = data.user.user_metadata.full_name;
const first_name = name.split(' ')[0];
const last_name = name.split(' ')[1] ? name.split(' ')[1] : '';

if (!email) {
setErrorMessage('Email not found');
setHideErrorMessage(false);
}
console.log(email);

const { data: profileData, error: profileError } = await supabase
.getClient()
.from('user_profiles')
.select()
.eq('email', email);

if (profileError) {
console.error(profileError);
}

if (profileData && profileData.length === 0) {
console.log('inserting');
const res = await fetch('/api/googleSignUp', {
method: 'POST',
body: JSON.stringify({
email: email,
first_name: first_name,
last_name: last_name,
user_id: data.user.id,
}),
});
if (res.status !== 200) {
console.error('Failed to insert user profile');
}
}

await signIn(data, error);
};

async function handleSubmit(event) {
event.preventDefault();

Expand All @@ -30,6 +88,10 @@ export function LoginCard() {

const { data, error } = await supabase.signInWithPassword(email, password);

await signIn(data, error);
}

async function signIn(data: SupabaseRes, error: AuthError) {
if (error) {
if (typeof error === 'object' && error !== null && 'message' in error) {
const message = error.message;
Expand Down Expand Up @@ -85,6 +147,7 @@ export function LoginCard() {
</StyledErrorText>
<Button color="blue">SIGN IN</Button>
</StyledForm>
<GoogleCard />
<GrayLink href="/reset-email">Forgot Password?</GrayLink>
<GrayLink href="/signup">Create a HackSC account</GrayLink>

Expand Down
64 changes: 58 additions & 6 deletions apps/sso/components/signup-card/signup-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,11 @@ import { useRouter } from 'next/router';
import Image from 'next/image';
import GrayLink from '../gray-link/gray-link';
import { MutatingDots } from 'react-loader-spinner';
import {
OneLineText,
Button,
ColorSpanBold,
OneLinePassword,
} from '@hibiscus/ui-kit-2023';
import { Button, ColorSpanBold } from '@hibiscus/ui-kit-2023';
import { useHibiscusSupabase } from '@hibiscus/hibiscus-supabase-context';
import { Input } from '../auth-components/styled-input';
import { StyledAuthCard } from '../auth-components/styled-card';
import useLoadGoogle from '../../hooks/useLoadGoogle';

/* eslint-disable-next-line */
export interface SignUpProps {}
Expand All @@ -28,6 +24,61 @@ export function SignUpCard(props: SignUpProps) {
const [errorMessage, setErrorMessage] = useState('');
const [signUpState, setSignUpState] = useState('');

const GoogleCard = useLoadGoogle();

window.handleSignInWithGoogle = async (response) => {
console.log(response);
const { data, error } = await supabase.getClient().auth.signInWithIdToken({
provider: 'google',
token: response.credential,
});

console.log(data, error);

const email = data.user.email!;
const name = data.user.user_metadata.full_name;
const first_name = name.split(' ')[0];
const last_name = name.split(' ')[1] ? name.split(' ')[1] : '';

if (!email) {
setErrorMessage('Email not found');
setHideErrorMessage(false);
}
console.log(email);

const { data: profileData, error: profileError } = await supabase
.getClient()
.from('user_profiles')
.select()
.eq('email', email);

if (profileError) {
console.error(profileError);
}

if (profileData && profileData.length === 0) {
console.log('inserting');
const res = await fetch('/api/googleSignUp', {
method: 'POST',
body: JSON.stringify({
email: email,
first_name: first_name,
last_name: last_name,
user_id: data.user.id,
}),
});
if (res.status !== 200) {
console.error('Failed to insert user profile');
}
}

setSignUpState('signing up');
router.push({
pathname: '/verify',
query: { email, first_name, last_name },
});
};

const handleSubmit = async (event) => {
event.preventDefault();

Expand Down Expand Up @@ -116,6 +167,7 @@ export function SignUpCard(props: SignUpProps) {
{errorMessage}
</StyledErrorText>
<Button color="blue">SIGN UP</Button>
<GoogleCard />
</StyledForm>
<GrayLink href="/login">Have an account? Login</GrayLink>

Expand Down
57 changes: 57 additions & 0 deletions apps/sso/hooks/useLoadGoogle.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { useEffect } from 'react';

const useLoadGoogle = () => {
function loadScript(src: string, position: HTMLElement | null, id: string) {
if (!position) {
return;
}

const script = document.createElement('script');
script.setAttribute('async', '');
script.setAttribute('id', id);
script.src = src;
position.appendChild(script);
}

useEffect(() => {
if (typeof window === 'undefined') return;

const googleSignInScript = document.getElementById('google-signin-client');
if (googleSignInScript) {
googleSignInScript.remove();
}

loadScript(
'https://accounts.google.com/gsi/client',
document.querySelector('body'),
'google-signin-client'
);
}, []);

const GoogleCard = () => (
<>
<div
id="g_id_onload"
data-client_id="661231070007-ojm5n2oc64h55085frrrdcs5o4o43j7r.apps.googleusercontent.com"
data-context="signin"
data-ux_mode="popup"
data-callback="handleSignInWithGoogle"
data-auto_prompt="false"
data-use_fedcm_for_prompt="true"
></div>

<div
className="g_id_signin"
data-type="standard"
data-shape="rectangular"
data-theme="outline"
data-text="signin_with"
data-size="large"
data-logo_alignment="left"
></div>
</>
);
return GoogleCard;
};

export default useLoadGoogle;
9 changes: 9 additions & 0 deletions apps/sso/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,12 @@ declare module '*.svg' {
export const ReactComponent: any;
export default content;
}


export { };

declare global {
interface Window {
handleSignInWithGoogle: (response: any) => void;
}
}
15 changes: 15 additions & 0 deletions apps/sso/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,27 @@ import './styles.css';
import Head from 'next/head';
import { GlobalStyles2023 } from '@hibiscus/styles';
import { SupabaseContextProvider } from '@hibiscus/hibiscus-supabase-context';
import { useHibiscusSupabase } from '@hibiscus/hibiscus-supabase-context';

function handleSignInWithGoogle(response) {
console.log('HEREREREREER');
}

function CustomApp({ Component, pageProps }: AppProps) {
const { supabase } = useHibiscusSupabase();

// async function handleSignInWithGoogle(response) {
// console.log('HEREREREREER');
// const { data, error } = await supabase.getClient().auth.signInWithIdToken({
// provider: 'google',
// token: response.credential,
// });
// }
return (
<>
<Head>
<link rel="shortcut icon" href="/static/favicon.ico" />
<script src="https://accounts.google.com/gsi/client" async />
</Head>
<main className="app">
<GlobalStyles2023 />
Expand Down
30 changes: 30 additions & 0 deletions apps/sso/pages/api/googleSignUp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { HibiscusSupabaseClient } from '@hibiscus/hibiscus-supabase-client';
import { NextApiHandler } from 'next';
import { container } from 'tsyringe';

const handler: NextApiHandler = async (req, res) => {
if (req.method === 'POST') {
try {
const supabase = container.resolve(HibiscusSupabaseClient);
supabase.setOptions({ useServiceKey: true });
const { email, first_name, last_name, user_id } = JSON.parse(req.body);
console.log(req.body);
console.log(req.body['email']);
console.log(email, first_name, last_name);
const { data, error } = await supabase.getClient().from('user_profiles').insert([
{
user_id,
email,
first_name,
last_name,
},
]);
console.log(data, error);
res.status(200).json({ data, error });
} catch (error) {
res.status(500).json({ error });
}
}
};

export default handler;
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@
"@sendgrid/mail": "^7.7.0",
"@sentry/browser": "^7.34.0",
"@sentry/nextjs": "^7.34.0",
"@supabase/auth-helpers-nextjs": "^0.5.2",
"@supabase/supabase-js": "^2.2.0",
"@supabase/auth-helpers-nextjs": "^0.10.0",
"@supabase/supabase-js": "^2.45.0",
"@vanilla-extract/css": "^1.13.0",
"@vanilla-extract/dynamic": "^2.0.3",
"@vanilla-extract/recipes": "^0.5.0",
"@vercel/edge-config": "^0.1.1",
"airplane": "^0.2.30",
"airplane": "^0.2.85",
"aws-serverless-express": "^3.4.0",
"axios": "^1.5.1",
"classnames": "^2.3.2",
Expand Down
Loading
Loading