done for the day
This commit is contained in:
parent
8303f287d9
commit
7238403f39
@ -2,76 +2,32 @@
|
||||
|
||||
import 'server-only';
|
||||
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) => {
|
||||
const requestUrl = new URL(request.url);
|
||||
const code = requestUrl.searchParams.get('code');
|
||||
const token = requestUrl.searchParams.get('token');
|
||||
const type = requestUrl.searchParams.get('type');
|
||||
const origin = requestUrl.origin;
|
||||
const redirectTo = requestUrl.searchParams.get('redirect_to')?.toString();
|
||||
export const GET = async (request: NextRequest) => {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const token_hash = searchParams.get('token');
|
||||
const type = searchParams.get('type') as EmailOtpType | null;
|
||||
const redirectTo = searchParams.get('redirect_to') ?? '/';
|
||||
|
||||
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`);
|
||||
if (token_hash && type) {
|
||||
const supabase = await createServerClient();
|
||||
const { error } = await supabase.auth.verifyOtp({
|
||||
type,
|
||||
token_hash,
|
||||
});
|
||||
if (!error) {
|
||||
if (type === 'signup' || type === 'magiclink' || type === 'email')
|
||||
return redirect('/');
|
||||
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 return redirect(`/?${error.message}`);
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
return redirect('/');
|
||||
};
|
||||
|
@ -1,24 +1,77 @@
|
||||
'use server';
|
||||
|
||||
import 'server-only';
|
||||
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) => {
|
||||
// The `/auth/callback` route is required for the server-side auth flow implemented
|
||||
// by the SSR package. It exchanges an auth code for the user's session.
|
||||
// https://supabase.com/docs/guides/auth/server-side/nextjs
|
||||
const requestUrl = new URL(request.url);
|
||||
const code = requestUrl.searchParams.get('code');
|
||||
const origin = requestUrl.origin;
|
||||
const redirectTo = requestUrl.searchParams.get('redirect_to')?.toString();
|
||||
export const GET = async (request: NextRequest) => {
|
||||
const { searchParams, origin } = new URL(request.url);
|
||||
const code = searchParams.get('code');
|
||||
const token = searchParams.get('token');
|
||||
const type = searchParams.get('type') as EmailOtpType | null;
|
||||
const redirectTo = searchParams.get('redirect_to')?.toString();
|
||||
|
||||
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) {
|
||||
const supabase = await createServerClient();
|
||||
await supabase.auth.exchangeCodeForSession(code);
|
||||
}
|
||||
|
||||
// Handle redirect
|
||||
if (redirectTo) {
|
||||
return NextResponse.redirect(`${origin}${redirectTo}`);
|
||||
try {
|
||||
new URL(redirectTo);
|
||||
return NextResponse.redirect(redirectTo);
|
||||
} catch {
|
||||
return NextResponse.redirect(`${origin}${redirectTo}`);
|
||||
}
|
||||
}
|
||||
|
||||
// URL to redirect to after sign up process completes
|
||||
return NextResponse.redirect(origin);
|
||||
}
|
||||
|
@ -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;
|
@ -5,7 +5,6 @@ import { useEffect } from 'react';
|
||||
import { AvatarUpload, ProfileForm, ResetPasswordForm } from '@/components/default/profile';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
CardDescription,
|
||||
@ -14,6 +13,7 @@ import {
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { resetPassword } from '@/lib/actions';
|
||||
import { toast } from 'sonner';
|
||||
import { type Result } from '@/lib/actions';
|
||||
|
||||
const ProfilePage = () => {
|
||||
const { profile, isLoading, isAuthenticated, updateProfile, refreshUserData } = useAuth();
|
||||
@ -44,19 +44,21 @@ const ProfilePage = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleResetPasswordSubmit = async (values: {
|
||||
password: string;
|
||||
confirmPassword: string;
|
||||
}) => {
|
||||
const handleResetPasswordSubmit = async (
|
||||
formData: FormData,
|
||||
): Promise<Result<null>> => {
|
||||
try {
|
||||
const result = await resetPassword(values);
|
||||
const result = await resetPassword(formData);
|
||||
if (!result.success) {
|
||||
toast.error(`Error resetting password: ${result.error}`)
|
||||
return {success: false, error: result.error};
|
||||
}
|
||||
return {success: true, data: null};
|
||||
} catch (error) {
|
||||
toast.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
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading && !profile ? (
|
||||
<div className='flex justify-center py-8'>
|
||||
<Loader2 className='h-8 w-8 animate-spin text-gray-500' />
|
||||
@ -101,7 +102,6 @@ const ProfilePage = () => {
|
||||
<ResetPasswordForm onSubmit={handleResetPasswordSubmit} />
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
|
@ -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;
|
@ -1,15 +1,53 @@
|
||||
'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 { signIn } from '@/lib/actions';
|
||||
import { SubmitButton } from '@/components/default';
|
||||
import { Input, Label } from '@/components/ui';
|
||||
import { useRouter } from 'next/navigation';
|
||||
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 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
|
||||
useEffect(() => {
|
||||
@ -18,46 +56,102 @@ const Login = () => {
|
||||
}
|
||||
}, [isAuthenticated, router]);
|
||||
|
||||
const handleSignIn = async (formData: FormData) => {
|
||||
const result = await signIn(formData);
|
||||
if (result?.success) {
|
||||
await refreshUserData();
|
||||
router.push('/');
|
||||
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);
|
||||
if (result?.success) {
|
||||
await refreshUserData();
|
||||
form.reset();
|
||||
router.push('');
|
||||
} else {
|
||||
setStatusMessage(`Error: ${result.error}`)
|
||||
}
|
||||
} catch (error) {
|
||||
setStatusMessage(
|
||||
`Error: ${error instanceof Error ? error.message : 'Could not sign in!'}`
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form className='flex-1 flex flex-col min-w-64'>
|
||||
<h1 className='text-2xl font-medium'>Sign in</h1>
|
||||
<p className='text-sm text-foreground'>
|
||||
Don't have an account?{' '}
|
||||
<Link className='text-foreground font-medium underline' href='/sign-up'>
|
||||
Sign up
|
||||
</Link>
|
||||
</p>
|
||||
<div className='flex flex-col gap-2 [&>input]:mb-3 mt-8'>
|
||||
<Label htmlFor='email'>Email</Label>
|
||||
<Input name='email' placeholder='you@example.com' required />
|
||||
<div className='flex justify-between items-center'>
|
||||
<Label htmlFor='password'>Password</Label>
|
||||
<Link
|
||||
className='text-xs text-foreground underline'
|
||||
href='/forgot-password'
|
||||
>
|
||||
Forgot Password?
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className='text-2xl font-medium'>
|
||||
Sign In
|
||||
</CardTitle>
|
||||
<CardDescription className='text-sm text-foreground'>
|
||||
Don't have an account?{' '}
|
||||
<Link className='font-medium underline' href='/sign-up'>
|
||||
Sign up
|
||||
</Link>
|
||||
</div>
|
||||
<Input
|
||||
type='password'
|
||||
name='password'
|
||||
placeholder='Your password'
|
||||
required
|
||||
/>
|
||||
<SubmitButton pendingText='Signing In...' formAction={handleSignIn}>
|
||||
Sign in
|
||||
</SubmitButton>
|
||||
</div>
|
||||
</form>
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Form {...form}>
|
||||
<form
|
||||
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
|
||||
className='text-xs text-foreground underline text-right'
|
||||
href='/forgot-password'
|
||||
>
|
||||
Forgot Password?
|
||||
</Link>
|
||||
</div>
|
||||
<FormControl>
|
||||
<Input type='password' placeholder='Your password' {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{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
|
||||
</SubmitButton>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
import { useFileUpload } from '@/lib/hooks/useFileUpload';
|
||||
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';
|
||||
|
||||
type AvatarUploadProps = {
|
||||
@ -43,6 +43,8 @@ export const AvatarUpload = ({ onAvatarUploaded }: AvatarUploadProps) => {
|
||||
};
|
||||
|
||||
return (
|
||||
<CardContent>
|
||||
|
||||
<div className='flex flex-col items-center'>
|
||||
<div
|
||||
className='relative group cursor-pointer mb-4'
|
||||
@ -92,5 +94,6 @@ export const AvatarUpload = ({ onAvatarUploaded }: AvatarUploadProps) => {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
);
|
||||
};
|
||||
|
@ -3,6 +3,7 @@ import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import {
|
||||
Button,
|
||||
CardContent,
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
@ -53,53 +54,55 @@ export const ProfileForm = ({onSubmit}: ProfileFormProps) => {
|
||||
};
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(handleSubmit)} className='space-y-6'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='full_name'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Full Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>Your public display name.</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='email'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Email</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Your email address associated with your account.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className='flex justify-center'>
|
||||
<Button type='submit' disabled={isLoading}>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className='mr-2 h-4 w-4 animate-spin' />
|
||||
Saving...
|
||||
</>
|
||||
) : (
|
||||
'Save Changes'
|
||||
<CardContent>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(handleSubmit)} className='space-y-6'>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='full_name'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Full Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>Your public display name.</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='email'
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Email</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Your email address associated with your account.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className='flex justify-center'>
|
||||
<Button type='submit' disabled={isLoading}>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className='mr-2 h-4 w-4 animate-spin' />
|
||||
Saving...
|
||||
</>
|
||||
) : (
|
||||
'Save Changes'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</CardContent>
|
||||
);
|
||||
}
|
||||
|
@ -2,7 +2,7 @@ import { z } from 'zod';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import {
|
||||
Button,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
@ -15,8 +15,10 @@ import {
|
||||
FormMessage,
|
||||
Input,
|
||||
} from '@/components/ui';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { SubmitButton } from '@/components/default';
|
||||
import { useState } from 'react';
|
||||
import { type Result } from '@/lib/actions';
|
||||
import { FormMessage as Pw } from '@/components/default';
|
||||
|
||||
const formSchema = z
|
||||
.object({
|
||||
@ -31,7 +33,7 @@ const formSchema = z
|
||||
});
|
||||
|
||||
type ResetPasswordFormProps = {
|
||||
onSubmit: (values: z.infer<typeof formSchema>) => Promise<void>;
|
||||
onSubmit: (formData: FormData) => Promise<Result<null>>;
|
||||
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);
|
||||
try {
|
||||
await onSubmit(values);
|
||||
setStatusMessage('Password updated successfully');
|
||||
form.reset();
|
||||
// Convert form values to FormData for your server action
|
||||
const formData = new FormData();
|
||||
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) {
|
||||
setStatusMessage(error instanceof Error ? error.message : 'An error occurred');
|
||||
setStatusMessage(
|
||||
error instanceof Error ? error.message : 'Password was not updated!'
|
||||
);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@ -65,15 +78,19 @@ export const ResetPasswordForm = ({
|
||||
|
||||
return (
|
||||
<div>
|
||||
<CardHeader className='pb-5'>
|
||||
<CardTitle className='text-xl'>Change Password</CardTitle>
|
||||
<CardDescription>
|
||||
Update your password to keep your account secure
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
<CardHeader className='pb-5'>
|
||||
<CardTitle className='text-2xl'>Change Password</CardTitle>
|
||||
<CardDescription>
|
||||
Update your password to keep your account secure
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(handleSubmit)} className='space-y-6'>
|
||||
<form
|
||||
onSubmit={form.handleSubmit(handleUpdatePassword)}
|
||||
className='space-y-6'
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name='password'
|
||||
@ -107,24 +124,27 @@ export const ResetPasswordForm = ({
|
||||
)}
|
||||
/>
|
||||
{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}
|
||||
</div>
|
||||
)}
|
||||
<div className='flex justify-center'>
|
||||
<Button type='submit' disabled={isLoading}>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className='mr-2 h-4 w-4 animate-spin' />
|
||||
Updating Password...
|
||||
</>
|
||||
) : (
|
||||
'Update Password'
|
||||
)}
|
||||
</Button>
|
||||
<SubmitButton
|
||||
disabled={isLoading}
|
||||
pendingText='Updating Password...'
|
||||
>
|
||||
Update Password
|
||||
</SubmitButton>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</CardContent>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
@ -3,21 +3,31 @@
|
||||
import { Button } from '@/components/ui';
|
||||
import { type ComponentProps } from 'react';
|
||||
import { useFormStatus } from 'react-dom';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
type Props = ComponentProps<typeof Button> & {
|
||||
disabled?: boolean;
|
||||
pendingText?: string;
|
||||
};
|
||||
|
||||
export const SubmitButton = ({
|
||||
children,
|
||||
disabled = false,
|
||||
pendingText = 'Submitting...',
|
||||
...props
|
||||
}: Props) => {
|
||||
const { pending } = useFormStatus();
|
||||
|
||||
return (
|
||||
<Button type='submit' aria-disabled={pending} {...props}>
|
||||
{pending ? pendingText : children}
|
||||
<Button type='submit' aria-disabled={pending} disabled={disabled} {...props}>
|
||||
{pending || disabled ? (
|
||||
<>
|
||||
<Loader2 className='mr-2 h-4 w-4 animate-spin' />
|
||||
{pendingText}
|
||||
</>
|
||||
) : (
|
||||
children
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
@ -98,13 +98,9 @@ export const forgotPassword = async (formData: FormData) => {
|
||||
};
|
||||
|
||||
|
||||
export const resetPassword = async ({
|
||||
password,
|
||||
confirmPassword,
|
||||
}: {
|
||||
password: string,
|
||||
confirmPassword: string
|
||||
}): Promise<Result<null>> => {
|
||||
export const resetPassword = async (formData: FormData): Promise<Result<null>> => {
|
||||
const password = formData.get('password') as string;
|
||||
const confirmPassword = formData.get('confirmPassword') as string;
|
||||
if (!password || !confirmPassword) {
|
||||
return { success: false, error: 'Password and confirm password are required!' };
|
||||
}
|
||||
@ -121,34 +117,6 @@ export const resetPassword = async ({
|
||||
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>> => {
|
||||
const supabase = await createServerClient();
|
||||
const { error } = await supabase.auth.signOut();
|
||||
|
Loading…
x
Reference in New Issue
Block a user