forgot password in login page and account info implemented, sms.ir service works fine with sandbox key.

This commit is contained in:
2026-07-04 00:01:58 +03:30
parent 2f95559087
commit 3f7364dbf0
26 changed files with 1000 additions and 38 deletions

View File

@@ -130,7 +130,19 @@
"organizationEmailPlaceholder": "contact@sunshineclinic.com",
"organizationType": "Organization type",
"dentalClinic": "Dental Clinic",
"dentalLab": "Dental Lab"
"dentalLab": "Dental Lab",
"mobile": "Mobile number",
"mobilePlaceholder": "0912 345 6789",
"forgotPasswordTitle": "Reset your password",
"forgotPasswordSubtitle": "Enter the mobile number on your account. We will send a verification code.",
"codeSentHint": "Enter the verification code we sent to your mobile.",
"sendCode": "Send verification code",
"verificationCode": "Verification code",
"verificationCodePlaceholder": "12345",
"verifyAndContinue": "Verify and continue",
"backToSignIn": "Back to sign in",
"codeSendFailed": "Could not send verification code. Please try again.",
"verifyFailed": "Invalid or expired verification code."
},
"landing": {
"heroTitle": "Connect Dental Clinics & Labs",
@@ -168,7 +180,10 @@
"organizationNameMinLength": "Organization name must be at least 2 characters",
"organizationEmailInvalid": "Please enter a valid organization email",
"organizationTypeRequired": "Please select organization type",
"passwordsDoNotMatch": "Passwords don't match"
"passwordsDoNotMatch": "Passwords don't match",
"mobileRequired": "Mobile number is required",
"mobileInvalid": "Please enter a valid Iranian mobile number",
"codeRequired": "Verification code is required"
},
"today": {
"welcomeBack": "Welcome back!!",
@@ -517,6 +532,16 @@
"accountTitle": "Account",
"accountSubtitle": "Profile and security settings for your login.",
"accountPlaceholder": "Password change and profile editing will be wired here next (e.g. invite flow, reset password).",
"changePasswordTitle": "Change password",
"resetPasswordTitle": "Set a new password",
"resetPasswordSubtitle": "Your mobile was verified. Choose a new password for your account.",
"currentPassword": "Current password",
"newPassword": "New password",
"confirmNewPassword": "Confirm new password",
"updatePassword": "Update password",
"setNewPassword": "Save new password",
"passwordChanged": "Password updated. Please sign in again.",
"passwordChangeFailed": "Could not update password. Please try again.",
"subscriptionsTitle": "Subscriptions",
"subscriptionsSubtitle": "Your DyoLink workspace plan and seats for {orgName}. Clinic and lab income tracking stays under the sidebar Billing tab.",
"noSubscriptionNotice": "This organization has no active subscription. Select a plan below to start the purchase process.",

View File

@@ -130,7 +130,19 @@
"organizationEmailPlaceholder": "contact@sunshineclinic.com",
"organizationType": "نوع سازمان",
"dentalClinic": "کلینیک دندانپزشکی",
"dentalLab": "لابراتوار دندانپزشکی"
"dentalLab": "لابراتوار دندانپزشکی",
"mobile": "شماره موبایل",
"mobilePlaceholder": "۰۹۱۲ ۳۴۵ ۶۷۸۹",
"forgotPasswordTitle": "بازیابی رمز عبور",
"forgotPasswordSubtitle": "شماره موبایل ثبت‌شده در حساب خود را وارد کنید. کد تأیید برای شما ارسال می‌شود.",
"codeSentHint": "کد تأیید ارسال‌شده به موبایل خود را وارد کنید.",
"sendCode": "ارسال کد تأیید",
"verificationCode": "کد تأیید",
"verificationCodePlaceholder": "۱۲۳۴۵",
"verifyAndContinue": "تأیید و ادامه",
"backToSignIn": "بازگشت به ورود",
"codeSendFailed": "ارسال کد تأیید انجام نشد. دوباره تلاش کنید.",
"verifyFailed": "کد تأیید نامعتبر یا منقضی شده است."
},
"landing": {
"heroTitle": "اتصال کلینیک‌ها و لابراتوارهای دندانپزشکی",
@@ -168,7 +180,10 @@
"organizationNameMinLength": "نام سازمان باید حداقل ۲ کاراکتر باشد",
"organizationEmailInvalid": "لطفاً یک ایمیل سازمانی معتبر وارد کنید",
"organizationTypeRequired": "لطفاً نوع سازمان را انتخاب کنید",
"passwordsDoNotMatch": "رمزهای عبور مطابقت ندارند"
"passwordsDoNotMatch": "رمزهای عبور مطابقت ندارند",
"mobileRequired": "شماره موبایل الزامی است",
"mobileInvalid": "لطفاً یک شماره موبایل ایرانی معتبر وارد کنید",
"codeRequired": "کد تأیید الزامی است"
},
"today": {
"welcomeBack": "خوش آمدید!!",
@@ -517,6 +532,16 @@
"accountTitle": "حساب کاربری",
"accountSubtitle": "تنظیمات پروفایل و امنیت برای ورود شما.",
"accountPlaceholder": "تغییر رمز عبور و ویرایش پروفایل در مرحله بعدی در اینجا قرار می‌گیرند (مثلاً فرآیند دعوت، بازنشانی رمز عبور).",
"changePasswordTitle": "تغییر رمز عبور",
"resetPasswordTitle": "تنظیم رمز عبور جدید",
"resetPasswordSubtitle": "موبایل شما تأیید شد. رمز عبور جدید برای حساب خود انتخاب کنید.",
"currentPassword": "رمز عبور فعلی",
"newPassword": "رمز عبور جدید",
"confirmNewPassword": "تأیید رمز عبور جدید",
"updatePassword": "به‌روزرسانی رمز عبور",
"setNewPassword": "ذخیره رمز عبور جدید",
"passwordChanged": "رمز عبور به‌روزرسانی شد. لطفاً دوباره وارد شوید.",
"passwordChangeFailed": "به‌روزرسانی رمز عبور انجام نشد. دوباره تلاش کنید.",
"subscriptionsTitle": "اشتراک‌ها",
"subscriptionsSubtitle": "طرح و مجوزهای فضای کاری DyoLink شما برای {orgName}. پیگیری درآمد کلینیک و لابراتوار در برگه صورتحساب در نوار کناری قرار دارد.",
"noSubscriptionNotice": "این سازمان اشتراک فعالی ندارد. برای شروع فرآیند خرید، یک طرح زیر را انتخاب کنید.",

View File

@@ -130,7 +130,19 @@
"organizationEmailPlaceholder": "contact@sunshineclinic.com",
"organizationType": "Organisatietype",
"dentalClinic": "Tandartspraktijk",
"dentalLab": "Tandtechnisch Laboratorium"
"dentalLab": "Tandtechnisch Laboratorium",
"mobile": "Mobiel nummer",
"mobilePlaceholder": "0612 345 678",
"forgotPasswordTitle": "Wachtwoord herstellen",
"forgotPasswordSubtitle": "Voer het mobiele nummer van uw account in. We sturen een verificatiecode.",
"codeSentHint": "Voer de verificatiecode in die we naar uw mobiel hebben gestuurd.",
"sendCode": "Verificatiecode versturen",
"verificationCode": "Verificatiecode",
"verificationCodePlaceholder": "12345",
"verifyAndContinue": "Verifiëren en doorgaan",
"backToSignIn": "Terug naar inloggen",
"codeSendFailed": "Verificatiecode kon niet worden verstuurd. Probeer het opnieuw.",
"verifyFailed": "Ongeldige of verlopen verificatiecode."
},
"landing": {
"heroTitle": "Verbind Tandheelkundige Klinieken & Laboratoria",
@@ -168,7 +180,10 @@
"organizationNameMinLength": "Organisatienaam moet minimaal 2 tekens bevatten",
"organizationEmailInvalid": "Voer een geldig organisatie-e-mailadres in",
"organizationTypeRequired": "Selecteer een organisatietype",
"passwordsDoNotMatch": "Wachtwoorden komen niet overeen"
"passwordsDoNotMatch": "Wachtwoorden komen niet overeen",
"mobileRequired": "Mobiel nummer is verplicht",
"mobileInvalid": "Voer een geldig Iraans mobiel nummer in",
"codeRequired": "Verificatiecode is verplicht"
},
"today": {
"welcomeBack": "Welkom terug!!",
@@ -517,6 +532,16 @@
"accountTitle": "Account",
"accountSubtitle": "Profiel- en beveiligingsinstellingen voor uw login.",
"accountPlaceholder": "Wachtwoordwijziging en profielbewerking worden hierna hier aangesloten (bijv. uitnodigingsflow, wachtwoord herstellen).",
"changePasswordTitle": "Wachtwoord wijzigen",
"resetPasswordTitle": "Nieuw wachtwoord instellen",
"resetPasswordSubtitle": "Uw mobiel is geverifieerd. Kies een nieuw wachtwoord voor uw account.",
"currentPassword": "Huidig wachtwoord",
"newPassword": "Nieuw wachtwoord",
"confirmNewPassword": "Bevestig nieuw wachtwoord",
"updatePassword": "Wachtwoord bijwerken",
"setNewPassword": "Nieuw wachtwoord opslaan",
"passwordChanged": "Wachtwoord bijgewerkt. Log opnieuw in.",
"passwordChangeFailed": "Wachtwoord kon niet worden bijgewerkt. Probeer het opnieuw.",
"subscriptionsTitle": "Abonnementen",
"subscriptionsSubtitle": "Uw DyoLink-werkruimteplan en plaatsen voor {orgName}. Kliniek- en laboratoriuminkomsten blijven onder het tabblad Facturatie in de zijbalk.",
"noSubscriptionNotice": "Deze organisatie heeft geen actief abonnement. Selecteer hieronder een abonnement om het aankoopproces te starten.",

View File

@@ -1,28 +1,180 @@
'use client';
import { useEffect, useMemo, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { useTranslations } from 'next-intl';
import { Link } from '@/i18n/navigation';
import { Link, useRouter } from '@/i18n/navigation';
import { useSearchParams } from 'next/navigation';
import { Lock } from 'lucide-react';
import { useAuth } from '@/lib/hooks/useAuth';
import { authApi } from '@/lib/api/auth';
import { Button } from '@/components/ui/shared/Button';
import { Input } from '@/components/ui/shared/Input';
import { Toast } from '@/components/ui/shared/Toast';
type PasswordForm = {
currentPassword: string;
newPassword: string;
confirmPassword: string;
};
export default function AccountSettingsPage() {
const t = useTranslations('settings');
const tAuth = useTranslations('auth');
const tCommon = useTranslations('common');
const tValidation = useTranslations('validation');
const { user, isAuthReady } = useAuth();
const router = useRouter();
const searchParams = useSearchParams();
const isResetFlow = searchParams.get('reset') === '1';
const [error, setError] = useState<string | null>(null);
const [successMessage, setSuccessMessage] = useState<string | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const passwordSchema = useMemo(
() =>
z
.object({
currentPassword: z.string(),
newPassword: z
.string()
.min(8, tValidation('passwordMinLength'))
.regex(/[A-Z]/, tValidation('passwordUppercase'))
.regex(/[0-9]/, tValidation('passwordNumber')),
confirmPassword: z.string(),
})
.refine((data) => data.newPassword === data.confirmPassword, {
message: tValidation('passwordsDoNotMatch'),
path: ['confirmPassword'],
})
.superRefine((data, ctx) => {
if (!isResetFlow && !data.currentPassword.trim()) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: tValidation('passwordRequired'),
path: ['currentPassword'],
});
}
}),
[isResetFlow, tValidation],
);
const {
register,
handleSubmit,
reset,
formState: { errors },
} = useForm<PasswordForm>({
resolver: zodResolver(passwordSchema),
defaultValues: {
currentPassword: '',
newPassword: '',
confirmPassword: '',
},
});
useEffect(() => {
if (isAuthReady && !user) {
router.replace('/login');
}
}, [isAuthReady, user, router]);
const onSubmit = async (data: PasswordForm) => {
try {
setError(null);
setSuccessMessage(null);
setIsSubmitting(true);
await authApi.changePassword({
...(isResetFlow ? {} : { currentPassword: data.currentPassword }),
newPassword: data.newPassword,
});
reset();
setSuccessMessage(t('passwordChanged'));
router.replace('/login');
} catch (err: unknown) {
const message = err instanceof Error ? err.message : t('passwordChangeFailed');
setError(message || t('passwordChangeFailed'));
} finally {
setIsSubmitting(false);
}
};
if (!isAuthReady || !user) {
return (
<p className="text-text-secondary text-sm">{tCommon('loadingEllipsis')}</p>
);
}
return (
<div className="space-y-6">
<div>
<Link
href="/today"
className="text-sm text-primary hover:opacity-90"
>
<Link href="/today" className="text-sm text-primary hover:opacity-90">
{tCommon('backToApp')}
</Link>
<h1 className="text-2xl font-semibold text-text-primary mt-4">{t('accountTitle')}</h1>
<p className="text-text-secondary text-sm mt-2">{t('accountSubtitle')}</p>
<p className="text-text-secondary text-sm mt-2">
{isResetFlow ? t('resetPasswordSubtitle') : t('accountSubtitle')}
</p>
</div>
<div className="surface-card p-6 space-y-3">
<p className="text-sm text-text-secondary">{t('accountPlaceholder')}</p>
<div className="surface-card p-6 sm:p-8 max-w-lg">
<h2 className="text-lg font-medium text-text-primary mb-1">
{isResetFlow ? t('resetPasswordTitle') : t('changePasswordTitle')}
</h2>
<p className="text-sm text-text-secondary mb-6">
{user.email}
{user.mobile ? ` · ${user.mobile}` : ''}
</p>
<form className="space-y-5" onSubmit={handleSubmit(onSubmit)}>
{!isResetFlow && (
<Input
label={t('currentPassword')}
{...register('currentPassword')}
type="password"
placeholder={tAuth('passwordPlaceholder')}
error={errors.currentPassword?.message}
icon={<Lock className="h-5 w-5 icon-flat" />}
/>
)}
<Input
label={t('newPassword')}
{...register('newPassword')}
type="password"
placeholder={tAuth('passwordPlaceholder')}
error={errors.newPassword?.message}
icon={<Lock className="h-5 w-5 icon-flat" />}
/>
<Input
label={t('confirmNewPassword')}
{...register('confirmPassword')}
type="password"
placeholder={tAuth('passwordPlaceholder')}
error={errors.confirmPassword?.message}
icon={<Lock className="h-5 w-5 icon-flat" />}
/>
{error && (
<div className="p-3 bg-red-950/30 border border-red-600/40 rounded-[var(--radius-md)]">
<p className="text-sm text-red-600">{error}</p>
</div>
)}
<Button type="submit" variant="primary" isLoading={isSubmitting}>
{isResetFlow ? t('setNewPassword') : t('updatePassword')}
</Button>
</form>
</div>
{successMessage && (
<Toast variant="success">{successMessage}</Toast>
)}
</div>
);
}

View File

@@ -0,0 +1,206 @@
'use client';
import { useMemo, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { useTranslations } from 'next-intl';
import { Link, useRouter } from '@/i18n/navigation';
import { Phone, ShieldCheck } from 'lucide-react';
import { authApi } from '@/lib/api/auth';
import { useAuth } from '@/lib/hooks/useAuth';
import { Button } from '@/components/ui/shared/Button';
import { Input } from '@/components/ui/shared/Input';
import { TopBarControls } from '@/components/ui/shared/TopBarControls';
type ForgotPasswordForm = {
mobile: string;
code: string;
};
function normalizeIranMobile(input: string): string {
let digits = input.replace(/\D/g, '');
if (digits.startsWith('98') && digits.length === 12) digits = digits.slice(2);
if (digits.startsWith('0') && digits.length === 11) digits = digits.slice(1);
return digits;
}
export default function ForgotPasswordPage() {
const t = useTranslations('auth');
const tCommon = useTranslations('common');
const tValidation = useTranslations('validation');
const router = useRouter();
const { refreshSession } = useAuth();
const [step, setStep] = useState<'mobile' | 'code'>('mobile');
const [error, setError] = useState<string | null>(null);
const [isSending, setIsSending] = useState(false);
const [isVerifying, setIsVerifying] = useState(false);
const [sentMobile, setSentMobile] = useState('');
const schema = useMemo(
() =>
z.object({
mobile: z
.string()
.min(1, tValidation('mobileRequired'))
.refine((value) => /^9\d{9}$/.test(normalizeIranMobile(value)), {
message: tValidation('mobileInvalid'),
}),
code: z.string(),
}),
[tValidation],
);
const {
register,
handleSubmit,
getValues,
formState: { errors },
} = useForm<ForgotPasswordForm>({
resolver: zodResolver(schema),
defaultValues: { mobile: '', code: '' },
});
const onSendCode = async () => {
const mobile = getValues('mobile');
const parsed = schema.safeParse({ mobile, code: '' });
if (!parsed.success) {
setError(parsed.error.issues[0]?.message ?? tValidation('mobileInvalid'));
return;
}
try {
setError(null);
setIsSending(true);
await authApi.sendForgotPasswordCode(mobile);
setSentMobile(mobile);
setStep('code');
} catch (err: unknown) {
const message = err instanceof Error ? err.message : t('codeSendFailed');
setError(message || t('codeSendFailed'));
} finally {
setIsSending(false);
}
};
const onVerify = async (data: ForgotPasswordForm) => {
if (!data.code.trim()) {
setError(tValidation('codeRequired'));
return;
}
try {
setError(null);
setIsVerifying(true);
const response = await authApi.verifyForgotPasswordCode(
sentMobile || data.mobile,
data.code.trim(),
);
const orgs = response.data.organizations;
if (orgs.length === 1) {
await authApi.selectOrganization(orgs[0].id);
localStorage.setItem('currentOrganizationId', orgs[0].id);
await refreshSession();
router.push('/settings/account?reset=1');
return;
}
if (orgs.length > 1) {
sessionStorage.setItem('authRedirect', '/settings/account?reset=1');
await refreshSession();
router.push('/select-organization');
return;
}
await refreshSession();
router.push('/settings/account?reset=1');
} catch (err: unknown) {
const message = err instanceof Error ? err.message : t('verifyFailed');
setError(message || t('verifyFailed'));
} finally {
setIsVerifying(false);
}
};
return (
<div className="relative min-h-screen app-web-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8">
<div className="absolute top-4 right-4">
<TopBarControls />
</div>
<div className="sm:mx-auto sm:w-full sm:max-w-md">
<Link href="/" className="flex justify-center">
<span className="text-3xl font-semibold text-text-primary">{tCommon('appName')}</span>
</Link>
<h2 className="mt-6 text-center text-3xl font-semibold text-text-primary">
{t('forgotPasswordTitle')}
</h2>
<p className="mt-2 text-center text-sm text-text-secondary">
{step === 'mobile' ? t('forgotPasswordSubtitle') : t('codeSentHint')}
</p>
</div>
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
<div className="surface-card py-8 px-4 sm:px-10">
<form
className="space-y-6"
onSubmit={handleSubmit(step === 'code' ? onVerify : () => undefined)}
>
{step === 'mobile' ? (
<Input
label={t('mobile')}
{...register('mobile')}
type="tel"
inputMode="tel"
autoComplete="tel"
placeholder={t('mobilePlaceholder')}
error={errors.mobile?.message}
icon={<Phone className="h-5 w-5 icon-flat" />}
/>
) : (
<Input
label={t('verificationCode')}
{...register('code')}
type="text"
inputMode="numeric"
autoComplete="one-time-code"
placeholder={t('verificationCodePlaceholder')}
error={errors.code?.message}
icon={<ShieldCheck className="h-5 w-5 icon-flat" />}
/>
)}
{error && (
<div className="p-3 bg-red-50 border border-red-200 rounded-lg">
<p className="text-sm text-red-600">{error}</p>
</div>
)}
{step === 'mobile' ? (
<Button
type="button"
variant="primary"
isLoading={isSending}
fullWidth
onClick={() => void onSendCode()}
>
{t('sendCode')}
</Button>
) : (
<Button type="submit" variant="primary" isLoading={isVerifying} fullWidth>
{t('verifyAndContinue')}
</Button>
)}
<p className="text-center text-sm text-text-secondary">
<Link href="/login" className="font-medium text-primary hover:opacity-90">
{t('backToSignIn')}
</Link>
</p>
</form>
</div>
</div>
</div>
);
}

View File

@@ -6,7 +6,7 @@ import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { useTranslations } from 'next-intl';
import { Link } from '@/i18n/navigation';
import { Mail, Lock, User } from 'lucide-react';
import { Mail, Lock, User, Phone } from 'lucide-react';
import { useAuth } from '@/lib/hooks/useAuth';
import { OrganizationDetailsFields } from '@/components/ui/auth/OrganizationDetailsFields';
import { RegistrationProgressSteps } from '@/components/ui/auth/RegistrationProgressSteps';
@@ -17,6 +17,7 @@ import { TopBarControls } from '@/components/ui/shared/TopBarControls';
type RegisterForm = {
name: string;
email: string;
mobile: string;
password: string;
confirmPassword: string;
organizationName: string;
@@ -24,6 +25,13 @@ type RegisterForm = {
organizationType: 'CLINIC' | 'LAB';
};
function normalizeIranMobile(input: string): string {
let digits = input.replace(/\D/g, '');
if (digits.startsWith('98') && digits.length === 12) digits = digits.slice(2);
if (digits.startsWith('0') && digits.length === 11) digits = digits.slice(1);
return digits;
}
export default function RegisterPage() {
const t = useTranslations('auth');
const tCommon = useTranslations('common');
@@ -38,6 +46,12 @@ export default function RegisterPage() {
.object({
name: z.string().min(2, tValidation('nameMinLength')),
email: z.string().email(tValidation('emailInvalid')),
mobile: z
.string()
.min(1, tValidation('mobileRequired'))
.refine((value) => /^9\d{9}$/.test(normalizeIranMobile(value)), {
message: tValidation('mobileInvalid'),
}),
password: z
.string()
.min(8, tValidation('passwordMinLength'))
@@ -74,7 +88,7 @@ export default function RegisterPage() {
const handleNext = async () => {
const fieldsToValidate =
step === 1
? (['name', 'email', 'password', 'confirmPassword'] as const)
? (['name', 'email', 'mobile', 'password', 'confirmPassword'] as const)
: (['organizationName', 'organizationEmail', 'organizationType'] as const);
const isValid = await trigger([...fieldsToValidate]);
@@ -90,6 +104,7 @@ export default function RegisterPage() {
data.email,
data.password,
data.name,
data.mobile,
data.organizationName,
data.organizationEmail,
data.organizationType,
@@ -157,6 +172,16 @@ export default function RegisterPage() {
error={errors.email?.message}
icon={<Mail className="h-5 w-5 icon-flat" />}
/>
<Input
label={t('mobile')}
{...register('mobile')}
type="tel"
inputMode="tel"
autoComplete="tel"
placeholder={t('mobilePlaceholder')}
error={errors.mobile?.message}
icon={<Phone className="h-5 w-5 icon-flat" />}
/>
<Input
label={t('password')}
{...register('password')}

View File

@@ -1,7 +1,7 @@
'use client';
import { ChevronDown } from 'lucide-react';
import React, { forwardRef } from 'react';
import React, { forwardRef, useId } from 'react';
interface DropdownProps extends React.SelectHTMLAttributes<HTMLSelectElement> {
label?: string;
@@ -10,7 +10,8 @@ interface DropdownProps extends React.SelectHTMLAttributes<HTMLSelectElement> {
export const Dropdown = forwardRef<HTMLSelectElement, DropdownProps>(
({ label, error, className = '', id, children, ...props }, ref) => {
const selectId = id || `dropdown-${Math.random().toString(36).slice(2, 9)}`;
const genId = useId();
const selectId = id ?? genId;
return (
<div className="w-full">

View File

@@ -1,5 +1,6 @@
// src/components/ui/Input.tsx
import React, { forwardRef } from 'react';
'use client';
import React, { forwardRef, useId } from 'react';
interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
label?: string;
@@ -9,8 +10,8 @@ interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
export const Input = forwardRef<HTMLInputElement, InputProps>(
({ label, error, icon, className = '', id, ...props }, ref) => {
const inputId =
id || `input-${Math.random().toString(36).slice(2, 9)}`;
const genId = useId();
const inputId = id ?? genId;
return (
<div className="w-full">

View File

@@ -1,6 +1,6 @@
// src/lib/api/auth.ts
import { apiClient } from './client';
import type { AuthResponse, TrialRegistrationData, LoginData } from '@/types/auth';
import type { AuthResponse, TrialRegistrationData, LoginData, ForgotPasswordVerifyResponse } from '@/types/auth';
import type { SubscriptionAlertData } from '@/types/subscription';
export const authApi = {
@@ -65,4 +65,25 @@ export const authApi = {
const response = await apiClient.post('/auth/refresh', { refreshToken });
return response.data;
},
sendForgotPasswordCode: async (mobile: string): Promise<{ success: boolean; message: string }> => {
const response = await apiClient.post('/auth/forgot-password/send-code', { mobile });
return response.data;
},
verifyForgotPasswordCode: async (
mobile: string,
code: string,
): Promise<ForgotPasswordVerifyResponse> => {
const response = await apiClient.post('/auth/forgot-password/verify', { mobile, code });
return response.data;
},
changePassword: async (data: {
currentPassword?: string;
newPassword: string;
}): Promise<{ success: boolean; message: string }> => {
const response = await apiClient.patch('/auth/profile/password', data);
return response.data;
},
};

View File

@@ -34,7 +34,9 @@ function shouldSkipRefreshRetry(url: string | undefined): boolean {
url.includes('/auth/refresh') ||
url.includes('/auth/login') ||
url.includes('/auth/register') ||
url.includes('/auth/logout')
url.includes('/auth/logout') ||
url.includes('/auth/forgot-password') ||
url.includes('/auth/profile/password')
);
}

View File

@@ -23,6 +23,7 @@ interface AuthContextType {
email: string,
password: string,
name: string,
mobile: string,
organizationName: string,
organizationEmail: string,
organizationType: 'CLINIC' | 'LAB'
@@ -37,6 +38,7 @@ interface AuthContextType {
planName?: string,
) => Promise<string>;
setUserLanguage: (language: string) => void;
refreshSession: () => Promise<void>;
clearError: () => void;
}
@@ -158,6 +160,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
email: string,
password: string,
name: string,
mobile: string,
organizationName: string,
organizationEmail: string,
organizationType: 'CLINIC' | 'LAB'
@@ -168,6 +171,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
const response = await authApi.registerTrial({
email,
mobile,
password,
name,
organizationName,
@@ -284,7 +288,16 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
plan: (organization as { plan?: Organization['plan'] }).plan,
});
router.push('/today');
const redirectPath =
typeof window !== 'undefined'
? sessionStorage.getItem('authRedirect')
: null;
if (redirectPath) {
sessionStorage.removeItem('authRedirect');
router.push(redirectPath);
} else {
router.push('/today');
}
} catch (err: any) {
setError(err.message);
@@ -327,6 +340,10 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
}
}, [normalizeProfilePayload, t]);
const refreshSession = useCallback(async () => {
await checkAuth();
}, [checkAuth]);
const clearError = useCallback(() => setError(null), []);
const setUserLanguage = useCallback((language: string) => {
@@ -348,6 +365,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
selectOrganization,
createOrganization,
setUserLanguage,
refreshSession,
clearError,
}),
[
@@ -363,6 +381,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
selectOrganization,
createOrganization,
setUserLanguage,
refreshSession,
clearError,
],
);

View File

@@ -12,6 +12,7 @@ export interface AuthResponse {
export interface TrialRegistrationData {
email: string;
mobile: string;
password: string;
name: string;
organizationName: string;
@@ -24,3 +25,12 @@ export interface LoginData {
password: string;
rememberMe?: boolean;
}
export interface ForgotPasswordVerifyResponse {
success: boolean;
data: {
user: AuthResponse['data']['user'];
organizations: AuthResponse['data']['organizations'];
redirectTo: string;
};
}

View File

@@ -3,6 +3,7 @@ export interface User {
email: string;
name: string;
language?: string;
mobile?: string | null;
}
export interface OrganizationPlan {