Skip to content

Commit

Permalink
[feat] add users to volunteer table, check if in volunteer table on s…
Browse files Browse the repository at this point in the history
…ign-in, and refactored signin/signup code into auth.ts
  • Loading branch information
rohin-444 committed Nov 19, 2024
1 parent 72f831e commit e225880
Show file tree
Hide file tree
Showing 3 changed files with 124 additions and 60 deletions.
103 changes: 103 additions & 0 deletions api/supabase/queries/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import supabase from '@/api/supabase/createClient';

export async function handleSignUp(
email: string,
password: string,
): Promise<{ success: boolean; message: string }> {
try {
const { data, error } = await supabase.auth.signUp({ email, password });

if (error) {
return { success: false, message: `Sign-up failed: ${error.message}` };
}

const user = data.user;
if (!user) {
return { success: false, message: 'Sign-up failed: User was not created.' };
}

const { error: insertError } = await supabase
.from('volunteers')
.insert([
{
user_id: user.id,
email,
first_name: '',
last_name: '',
phone_number: '',
notifications_opt_in: true, // default value
},
]);

if (insertError) {
return { success: false, message: `Error storing user data: ${insertError.message}` };
}

return { success: true, message: 'Sign-up successful!' };
} catch (err) {
if (err instanceof Error) {
return { success: false, message: `Sign-up failed: ${err.message}` };
}
return { success: false, message: 'Sign-up failed: An unknown error occurred.' };
}
}

export async function handleSignIn(
email: string,
password: string,
): Promise<{ success: boolean; message: string }> {
try {
const { error: signInError } = await supabase.auth.signInWithPassword({
email,
password,
});

if (signInError) {
return { success: false, message: `Login failed: ${signInError.message}` };
}

const { data: sessionData, error: sessionError } = await supabase.auth.getSession();

if (sessionError || !sessionData?.session) {
return { success: false, message: 'Failed to retrieve session information after login.' };
}

const user_id = sessionData.session.user.id;

const userExists = await checkUserExists(user_id, 'volunteer');

if (!userExists) {
return { success: false, message: 'User not found in volunteers table.' };
}

return { success: true, message: 'Login successful!' };
} catch (err) {
if (err instanceof Error) {
return { success: false, message: `Login failed: ${err.message}` };
}
return { success: false, message: 'Login failed: An unknown error occurred.' };
}
}

export async function checkUserExists(
userId: string,
userType: 'volunteer' | 'facility',
): Promise<boolean> {
try {
const table = userType === 'volunteer' ? 'volunteers' : 'facilities';

const { data, error } = await supabase
.from(table)
.select('user_id')
.eq('user_id', userId)
.single();

if (error || !data) {
return false;
}
return true;
} catch (err) {
console.error('Error checking user existence:', err);
return false;
}
}
42 changes: 11 additions & 31 deletions app/(auth)/signin/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import supabase from '@/api/supabase/createClient';
// import supabase from '@/api/supabase/createClient';
import { H5 } from '@/styles/text';
import { useSession } from '@/utils/AuthProvider';
import { handleSignIn as signInUser } from '@/api/supabase/queries/auth';
import {
Button,
Card,
Expand All @@ -23,7 +23,6 @@ import {

export default function SignIn() {
const router = useRouter();
const sessionHandler = useSession();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [message, setMessage] = useState('');
Expand All @@ -34,34 +33,15 @@ export default function SignIn() {
setMessage('');
setIsError(false);

const { error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) {
setMessage(`Login failed: ${error.message}`);
setIsError(true);
} else {
try {
const { error } = await sessionHandler.signInWithEmail(email, password);
if (error) {
setMessage(`Login failed: ${error.message}`);
setIsError(true);
} else {
setMessage('Login successful!');
setIsError(false);
setTimeout(() => {
router.push('/onboarding/general');
}, 1000);
}
} catch (error) {
if (error instanceof Error) {
setMessage(`Login failed: ${error.message}`);
} else {
setMessage('Login failed: An unknown error occurred');
}
setIsError(true);
}
const { success, message } = await signInUser(email, password);

setMessage(message);
setIsError(!success);

if (success) {
setTimeout(() => {
router.push('/activeEvents');
}, 1000);
}
};

Expand Down
39 changes: 10 additions & 29 deletions app/(auth)/signup/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@

import { useState } from 'react';
import { useRouter } from 'next/navigation';
// import supabase from '@/api/supabase/createClient';
import { H5 } from '@/styles/text';
import { useSession } from '@/utils/AuthProvider';
import { handleSignUp as signUpUser } from '@/api/supabase/queries/auth';
import {
Button,
Card,
Expand All @@ -23,7 +22,6 @@ import {

export default function SignUp() {
const router = useRouter();
const { signUp } = useSession();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmedPassword, setConfirmedPassword] = useState('');
Expand All @@ -40,32 +38,15 @@ export default function SignUp() {
return;
}

try {
const { data, error } = await signUp(email, password);
if (error) {
setMessage(`Sign-up failed: ${error.message}`);
setIsError(true);
} else {
if (data.user?.email_confirmed_at === null) {
setMessage(
'Sign-up successful! Please confirm your email to complete registration.',
);
setIsError(false);
} else {
setMessage('Sign-up successful!');
setIsError(false);
setTimeout(() => {
router.push('/signin');
}, 1500);
}
}
} catch (error) {
if (error instanceof Error) {
setMessage(`Sign-up failed: ${error.message}`);
} else {
setMessage('Sign-up failed: An unknown error occurred');
}
setIsError(true);
const { success, message } = await signUpUser(email, password);

setMessage(message);
setIsError(!success);

if (success) {
setTimeout(() => {
router.push('/signin');
}, 1500);
}
};

Expand Down

0 comments on commit e225880

Please sign in to comment.