done for the day

This commit is contained in:
Gabriel Brown 2025-05-30 16:50:18 -05:00
parent 8303f287d9
commit 7238403f39
11 changed files with 346 additions and 285 deletions

View File

@ -2,76 +2,32 @@
import 'server-only'; import 'server-only';
import { createServerClient } from '@/utils/supabase'; import { createServerClient } from '@/utils/supabase';
import { NextResponse } from 'next/server'; import { type EmailOtpType } from '@supabase/supabase-js';
import { type NextRequest } from 'next/server';
import { redirect } from 'next/navigation';
export const GET = async (request: Request) => { export const GET = async (request: NextRequest) => {
const requestUrl = new URL(request.url); const { searchParams } = new URL(request.url);
const code = requestUrl.searchParams.get('code'); const token_hash = searchParams.get('token');
const token = requestUrl.searchParams.get('token'); const type = searchParams.get('type') as EmailOtpType | null;
const type = requestUrl.searchParams.get('type'); const redirectTo = searchParams.get('redirect_to') ?? '/';
const origin = requestUrl.origin;
const redirectTo = requestUrl.searchParams.get('redirect_to')?.toString();
if (token_hash && type) {
const supabase = await createServerClient(); const supabase = await createServerClient();
if (token && type) {
try {
if (type === 'signup') {
// Confirm email signup
const { error } = await supabase.auth.verifyOtp({ const { error } = await supabase.auth.verifyOtp({
token_hash: token, type,
type: 'signup', token_hash,
}); });
if (!error) {
if (error) { if (type === 'signup' || type === 'magiclink' || type === 'email')
console.error('Email confirmation error:', error); return redirect('/');
return NextResponse.redirect(`${origin}/sign-in?error=Invalid or expired confirmation link`); if (type === 'recovery' || type === 'email_change')
return redirect('/profile');
if (type === 'invite')
return redirect('/sign-up');
else return redirect(`/?Could not identify type ${type as string}`)
} }
} else if (type === 'recovery') { else return redirect(`/?${error.message}`);
// Handle password recovery
const { error } = await supabase.auth.verifyOtp({
token_hash: token,
type: 'recovery',
});
if (error) {
console.error('Password recovery error:', error);
return NextResponse.redirect(`${origin}/sign-in?error=Invalid or expired reset link`);
} else {
return NextResponse.redirect(`${origin}/reset-password`);
} }
} else if (type === 'email_change') { return redirect('/');
// Handle email change };
const { error } = await supabase.auth.verifyOtp({
token_hash: token,
type: 'email_change',
});
if (error) {
console.error('Email change error:', error);
return NextResponse.redirect(`${origin}/profile?error=Invalid or expired email change link`);
}
}
} catch (error) {
console.error('Verification error:', error);
return NextResponse.redirect(`${origin}/sign-in?error=Verification failed`);
}
}
// Handle code-based flow (OAuth, etc.)
if (code) {
await supabase.auth.exchangeCodeForSession(code);
}
// Handle redirect
if (redirectTo) {
try {
new URL(redirectTo);
return NextResponse.redirect(redirectTo);
} catch {
return NextResponse.redirect(`${origin}${redirectTo}`);
}
}
return NextResponse.redirect(origin);
}

View File

@ -1,24 +1,77 @@
'use server';
import 'server-only';
import { createServerClient } from '@/utils/supabase'; import { createServerClient } from '@/utils/supabase';
import { NextResponse } from 'next/server'; import { type EmailOtpType } from '@supabase/supabase-js';
import { type NextRequest, NextResponse } from 'next/server';
export const GET = async (request: Request) => { export const GET = async (request: NextRequest) => {
// The `/auth/callback` route is required for the server-side auth flow implemented const { searchParams, origin } = new URL(request.url);
// by the SSR package. It exchanges an auth code for the user's session. const code = searchParams.get('code');
// https://supabase.com/docs/guides/auth/server-side/nextjs const token = searchParams.get('token');
const requestUrl = new URL(request.url); const type = searchParams.get('type') as EmailOtpType | null;
const code = requestUrl.searchParams.get('code'); const redirectTo = searchParams.get('redirect_to')?.toString();
const origin = requestUrl.origin;
const redirectTo = requestUrl.searchParams.get('redirect_to')?.toString();
if (code) {
const supabase = await createServerClient(); const supabase = await createServerClient();
if (token && type) {
try {
if (type === 'signup') {
// Confirm email signup
const { error } = await supabase.auth.verifyOtp({
token_hash: token,
type: 'signup',
});
if (error) {
console.error('Email confirmation error:', error);
return NextResponse.redirect(`${origin}/sign-in?error=Invalid or expired confirmation link`);
}
} else if (type === 'recovery') {
// Handle password recovery
const { error } = await supabase.auth.verifyOtp({
token_hash: token,
type: 'recovery',
});
if (error) {
console.error('Password recovery error:', error);
return NextResponse.redirect(`${origin}/sign-in?error=Invalid or expired reset link`);
} else {
return NextResponse.redirect(`${origin}/reset-password`);
}
} else if (type === 'email_change') {
// Handle email change
const { error } = await supabase.auth.verifyOtp({
token_hash: token,
type: 'email_change',
});
if (error) {
console.error('Email change error:', error);
return NextResponse.redirect(`${origin}/profile?error=Invalid or expired email change link`);
}
}
} catch (error) {
console.error('Verification error:', error);
return NextResponse.redirect(`${origin}/sign-in?error=Verification failed`);
}
}
// Handle code-based flow (OAuth, etc.)
if (code) {
await supabase.auth.exchangeCodeForSession(code); await supabase.auth.exchangeCodeForSession(code);
} }
// Handle redirect
if (redirectTo) { if (redirectTo) {
try {
new URL(redirectTo);
return NextResponse.redirect(redirectTo);
} catch {
return NextResponse.redirect(`${origin}${redirectTo}`); return NextResponse.redirect(`${origin}${redirectTo}`);
} }
}
// URL to redirect to after sign up process completes
return NextResponse.redirect(origin); return NextResponse.redirect(origin);
} }

View File

@ -1,8 +0,0 @@
const Layout = async ({ children }: { children: React.ReactNode }) => {
return (
<div className='max-w-7xl flex flex-col gap-12 items-center'>
{children}
</div>
);
};
export default Layout;

View File

@ -5,7 +5,6 @@ import { useEffect } from 'react';
import { AvatarUpload, ProfileForm, ResetPasswordForm } from '@/components/default/profile'; import { AvatarUpload, ProfileForm, ResetPasswordForm } from '@/components/default/profile';
import { import {
Card, Card,
CardContent,
CardHeader, CardHeader,
CardTitle, CardTitle,
CardDescription, CardDescription,
@ -14,6 +13,7 @@ import {
import { Loader2 } from 'lucide-react'; import { Loader2 } from 'lucide-react';
import { resetPassword } from '@/lib/actions'; import { resetPassword } from '@/lib/actions';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { type Result } from '@/lib/actions';
const ProfilePage = () => { const ProfilePage = () => {
const { profile, isLoading, isAuthenticated, updateProfile, refreshUserData } = useAuth(); const { profile, isLoading, isAuthenticated, updateProfile, refreshUserData } = useAuth();
@ -44,19 +44,21 @@ const ProfilePage = () => {
} }
}; };
const handleResetPasswordSubmit = async (values: { const handleResetPasswordSubmit = async (
password: string; formData: FormData,
confirmPassword: string; ): Promise<Result<null>> => {
}) => {
try { try {
const result = await resetPassword(values); const result = await resetPassword(formData);
if (!result.success) { if (!result.success) {
toast.error(`Error resetting password: ${result.error}`) toast.error(`Error resetting password: ${result.error}`)
return {success: false, error: result.error};
} }
return {success: true, data: null};
} catch (error) { } catch (error) {
toast.error( toast.error(
`Error resetting password!: ${error as string ?? 'Unknown error'}` `Error resetting password!: ${error as string ?? 'Unknown error'}`
); );
return {success: false, error: 'Unknown error'};
} }
} }
@ -87,7 +89,6 @@ const ProfilePage = () => {
Manage your personal information and how it appears to others Manage your personal information and how it appears to others
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent>
{isLoading && !profile ? ( {isLoading && !profile ? (
<div className='flex justify-center py-8'> <div className='flex justify-center py-8'>
<Loader2 className='h-8 w-8 animate-spin text-gray-500' /> <Loader2 className='h-8 w-8 animate-spin text-gray-500' />
@ -101,7 +102,6 @@ const ProfilePage = () => {
<ResetPasswordForm onSubmit={handleResetPasswordSubmit} /> <ResetPasswordForm onSubmit={handleResetPasswordSubmit} />
</div> </div>
)} )}
</CardContent>
</Card> </Card>
</div> </div>
); );

View File

@ -1,38 +0,0 @@
import { resetPasswordFromEmail } from '@/lib/actions';
import { FormMessage, type Message, SubmitButton } from '@/components/default';
import { Input, Label } from '@/components/ui';
import { getUser } from '@/lib/actions';
import { redirect } from 'next/navigation';
const ResetPassword = async (props: { searchParams: Promise<Message> }) => {
const user = await getUser();
if (!user.success) {
redirect('/sign-in');
}
const searchParams = await props.searchParams;
return (
<form className='flex flex-col w-full max-w-md p-4 gap-2 [&>input]:mb-4'>
<h1 className='text-2xl font-medium'>Reset password</h1>
<p className='text-sm text-foreground/60'>
Please enter your new password below.
</p>
<Label htmlFor='password'>New password</Label>
<Input
type='password'
name='password'
placeholder='New password'
required
/>
<Label htmlFor='confirmPassword'>Confirm password</Label>
<Input
type='password'
name='confirmPassword'
placeholder='Confirm password'
required
/>
<SubmitButton formAction={resetPasswordFromEmail}>Reset password</SubmitButton>
<FormMessage message={searchParams} />
</form>
);
};
export default ResetPassword;

View File

@ -1,15 +1,53 @@
'use client'; 'use client';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import {
Button,
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
Input,
Label,
} from '@/components/ui';
import Link from 'next/link'; import Link from 'next/link';
import { signIn } from '@/lib/actions'; import { signIn } from '@/lib/actions';
import { SubmitButton } from '@/components/default'; import { SubmitButton } from '@/components/default';
import { Input, Label } from '@/components/ui';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { useAuth } from '@/components/context/auth'; import { useAuth } from '@/components/context/auth';
import { useEffect } from 'react'; import { useEffect, useState } from 'react';
const formSchema = z.object({
email: z.string().email({
message: 'Please enter a valid email address.',
}),
password: z.string().min(8, {
message: 'Password must be at least 8 characters.',
}),
})
const Login = () => { const Login = () => {
const router = useRouter(); const router = useRouter();
const { isAuthenticated, refreshUserData } = useAuth(); const { isAuthenticated, isLoading, refreshUserData } = useAuth();
const [statusMessage, setStatusMessage] = useState('');
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
email: '',
password: '',
},
});
// Redirect if already authenticated // Redirect if already authenticated
useEffect(() => { useEffect(() => {
@ -18,46 +56,102 @@ const Login = () => {
} }
}, [isAuthenticated, router]); }, [isAuthenticated, router]);
const handleSignIn = async (formData: FormData) => { const handleSignIn = async (values: z.infer<typeof formSchema>) => {
try {
const formData = new FormData();
formData.append('email', values.email);
formData.append('password', values.password);
const result = await signIn(formData); const result = await signIn(formData);
if (result?.success) { if (result?.success) {
await refreshUserData(); await refreshUserData();
router.push('/'); form.reset();
router.push('');
} else {
setStatusMessage(`Error: ${result.error}`)
}
} catch (error) {
setStatusMessage(
`Error: ${error instanceof Error ? error.message : 'Could not sign in!'}`
);
} }
}; };
return ( return (
<form className='flex-1 flex flex-col min-w-64'> <Card>
<h1 className='text-2xl font-medium'>Sign in</h1> <CardHeader>
<p className='text-sm text-foreground'> <CardTitle className='text-2xl font-medium'>
Sign In
</CardTitle>
<CardDescription className='text-sm text-foreground'>
Don&apos;t have an account?{' '} Don&apos;t have an account?{' '}
<Link className='text-foreground font-medium underline' href='/sign-up'> <Link className='font-medium underline' href='/sign-up'>
Sign up Sign up
</Link> </Link>
</p> </CardDescription>
<div className='flex flex-col gap-2 [&>input]:mb-3 mt-8'> </CardHeader>
<Label htmlFor='email'>Email</Label> <CardContent>
<Input name='email' placeholder='you@example.com' required /> <Form {...form}>
<div className='flex justify-between items-center'> <form
<Label htmlFor='password'>Password</Label> onSubmit={form.handleSubmit(handleSignIn)}
className='flex flex-col min-w-64 space-y-6'
>
<FormField
control={form.control}
name='email'
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input type='email' placeholder='you@example.com' {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name='password'
render={({ field }) => (
<FormItem>
<div className='flex justify-between'>
<FormLabel>Password</FormLabel>
<Link <Link
className='text-xs text-foreground underline' className='text-xs text-foreground underline text-right'
href='/forgot-password' href='/forgot-password'
> >
Forgot Password? Forgot Password?
</Link> </Link>
</div> </div>
<Input <FormControl>
type='password' <Input type='password' placeholder='Your password' {...field} />
name='password' </FormControl>
placeholder='Your password' <FormMessage />
required </FormItem>
)}
/> />
<SubmitButton pendingText='Signing In...' formAction={handleSignIn}> {statusMessage && (
<div
className={`text-sm text-center ${
statusMessage.includes('Error') || statusMessage.includes('failed')
? 'text-destructive'
: 'text-green-800'
}`}
>
{statusMessage}
</div>
)}
<SubmitButton
disabled={isLoading}
pendingText='Signing In...'
>
Sign in Sign in
</SubmitButton> </SubmitButton>
</div>
</form> </form>
</Form>
</CardContent>
</Card>
); );
}; };

View File

@ -1,6 +1,6 @@
import { useFileUpload } from '@/lib/hooks/useFileUpload'; import { useFileUpload } from '@/lib/hooks/useFileUpload';
import { useAuth } from '@/components/context/auth'; import { useAuth } from '@/components/context/auth';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui'; import { Avatar, AvatarFallback, AvatarImage, CardContent } from '@/components/ui';
import { Loader2, Pencil, Upload, User } from 'lucide-react'; import { Loader2, Pencil, Upload, User } from 'lucide-react';
type AvatarUploadProps = { type AvatarUploadProps = {
@ -43,6 +43,8 @@ export const AvatarUpload = ({ onAvatarUploaded }: AvatarUploadProps) => {
}; };
return ( return (
<CardContent>
<div className='flex flex-col items-center'> <div className='flex flex-col items-center'>
<div <div
className='relative group cursor-pointer mb-4' className='relative group cursor-pointer mb-4'
@ -92,5 +94,6 @@ export const AvatarUpload = ({ onAvatarUploaded }: AvatarUploadProps) => {
</div> </div>
)} )}
</div> </div>
</CardContent>
); );
}; };

View File

@ -3,6 +3,7 @@ import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import { import {
Button, Button,
CardContent,
Form, Form,
FormControl, FormControl,
FormDescription, FormDescription,
@ -53,6 +54,7 @@ export const ProfileForm = ({onSubmit}: ProfileFormProps) => {
}; };
return ( return (
<CardContent>
<Form {...form}> <Form {...form}>
<form onSubmit={form.handleSubmit(handleSubmit)} className='space-y-6'> <form onSubmit={form.handleSubmit(handleSubmit)} className='space-y-6'>
<FormField <FormField
@ -101,5 +103,6 @@ export const ProfileForm = ({onSubmit}: ProfileFormProps) => {
</div> </div>
</form> </form>
</Form> </Form>
</CardContent>
); );
} }

View File

@ -2,7 +2,7 @@ import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod'; import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import { import {
Button, CardContent,
CardDescription, CardDescription,
CardHeader, CardHeader,
CardTitle, CardTitle,
@ -15,8 +15,10 @@ import {
FormMessage, FormMessage,
Input, Input,
} from '@/components/ui'; } from '@/components/ui';
import { Loader2 } from 'lucide-react'; import { SubmitButton } from '@/components/default';
import { useState } from 'react'; import { useState } from 'react';
import { type Result } from '@/lib/actions';
import { FormMessage as Pw } from '@/components/default';
const formSchema = z const formSchema = z
.object({ .object({
@ -31,7 +33,7 @@ const formSchema = z
}); });
type ResetPasswordFormProps = { type ResetPasswordFormProps = {
onSubmit: (values: z.infer<typeof formSchema>) => Promise<void>; onSubmit: (formData: FormData) => Promise<Result<null>>;
message?: string; message?: string;
}; };
@ -50,14 +52,25 @@ export const ResetPasswordForm = ({
}, },
}); });
const handleSubmit = async (values: z.infer<typeof formSchema>) => { const handleUpdatePassword = async (values: z.infer<typeof formSchema>) => {
setIsLoading(true); setIsLoading(true);
try { try {
await onSubmit(values); // Convert form values to FormData for your server action
setStatusMessage('Password updated successfully'); const formData = new FormData();
form.reset(); formData.append('password', values.password);
formData.append('confirmPassword', values.confirmPassword);
const result = await onSubmit(formData);
if (result?.success) {
setStatusMessage('Password updated successfully!');
form.reset(); // Clear the form on success
} else {
setStatusMessage('Error: Unable to update password!');
}
} catch (error) { } catch (error) {
setStatusMessage(error instanceof Error ? error.message : 'An error occurred'); setStatusMessage(
error instanceof Error ? error.message : 'Password was not updated!'
);
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
@ -66,14 +79,18 @@ export const ResetPasswordForm = ({
return ( return (
<div> <div>
<CardHeader className='pb-5'> <CardHeader className='pb-5'>
<CardTitle className='text-xl'>Change Password</CardTitle> <CardTitle className='text-2xl'>Change Password</CardTitle>
<CardDescription> <CardDescription>
Update your password to keep your account secure Update your password to keep your account secure
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent>
<Form {...form}> <Form {...form}>
<form onSubmit={form.handleSubmit(handleSubmit)} className='space-y-6'> <form
onSubmit={form.handleSubmit(handleUpdatePassword)}
className='space-y-6'
>
<FormField <FormField
control={form.control} control={form.control}
name='password' name='password'
@ -107,24 +124,27 @@ export const ResetPasswordForm = ({
)} )}
/> />
{statusMessage && ( {statusMessage && (
<div className={`text-sm text-center ${statusMessage.includes('error') || statusMessage.includes('failed') ? 'text-destructive' : 'text-green-600'}`}> <div
className={`text-sm text-center ${
statusMessage.includes('Error') || statusMessage.includes('failed')
? 'text-destructive'
: 'text-green-600'
}`}
>
{statusMessage} {statusMessage}
</div> </div>
)} )}
<div className='flex justify-center'> <div className='flex justify-center'>
<Button type='submit' disabled={isLoading}> <SubmitButton
{isLoading ? ( disabled={isLoading}
<> pendingText='Updating Password...'
<Loader2 className='mr-2 h-4 w-4 animate-spin' /> >
Updating Password... Update Password
</> </SubmitButton>
) : (
'Update Password'
)}
</Button>
</div> </div>
</form> </form>
</Form> </Form>
</CardContent>
</div> </div>
); );
}; };

View File

@ -3,21 +3,31 @@
import { Button } from '@/components/ui'; import { Button } from '@/components/ui';
import { type ComponentProps } from 'react'; import { type ComponentProps } from 'react';
import { useFormStatus } from 'react-dom'; import { useFormStatus } from 'react-dom';
import { Loader2 } from 'lucide-react';
type Props = ComponentProps<typeof Button> & { type Props = ComponentProps<typeof Button> & {
disabled?: boolean;
pendingText?: string; pendingText?: string;
}; };
export const SubmitButton = ({ export const SubmitButton = ({
children, children,
disabled = false,
pendingText = 'Submitting...', pendingText = 'Submitting...',
...props ...props
}: Props) => { }: Props) => {
const { pending } = useFormStatus(); const { pending } = useFormStatus();
return ( return (
<Button type='submit' aria-disabled={pending} {...props}> <Button type='submit' aria-disabled={pending} disabled={disabled} {...props}>
{pending ? pendingText : children} {pending || disabled ? (
<>
<Loader2 className='mr-2 h-4 w-4 animate-spin' />
{pendingText}
</>
) : (
children
)}
</Button> </Button>
); );
}; };

View File

@ -98,13 +98,9 @@ export const forgotPassword = async (formData: FormData) => {
}; };
export const resetPassword = async ({ export const resetPassword = async (formData: FormData): Promise<Result<null>> => {
password, const password = formData.get('password') as string;
confirmPassword, const confirmPassword = formData.get('confirmPassword') as string;
}: {
password: string,
confirmPassword: string
}): Promise<Result<null>> => {
if (!password || !confirmPassword) { if (!password || !confirmPassword) {
return { success: false, error: 'Password and confirm password are required!' }; return { success: false, error: 'Password and confirm password are required!' };
} }
@ -121,34 +117,6 @@ export const resetPassword = async ({
return { success: true, data: null }; return { success: true, data: null };
}; };
export const resetPasswordFromEmail = async (formData: FormData) => {
const password = formData.get('password') as string;
const confirmPassword = formData.get('confirmPassword') as string;
if (!password || !confirmPassword) {
encodedRedirect(
'error',
'/reset-password',
'Password and confirm password are required',
);
}
const supabase = await createServerClient();
if (password !== confirmPassword) {
encodedRedirect('error', '/reset-password', 'Passwords do not match');
}
const { error } = await supabase.auth.updateUser({
password: password,
});
if (error) {
encodedRedirect('error', '/reset-password', 'Password update failed');
}
encodedRedirect('success', '/reset-password', 'Password updated');
};
export const signOut = async (): Promise<Result<null>> => { export const signOut = async (): Promise<Result<null>> => {
const supabase = await createServerClient(); const supabase = await createServerClient();
const { error } = await supabase.auth.signOut(); const { error } = await supabase.auth.signOut();