feat: add forgot password flow and reusable password field

This commit is contained in:
2026-06-17 16:55:10 +05:30
parent 4c2241ff72
commit b325975282
15 changed files with 541 additions and 44 deletions

View File

@@ -0,0 +1,94 @@
'use client';
import Link from 'next/link';
import { MailCheck, Send } from 'lucide-react';
import { Suspense } from 'react';
import { FormField } from '@/components/form';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { GuestGuard } from '@/guards';
import { useForgotPasswordForm } from '@/hooks/useForgotPasswordForm';
import { ROUTES } from '@/utils/routes';
import { Loader2 } from 'lucide-react';
function ForgotPasswordContent() {
const {
register,
handleSubmit,
errors,
isLoading,
isSubmitted,
isFormSubmitted,
canSubmit,
displayInfo,
} = useForgotPasswordForm();
return (
<GuestGuard>
<div className="flex min-h-screen w-full">
<div className="hidden w-[40%] md:flex" />
<div className="flex h-screen flex-1 items-center justify-center border-l border-border p-6 md:w-[60%]">
<section className="w-full max-w-sm space-y-7">
<header className="space-y-2 text-center md:text-left">
<p className="text-muted-foreground">VisionRoad</p>
<h1>{displayInfo.title}</h1>
<p className="text-muted-foreground">{displayInfo.description}</p>
</header>
{!isSubmitted ? (
<form className="space-y-5" onSubmit={handleSubmit}>
<FormField
id="email"
label="Email"
required
error={isFormSubmitted ? errors.email?.message : undefined}
>
<Input
id="email"
type="email"
placeholder="name@example.com"
autoComplete="email"
disabled={isLoading}
aria-invalid={!!errors.email}
{...register('email')}
/>
</FormField>
<Button
type="submit"
className="w-full"
disabled={isLoading || !canSubmit}
>
{isLoading ? <Loader2 className="size-4 animate-spin" /> : <Send />}
{displayInfo.buttonLabel}
</Button>
<div className="text-center">
<Link className="text-primary" href={ROUTES.LOGIN}>
Back to Login
</Link>
</div>
</form>
) : (
<Button asChild className="w-full">
<Link href={ROUTES.LOGIN}>
<MailCheck />
{displayInfo.buttonLabel}
</Link>
</Button>
)}
</section>
</div>
</div>
</GuestGuard>
);
}
export default function ForgotPasswordPage() {
return (
<Suspense fallback={null}>
<ForgotPasswordContent />
</Suspense>
);
}

View File

@@ -1,10 +1,14 @@
'use client';
import Link from 'next/link';
import { PasswordField } from '@/components/form';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { GuestGuard } from '@/guards';
import { useLoginForm } from '@/hooks/useLoginForm';
import { ROUTES } from '@/utils/routes';
import { Loader2 } from 'lucide-react';
export default function LoginPage() {
@@ -47,25 +51,24 @@ export default function LoginPage() {
)}
</div>
<div className="space-y-2">
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
placeholder="Enter password"
autoComplete="current-password"
disabled={isLoading}
aria-invalid={!!errors.password}
{...register('password', {
required: 'Password is required',
})}
/>
{errors.password && (
<p className="text-sm text-destructive">
{errors.password.message}
</p>
)}
</div>
<PasswordField
id="password"
label="Password"
required
labelEnd={
<Link href={ROUTES.FORGOT_PASSWORD} className="text-primary">
Forgot password?
</Link>
}
placeholder="Enter password"
autoComplete="current-password"
disabled={isLoading}
aria-invalid={!!errors.password}
error={errors.password?.message}
{...register('password', {
required: 'Password is required',
})}
/>
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? (

View File

@@ -0,0 +1,90 @@
'use client';
import { Loader2 } from 'lucide-react';
import { Suspense } from 'react';
import { PasswordField } from '@/components/form';
import { Button } from '@/components/ui/button';
import { GuestGuard } from '@/guards';
import { useSetPasswordForm } from '@/hooks/useSetPasswordForm';
function ResetPasswordContent() {
const {
register,
handleSubmit,
errors,
isLoading,
isSubmitted,
canSubmit,
displayInfo,
hasToken,
} = useSetPasswordForm();
return (
<GuestGuard>
<div className="flex min-h-screen w-full">
<div className="hidden w-[40%] md:flex" />
<div className="flex h-screen flex-1 items-center justify-center border-l border-border p-6 md:w-[60%]">
<section className="w-full max-w-sm space-y-7">
<header className="space-y-2 text-center md:text-left">
<p className="text-muted-foreground">VisionRoad</p>
<h1>{displayInfo.title}</h1>
<p className="text-muted-foreground">{displayInfo.description}</p>
</header>
{!hasToken ? (
<div className="rounded-md border border-destructive/30 bg-destructive/5 p-4 text-destructive">
Password reset token is missing.
</div>
) : (
<form className="space-y-5" onSubmit={handleSubmit}>
<PasswordField
id="password"
label="New Password"
required
error={isSubmitted ? errors.password?.message : undefined}
placeholder="Enter new password"
autoComplete="new-password"
disabled={isLoading}
aria-invalid={!!errors.password}
{...register('password')}
/>
<PasswordField
id="confirm-password"
label="Confirm Password"
required
error={
isSubmitted ? errors.confirmPassword?.message : undefined
}
placeholder="Confirm new password"
autoComplete="new-password"
disabled={isLoading}
aria-invalid={!!errors.confirmPassword}
{...register('confirmPassword')}
/>
<Button
type="submit"
className="w-full"
disabled={isLoading || !canSubmit}
>
{isLoading ? <Loader2 className="size-4 animate-spin" /> : null}
{displayInfo.buttonLabel}
</Button>
</form>
)}
</section>
</div>
</div>
</GuestGuard>
);
}
export default function ResetPasswordPage() {
return (
<Suspense fallback={null}>
<ResetPasswordContent />
</Suspense>
);
}

View File

@@ -0,0 +1 @@
export { default } from '../reset-password/page';

View File

@@ -98,32 +98,34 @@ export function UserSheet({
</FormField>
</div>
<FormField
id="email"
label="Email"
required
error={emailErrorMessage}
>
<Input
<div className="grid gap-4 md:grid-cols-2">
<FormField
id="email"
placeholder="name@example.com"
aria-invalid={!!emailErrorMessage}
{...register('email')}
/>
</FormField>
label="Email"
required
error={emailErrorMessage}
>
<Input
id="email"
placeholder="name@example.com"
aria-invalid={!!emailErrorMessage}
{...register('email')}
/>
</FormField>
<FormField
id="phone-number"
label="Phone Number"
error={phoneErrorMessage}
>
<Input
<FormField
id="phone-number"
placeholder="+919876543210"
aria-invalid={!!phoneErrorMessage}
{...register('phone_number')}
/>
</FormField>
label="Phone Number"
error={phoneErrorMessage}
>
<Input
id="phone-number"
placeholder="+919876543210"
aria-invalid={!!phoneErrorMessage}
{...register('phone_number')}
/>
</FormField>
</div>
<FormField label="Role" required error={roleErrorMessage}>
<RoleCombobox

View File

@@ -0,0 +1,67 @@
'use client';
import { EyeIcon, EyeOffIcon } from 'lucide-react';
import { useState, type ComponentProps, type ReactNode } from 'react';
import {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupInput,
} from '@/components/ui/input-group';
import { FormField } from './FormField';
interface PasswordFieldProps
extends Omit<ComponentProps<typeof InputGroupInput>, 'type'> {
label: ReactNode;
required?: boolean;
error?: ReactNode;
labelEnd?: ReactNode;
fieldClassName?: string;
}
export function PasswordField({
id,
label,
required = false,
error,
labelEnd,
fieldClassName,
disabled,
...props
}: PasswordFieldProps) {
const [showPassword, setShowPassword] = useState(false);
const ToggleIcon = showPassword ? EyeOffIcon : EyeIcon;
return (
<FormField
id={id}
label={label}
required={required}
error={error}
labelEnd={labelEnd}
className={fieldClassName}
>
<InputGroup data-disabled={disabled ? 'true' : undefined}>
<InputGroupInput
id={id}
type={showPassword ? 'text' : 'password'}
disabled={disabled}
{...props}
/>
<InputGroupAddon align="inline-end">
<InputGroupButton
type="button"
size="icon-xs"
aria-label={showPassword ? 'Hide password' : 'Show password'}
disabled={disabled}
onClick={() => setShowPassword((current) => !current)}
>
<ToggleIcon />
</InputGroupButton>
</InputGroupAddon>
</InputGroup>
</FormField>
);
}

View File

@@ -1 +1,2 @@
export { FormField } from './FormField';
export { PasswordField } from './PasswordField';

View File

@@ -4,6 +4,9 @@ export const API_ROUTES = {
REFRESH: 'api/auth/refresh',
LOGOUT: 'api/auth/logout',
ME: 'api/auth/me',
FORGOT_PASSWORD: 'api/auth/forget-password',
RESET_PASSWORD: 'api/auth/reset-password',
SET_PASSWORD: 'api/auth/set-password',
},
PERMISSIONS: {
MY_PERMISSIONS: 'api/permissions/my-permissions',

View File

@@ -0,0 +1,80 @@
'use client';
import { authService } from '@/services/api/auth.service';
import { zodResolver } from '@hookform/resolvers/zod';
import { useSearchParams } from 'next/navigation';
import { useMemo, useState } from 'react';
import { useForm, useWatch } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
const forgotPasswordFormSchema = z.object({
email: z
.string()
.trim()
.min(1, 'Email is required')
.email('Please enter a valid email address'),
});
export type ForgotPasswordFormValues = z.infer<
typeof forgotPasswordFormSchema
>;
export function useForgotPasswordForm() {
const searchParams = useSearchParams();
const email = searchParams.get('email') || '';
const [isSubmitted, setIsSubmitted] = useState(false);
const {
control,
register,
handleSubmit: submitForm,
formState: { errors, isSubmitting, isSubmitted: isFormSubmitted },
} = useForm<ForgotPasswordFormValues>({
defaultValues: { email },
mode: 'onSubmit',
reValidateMode: 'onChange',
resolver: zodResolver(forgotPasswordFormSchema),
});
const emailValue = useWatch({ control, name: 'email' }) || '';
const canSubmit = emailValue.trim().length > 0;
const displayInfo = useMemo(
() => ({
title: isSubmitted ? 'Check Your Email' : 'Forgot Password?',
description: isSubmitted
? 'We have sent a password reset link to your account. Please check your email and follow the instructions.'
: 'Enter your email address to receive a password reset link.',
buttonLabel: isSubmitted ? 'Back to Login' : 'Send Reset Link',
}),
[isSubmitted],
);
const onSubmit = submitForm(
async (values) => {
try {
await authService.forgotPassword({ email: values.email.trim() });
setIsSubmitted(true);
} catch (error) {
toast.error(
error instanceof Error ? error.message : 'Unable to send reset link',
);
}
},
(formErrors) => {
if (formErrors.email?.message) {
toast.error(formErrors.email.message);
}
},
);
return {
register,
handleSubmit: onSubmit,
errors,
isLoading: isSubmitting,
isSubmitted,
isFormSubmitted,
canSubmit,
displayInfo,
};
}

View File

@@ -0,0 +1,117 @@
'use client';
import { authService } from '@/services/api/auth.service';
import type { SetPasswordPayload } from '@/types';
import { ROUTES } from '@/utils/routes';
import { zodResolver } from '@hookform/resolvers/zod';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useMemo } from 'react';
import { useForm, useWatch } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
const setPasswordFormSchema = z
.object({
password: z
.string()
.trim()
.min(1, 'Password is required')
.min(6, 'Password must be at least 6 characters'),
confirmPassword: z.string().trim().min(1, 'Confirm password is required'),
})
.refine((values) => values.password === values.confirmPassword, {
path: ['confirmPassword'],
message: 'Passwords do not match',
});
export type SetPasswordFormValues = z.infer<typeof setPasswordFormSchema>;
export function useSetPasswordForm() {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const token = searchParams.get('token') || '';
const isInvite = pathname.includes(ROUTES.SET_PASSWORD);
const {
control,
register,
handleSubmit: submitForm,
formState: { errors, isSubmitting, isSubmitted },
} = useForm<SetPasswordFormValues>({
defaultValues: {
password: '',
confirmPassword: '',
},
mode: 'onSubmit',
reValidateMode: 'onChange',
resolver: zodResolver(setPasswordFormSchema),
});
const password = useWatch({ control, name: 'password' }) || '';
const confirmPassword = useWatch({ control, name: 'confirmPassword' }) || '';
const canSubmit =
Boolean(token) &&
password.trim().length > 0 &&
confirmPassword.trim().length > 0;
const displayInfo = useMemo(
() => ({
title: isInvite ? 'Set Your Password' : 'Reset Your Password',
description: isInvite
? 'Welcome. Please set a secure password for your account.'
: 'Please enter your new password below.',
buttonLabel: isInvite ? 'Accept & Set Password' : 'Reset Password',
}),
[isInvite],
);
const onSubmit = submitForm(
async (values) => {
if (!token) {
toast.error('Password reset token is missing');
return;
}
const payload: SetPasswordPayload = {
token,
password: values.password.trim(),
confirm_password: values.confirmPassword.trim(),
};
try {
if (isInvite) {
await authService.setPassword(payload);
} else {
await authService.resetPassword(payload);
}
toast.success(
isInvite ? 'Password set successfully' : 'Password reset successfully',
);
router.replace(ROUTES.LOGIN);
} catch (error) {
toast.error(
error instanceof Error ? error.message : 'Unable to update password',
);
}
},
(formErrors) => {
if (formErrors.password?.message) {
toast.error(formErrors.password.message);
return;
}
if (formErrors.confirmPassword?.message) {
toast.error(formErrors.confirmPassword.message);
}
},
);
return {
register,
handleSubmit: onSubmit,
errors,
isLoading: isSubmitting,
isSubmitted,
canSubmit,
displayInfo,
hasToken: Boolean(token),
};
}

View File

@@ -1,8 +1,10 @@
import type {
AuthResponseData,
ForgotPasswordPayload,
LoginPayload,
MeResponse,
PermissionResponse,
SetPasswordPayload,
} from '@/types';
import { API_ROUTES } from '@/constants/apiRoutes';
import axiosClient, { axiosAuth } from '../axios/axios';
@@ -41,4 +43,25 @@ export const authService = {
);
return response.data;
},
forgotPassword: async (payload: ForgotPasswordPayload): Promise<unknown> => {
const response = await axiosAuth.post(
API_ROUTES.AUTH.FORGOT_PASSWORD,
payload,
);
return response.data;
},
resetPassword: async (payload: SetPasswordPayload): Promise<unknown> => {
const response = await axiosAuth.post(
API_ROUTES.AUTH.RESET_PASSWORD,
payload,
);
return response.data;
},
setPassword: async (payload: SetPasswordPayload): Promise<unknown> => {
const response = await axiosAuth.post(
API_ROUTES.AUTH.SET_PASSWORD,
payload,
);
return response.data;
},
};

View File

@@ -36,7 +36,10 @@ axiosClient.interceptors.response.use(
const requestUrl = originalRequest?.url ?? '';
const isAuthRoute =
requestUrl.includes('api/auth/login') ||
requestUrl.includes('api/auth/refresh');
requestUrl.includes('api/auth/refresh') ||
requestUrl.includes('api/auth/forget-password') ||
requestUrl.includes('api/auth/reset-password') ||
requestUrl.includes('api/auth/set-password');
if (
status === 401 &&

View File

@@ -60,6 +60,16 @@ export type LoginPayload = {
rememberMe?: boolean;
};
export type ForgotPasswordPayload = {
email: string;
};
export type SetPasswordPayload = {
token: string;
password: string;
confirm_password: string;
};
export type AuthResponseData = {
access_token?: string;
token_type?: string;

View File

@@ -1,5 +1,8 @@
export const ROUTES = {
LOGIN: '/login',
FORGOT_PASSWORD: '/forgot-password',
RESET_PASSWORD: '/reset-password',
SET_PASSWORD: '/set-password',
DASHBOARD: '/dashboard',
PROJECT: '/project',
PACKAGE: '/package',