otp request + otp verify + component toast

This commit is contained in:
hamid zarghami
2025-11-11 12:35:44 +03:30
parent 04f3b3b9b5
commit bd2f5b33c1
16 changed files with 488 additions and 654 deletions
+14
View File
@@ -0,0 +1,14 @@
import { useMutation } from "@tanstack/react-query";
import * as api from "../service/LoginService";
export const useOtpRequest = () => {
return useMutation({
mutationFn: api.loginOTP,
});
};
export const useOtpVerify = () => {
return useMutation({
mutationFn: api.loginVerifyOTP,
});
};
+12 -158
View File
@@ -1,169 +1,23 @@
'use client'
import React, {
useState,
type FormEvent,
type ChangeEvent,
useEffect,
useTransition
} from 'react'
import { useAuthStore } from '@/zustand/authStore'
import { redirect, useParams, useRouter } from 'next/navigation'
import StepEnterPassword from '@/features/auth/components/StepEnterPassword'
import React from 'react'
import StepEnterNumber from '@/features/auth/components/StepEnterNumber'
import { AUTH_PAGE_ELEMENT, AUTH_STEP } from '@/enums'
import AuthFormWrapper from '@/features/auth/components/AuthFormWrapper'
import { useLogin } from '@/hooks/auth/useLogin'
import { useCheckUserExistsLazy } from '@/hooks/auth/useCheckUserExists'
import { useAuthTempStore } from '@/zustand/authTempStroe'
type Props = object
function AuthIndex ({}: Props) {
const update_temp_store = useAuthTempStore(state => state.update)
const user_temp_store = useAuthTempStore(state => state.user)
const [number, setNumber] = useState(user_temp_store?.number ?? '')
const [password, setPassword] = useState('')
const [showPassword, setShowPassword] = useState(false)
const [rememberMe, setRememberMe] = useState(false)
const [step, setStep] = useState(
number == '' ? AUTH_STEP.ENTER_NUMBER : AUTH_STEP.ENTER_CURRENT_PASSWORD
)
const [isPending, startTransition] = useTransition()
const isAuthenticated = useAuthStore(state => state.isAuthenticated)
const loginMutation = useLogin()
const { run: runUserExistCheck } = useCheckUserExistsLazy()
const router = useRouter()
const { name } = useParams()
const basePath = `/${name ?? ''}`
useEffect(() => {
if (isAuthenticated) {
redirect(basePath)
}
}, [isAuthenticated, basePath])
const onChange = (e: ChangeEvent<HTMLInputElement>) => {
if (e.target.name == AUTH_PAGE_ELEMENT.INPUT_PHONE) {
setNumber(() => e.target.value)
} else if (e.target.name == AUTH_PAGE_ELEMENT.INPUT_PASSWORD) {
setPassword(() => e.target.value)
} else if (e.target.name == AUTH_PAGE_ELEMENT.INPUT_REMEMBER_ME) {
setRememberMe(state => !state)
}
}
const onClick = async (
e:
| React.MouseEvent<HTMLButtonElement, MouseEvent>
| React.MouseEvent<HTMLInputElement, MouseEvent>
) => {
e.stopPropagation()
const target = e.target as HTMLButtonElement
if (target.id === AUTH_PAGE_ELEMENT.TOGGLE_PASSWORD) {
setShowPassword(state => !state)
}
}
const onSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault()
startTransition(async () => {
try {
/* DEV SECTION */
/* REMOVE THIS CODE FOR PRODUCTION */
throw false
/* END OF DEV SECTION */
/* SECTION DETAILS */
/* if number is entered in the /auth page this page directly shows the password page */
/* Otherwise it shows the number page */
if (step == AUTH_STEP.ENTER_NUMBER) {
const userExists = await runUserExistCheck(number)
update_temp_store({
number: number,
mustLogin: userExists
})
if (userExists) {
setStep(AUTH_STEP.ENTER_CURRENT_PASSWORD)
} else {
router.replace(`${basePath}/auth/signup`)
}
} else if (
step == AUTH_STEP.ENTER_OTP ||
step == AUTH_STEP.ENTER_CREATE_PASSWORD ||
step == AUTH_STEP.ENTER_RESET_PASSWORD
) {
setStep(AUTH_STEP.ENTER_CURRENT_PASSWORD)
} else if (step == AUTH_STEP.ENTER_CURRENT_PASSWORD) {
update_temp_store({
password,
rememberMe
})
try {
await loginMutation.mutateAsync({ phone: number, password })
console.log('Signed in')
router.replace(basePath)
} catch (e) {
console.error('Could not Login: ', e)
}
}
} catch (ex) {
console.error(ex)
// TODO: Add toast errors
/* DEV SECTION */
/* REMOVE THIS CODE FOR PRODUCTION */
if (step == AUTH_STEP.ENTER_NUMBER) {
update_temp_store({
number,
mustLogin: !number.endsWith('0')
})
setStep(AUTH_STEP.ENTER_CURRENT_PASSWORD)
} else if (
step == AUTH_STEP.ENTER_OTP ||
step == AUTH_STEP.ENTER_CREATE_PASSWORD ||
step == AUTH_STEP.ENTER_RESET_PASSWORD
) {
setStep(AUTH_STEP.ENTER_CURRENT_PASSWORD)
} else if (step == AUTH_STEP.ENTER_CURRENT_PASSWORD) {
update_temp_store({
password,
rememberMe
})
try {
console.log('Signed in')
router.replace(basePath)
} catch (e) {
console.error('Could not Login: ', e)
}
}
/* END OF DEV SECTION */
}
})
}
function AuthIndex({ }: Props) {
return (
<AuthFormWrapper isPending={isPending} onSubmit={onSubmit}>
{step === AUTH_STEP.ENTER_NUMBER && (
<StepEnterNumber
pending={isPending}
onChange={onChange}
value={number}
/>
)}
{step === AUTH_STEP.ENTER_CURRENT_PASSWORD && (
<StepEnterPassword
pending={isPending}
onChange={onChange}
onClick={onClick}
value={password}
passwordVisible={showPassword}
rememberMe={rememberMe}
/>
)}
<AuthFormWrapper isPending={false} onSubmit={() => undefined}>
<StepEnterNumber />
{/* <StepEnterPassword
pending={false}
onChange={() => undefined}
onClick={() => undefined}
value=''
passwordVisible={false}
rememberMe={false}
/> */}
</AuthFormWrapper>
)
}
@@ -0,0 +1,12 @@
import { api } from "@/lib/api/axiosInstance";
import { LoginOTPRequestType, LoginVerifyOTPType } from "../types/Types";
export const loginOTP = async (params: LoginOTPRequestType) => {
const { data } = await api.post("/auth/otp/request", params);
return data;
};
export const loginVerifyOTP = async (params: LoginVerifyOTPType) => {
const { data } = await api.post("/auth/otp/verify", params);
return data;
};
+9
View File
@@ -0,0 +1,9 @@
export type LoginOTPRequestType = {
phone: string;
slug: string;
};
export type LoginVerifyOTPType = {
phone: string;
otp: string;
};
+2
View File
@@ -5,6 +5,7 @@ import { notFound } from "next/navigation";
import i18nConfig from "../../i18nConfig";
import initTranslations from '@/lib/i18n';
import TranslationsProvider from "@/components/utils/TranslationsProdiver";
import ToastContainer from "@/components/Toast";
export const metadata: Metadata = {
title: 'Dashboard',
@@ -49,6 +50,7 @@ export default async function RootLayout({
{children}
</div>
</TranslationsProvider>
<ToastContainer />
</ReactQueryProvider>
</body>
</html >
+73
View File
@@ -0,0 +1,73 @@
'use client'
import { CloseCircle, InfoCircle, TickCircle } from 'iconsax-react';
import React, { useState, useEffect } from 'react';
interface Toast {
id: string;
message: string;
type?: 'success' | 'error' | 'info';
isExiting?: boolean;
}
let addToast: (toast: Toast) => void;
const ToastContainer: React.FC = () => {
const [toasts, setToasts] = useState<Toast[]>([]);
// ثبت toast جدید
const showToast = (toast: Toast) => {
setToasts((prev) => [...prev, toast]);
// حذف خودکار بعد از ۳ ثانیه
setTimeout(() => {
setToasts((prev) => prev.map(t =>
t.id === toast.id ? { ...t, isExiting: true } : t
));
// حذف از DOM بعد از اتمام انیمیشن
setTimeout(() => {
setToasts((prev) => prev.filter((t) => t.id !== toast.id));
}, 300); // مدت زمان انیمیشن خروج
}, 3000);
};
// تخصیص تابع نمایش toast به متغیر سراسری
useEffect(() => {
addToast = showToast;
}, []);
return (
<div className="fixed top-4 text-sm right-0 left-0 mx-auto w-fit z-50 flex flex-col gap-2">
{toasts.map((toast) => (
<div
key={toast.id}
className={`px-4 flex items-center gap-2 backdrop-blur-2xl h-16 min-w-[300px] rounded-2xl shadow-md
${toast.isExiting ? 'animate-slide-out-right' : 'animate-slide-in-right'} ${toast.type === 'success'
? 'bg-white/70 text-black'
: toast.type === 'error'
? 'bg-white/70 text-black'
: 'bg-white/70 text-black'
}`}
style={{
animationFillMode: 'forwards',
animationDuration: '0.3s',
animationTimingFunction: 'ease-out'
}}
>
{
toast.type === 'success' ? <TickCircle className='size-5' color='green' /> :
toast.type === 'error' ? <CloseCircle className='size-5' color='red' /> :
<InfoCircle className='size-5' color='blue' />
}
{toast.message}
</div>
))}
</div>
);
};
export const toast = (message?: string, type: 'success' | 'error' | 'info' = 'info') => {
addToast({ id: Date.now().toString(), message: message || '', type });
};
export default ToastContainer;
+29 -24
View File
@@ -12,30 +12,35 @@ type Props = {
} & Omit<React.InputHTMLAttributes<HTMLInputElement>, "id">;
function InputField({ onChange, htmlFor, labelText, children, valid = true, className, ...inputProps }: Props) {
return (
<div
spellCheck={false}
className={`${className} ${valid ? 'border-border' : 'border-invalid'} h-11 inline-flex relative border px-3 w-full rounded-normal group focus-within:border`}>
<label
className='absolute start-2 -top-2.5 px-2 bg-inherit text-[12px] text-foreground'
htmlFor={htmlFor}>
{labelText}
</label>
const InputField = React.forwardRef<HTMLInputElement, Props>(
({ onChange, htmlFor, labelText, children, valid = true, className, ...inputProps }, ref) => {
return (
<div
spellCheck={false}
className={`${className} ${valid ? 'border-border' : 'border-invalid'} h-11 inline-flex relative border px-3 w-full rounded-normal group focus-within:border`}>
<label
className='absolute start-2 -top-2.5 px-2 bg-inherit text-[12px] text-foreground'
htmlFor={htmlFor}>
{labelText}
</label>
<Tooltip content={inputProps['aria-errormessage']} hidden={!inputProps['aria-errormessage']}>
<input
onChange={onChange}
className={clsx(
inputProps['aria-errormessage'] && '!text-red-300',
'py-2.5 pt-3.5 text-sm2 w-full outline-0 !leading-6'
)}
name={htmlFor}
{...inputProps} />
{children}
</Tooltip>
</div>
)
}
<Tooltip content={inputProps['aria-errormessage']} hidden={!inputProps['aria-errormessage']}>
<input
ref={ref}
onChange={onChange}
className={clsx(
inputProps['aria-errormessage'] && '!text-red-300',
'py-2.5 pt-3.5 text-sm2 w-full outline-0 !leading-6'
)}
name={htmlFor}
{...inputProps} />
{children}
</Tooltip>
</div>
)
}
)
InputField.displayName = 'InputField'
export default InputField
+3 -6
View File
@@ -1,7 +1,4 @@
export enum AUTH_STEP {
ENTER_NUMBER = 0,
ENTER_CURRENT_PASSWORD = 1,
ENTER_OTP = 2,
ENTER_CREATE_PASSWORD = 3,
ENTER_RESET_PASSWORD = 4,
}
ENTER_NUMBER = 0,
ENTER_OTP = 1,
}
@@ -5,12 +5,24 @@ import React from 'react'
type Props = {
isPending: boolean
} & Omit<React.FormHTMLAttributes<HTMLFormElement>, "id">;
} & Omit<React.FormHTMLAttributes<HTMLFormElement>, 'id'>;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function AuthFormWrapper({ children, isPending, ...restProps }: Props) {
function AuthFormWrapper({ children, isPending, onSubmit, ...restProps }: Props) {
const handleSubmit = React.useCallback(
(event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
onSubmit?.(event);
},
[onSubmit],
);
return (
<form {...restProps} className='p-6 lg:py-[75px] w-full flex items-center justify-center py-4 lg:items-center lg:px-10 px-4 drop-shadow-black h-full'>
<form
{...restProps}
onSubmit={handleSubmit}
className='p-6 lg:py-[75px] w-full flex items-center justify-center py-4 lg:items-center lg:px-10 px-4 drop-shadow-black h-full'
>
<div className='relative h-full w-full px-4 sm:px-6 lg:p-0 flex flex-col max-h-[812px] max-w-[1200px] bg-container rounded-container overflow-clip lg:flex-row justify-between'>
{children}
{/* <LoadingOverlay visible={isPending} bgOpacity={0} /> */}
@@ -2,35 +2,55 @@
import Button from '@/components/button/PrimaryButton'
import InputField from '@/components/input/InputField'
import { AUTH_PAGE_ELEMENT } from '@/enums'
import { AUTH_PAGE_ELEMENT, AUTH_STEP } from '@/enums'
import { LoginOTPRequestType } from '@/app/auth/login/types/Types'
import Image from 'next/image'
import React, { useEffect, useState } from 'react'
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import { useOtpRequest } from '@/app/auth/login/hooks/useAuthData'
import { useParams } from 'next/navigation'
import { toast } from '@/components/Toast'
import StepOtp from './StepOtp'
type Props = {
onChange: React.ChangeEventHandler<HTMLInputElement>
value: string
pending?: boolean | undefined
} & Omit<React.InputHTMLAttributes<HTMLInputElement>, 'id'>
function StepEnterNumber ({ onChange, pending, disabled, value }: Props) {
const [error, setError] = useState('')
function StepEnterNumber() {
const { t } = useTranslation('auth')
const { name } = useParams()
const [step, setStep] = useState(AUTH_STEP.ENTER_NUMBER)
const hasError = (e = error) => {
return e.trim().length > 0
}
const { mutate: mutateOtpRequest } = useOtpRequest()
useEffect(() => {
let error = ''
if (value.length > 0) {
if (!/^09\d{7,9}$/.test(value)) {
error = t('Errors.PhoneNumberFormat')
const formik = useFormik<LoginOTPRequestType>({
initialValues: {
phone: '',
slug: '',
},
validationSchema: Yup.object({
phone: Yup.string().required('Errors.PhoneNumberRequired').matches(/^09\d{9}$/, 'Errors.PhoneNumberFormat'),
}),
onSubmit: (values) => {
if (name) {
values.slug = name as string
values.phone = 'qtest'
mutateOtpRequest(values, {
onSuccess: () => {
toast(t('auth.otp_sent'))
setStep(AUTH_STEP.ENTER_OTP)
},
onError: (error) => {
// toast(t('auth.otp_sent_error'))
console.log(error);
}
})
}
}
})
setError(error)
}, [t, value])
return (
<>
@@ -46,27 +66,43 @@ function StepEnterNumber ({ onChange, pending, disabled, value }: Props) {
<div className='w-full min-w-1/2 lg:max-w-1/2 h-full lg:px-9 py-7 flex flex-col justify-between lg:justify-center lg:gap-10'>
<div className='w-full'>
<div className='pt-4'>
<h6 className='text-lg font-bold'>{t('Enter.Heading')}</h6>
<p className='mt-3 text-[13px]'>{t('Enter.Description')}</p>
{
step === AUTH_STEP.ENTER_NUMBER && (
<>
<h6 className='text-lg font-bold'>{t('Enter.Heading')}</h6>
<p className='mt-3 text-[13px]'>{t('Enter.Description')}</p>
</>
)
}
{
step === AUTH_STEP.ENTER_OTP && (
<>
<h6 className='text-lg font-bold'>{t('OTP.Heading')}</h6>
<p className='mt-3 text-[13px]'>{t('OTP.Description', { phoneNumber: formik.values.phone })}</p>
</>
)
}
</div>
<InputField
valid={!hasError()}
aria-errormessage={error}
inputMode='tel'
autoComplete='tel'
className='mt-10 w-full bg-container'
htmlFor={AUTH_PAGE_ELEMENT.INPUT_PHONE}
labelText={t('Enter.LabelPhoneNumber')}
value={value}
placeholder='09120000000'
onChange={onChange}
type='number'
/>
{step === AUTH_STEP.ENTER_NUMBER && (
<InputField
inputMode='tel'
autoComplete='tel'
className='mt-10 w-full bg-container'
htmlFor={AUTH_PAGE_ELEMENT.INPUT_PHONE}
labelText={t('Enter.LabelPhoneNumber')}
{...formik.getFieldProps('phone')}
placeholder='09120000000'
/>
)}
{step === AUTH_STEP.ENTER_OTP && (
<StepOtp phone={formik.values.phone} />
)}
</div>
<Button
disabled={disabled || hasError() || value.length <= 0}
pending={pending}
type='submit'
disabled={!formik.isValid}
pending={false}
type='button'
onClick={() => formik.handleSubmit()}
>
{t('Enter.ButtonSubmit')}
</Button>
+59
View File
@@ -0,0 +1,59 @@
import { LoginVerifyOTPType } from '@/app/auth/login/types/Types'
import React from 'react'
import OTPInput from 'react-otp-input'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import { useTranslation } from 'react-i18next'
import { useOtpVerify } from '@/app/auth/login/hooks/useAuthData'
import { toast } from '@/components/Toast'
type Props = {
phone: string
}
const StepOtp = ({ phone }: Props) => {
const { t } = useTranslation('auth')
const { mutate: mutateOtpVerify } = useOtpVerify()
const formik = useFormik<LoginVerifyOTPType>({
initialValues: {
phone: phone,
otp: ''
},
validationSchema: Yup.object({
otp: Yup.string().required(t('Errors.OTPRequired'))
}),
onSubmit: (values) => {
mutateOtpVerify(values, {
onSuccess: () => {
toast(t('auth.otp_verified'))
},
onError: (error) => {
console.log(error)
}
})
}
})
return (
<div className='mt-6 sm:mt-8 dltr otp'>
<OTPInput
shouldAutoFocus
value={formik.values.otp}
numInputs={5}
inputType='tel'
containerStyle={{ direction: 'ltr' }}
onChange={(otp: string) => formik.setFieldValue('otp', otp)}
renderInput={(props) =>
<input
{...props}
type='tel'
autoComplete="one-time-code"
inputMode="numeric"
className='w-full h-[45px] sm:h-[50px] flex-1 mx-1 sm:mx-2 bg-white border border-gray-300 outline-0 rounded-[10px] text-center text-lg sm:text-xl' />
}
/>
</div>
)
}
export default StepOtp
+6 -7
View File
@@ -1,11 +1,11 @@
import { useAuthStore } from '@/zustand/authStore';
import axios from 'axios';
import { refreshToken } from './auth/refresh-token';
import { useAuthStore } from "@/zustand/authStore";
import axios from "axios";
import { refreshToken } from "./auth/refresh-token";
// Create axios instance
const api = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL || 'https://api.example.com',
headers: { 'Content-Type': 'application/json' },
baseURL: process.env.NEXT_PUBLIC_API_BASE_URL,
headers: { "Content-Type": "application/json" },
});
let isRefreshing = false;
@@ -65,10 +65,9 @@ api.interceptors.response.use(
isRefreshing = true;
const token = useAuthStore.getState().user?.refreshToken;
console.log(useAuthStore.getState())
console.log(useAuthStore.getState());
if (!token) {
useAuthStore.getState().logout();
return Promise.reject(error);
}
+2 -1
View File
@@ -7,7 +7,7 @@
},
"OTP": {
"Heading": "Enter Activation Code",
"Description": "Please enter the 6-digit code sent to the number {phoneNumber}.",
"Description": "Please enter the 6-digit code sent to the number {{phoneNumber}}.",
"Label": "",
"TimerRunning": "{seconds} seconds left to receive the code",
"TimerOut": "Didnt receive the code?",
@@ -33,6 +33,7 @@
"Errors": {
"PasswordLength": "Password must be at least 6 characters long",
"PasswordMatch": "Repeated password does not match",
"PhoneNumberRequired": "Phone number is required",
"PhoneNumberFormat": "Phone number format is incorrect",
"OTPFormat": "Activation code is incomplete"
}
+39 -38
View File
@@ -1,39 +1,40 @@
{
"Enter": {
"Heading": "ورود به سیستم",
"Description": "برای ورود شماره همراه خود را وارد نمایید.",
"LabelPhoneNumber": "شماره همراه",
"ButtonSubmit": "بعدی"
},
"OTP": {
"Heading": "کد فعالسازی را وارد کنید",
"Description": "کد ۶ رقمی ارسال شده به شماره {phoneNumber} را وارد نمایید.",
"Label": "",
"TimerRunning": "{seconds} ثانیه دیگر تا دریافت کد",
"TimerOut": "کد را دریافت نکردید؟",
"TimerReset": "دوباره امتحان کنید",
"ButtonSubmit": "بعدی"
},
"NewPassword": {
"HeadingCreatePass": "انتخاب کلمه عبور",
"HeadingResetPass": "تغییر کلمه عبور",
"Description": "کلمه عبور جدید باید ترکیبی از حروف بزرگ و کوچک و نشانه ها باشد مثل A126bdz@",
"LabelPass": "کلمه عبور",
"LabelRepeatPass": "تکرار کلمه عبور",
"ButtonSubmit": "ورود"
},
"EnterPass": {
"Heading": "ورود به سیستم",
"Description": "کلمه عبور خود را وارد نمایید.",
"LabelPass": "کلمه عبور",
"ButtonRecover": "بازیابی کلمه عبور",
"LabelRememberance": "مرا به خاطر بسپار",
"ButtonSubmit": "ورود به منو"
},
"Errors": {
"PasswordLength": "کلمه عبور باید شامل حداقل 6 کاراکتر باشد",
"PasswordMatch": "تکرار کلمه عبور مطابقت ندارد",
"PhoneNumberFormat": "فرمت شماره تلفن اشتباه است",
"OTPFormat": "کد فعالسازی کامل نیست"
}
}
"Enter": {
"Heading": "ورود به سیستم",
"Description": "برای ورود شماره همراه خود را وارد نمایید.",
"LabelPhoneNumber": "شماره همراه",
"ButtonSubmit": "بعدی"
},
"OTP": {
"Heading": "کد فعالسازی را وارد کنید",
"Description": "کد ۵ رقمی ارسال شده به شماره {{phoneNumber}} را وارد نمایید.",
"Label": "",
"TimerRunning": "{seconds} ثانیه دیگر تا دریافت کد",
"TimerOut": "کد را دریافت نکردید؟",
"TimerReset": "دوباره امتحان کنید",
"ButtonSubmit": "بعدی"
},
"NewPassword": {
"HeadingCreatePass": "انتخاب کلمه عبور",
"HeadingResetPass": "تغییر کلمه عبور",
"Description": "کلمه عبور جدید باید ترکیبی از حروف بزرگ و کوچک و نشانه ها باشد مثل A126bdz@",
"LabelPass": "کلمه عبور",
"LabelRepeatPass": "تکرار کلمه عبور",
"ButtonSubmit": "ورود"
},
"EnterPass": {
"Heading": "ورود به سیستم",
"Description": "کلمه عبور خود را وارد نمایید.",
"LabelPass": "کلمه عبور",
"ButtonRecover": "بازیابی کلمه عبور",
"LabelRememberance": "مرا به خاطر بسپار",
"ButtonSubmit": "ورود به منو"
},
"Errors": {
"PasswordLength": "کلمه عبور باید شامل حداقل 6 کاراکتر باشد",
"PasswordMatch": "تکرار کلمه عبور مطابقت ندارد",
"PhoneNumberRequired": "وارد کردن شماره تلفن اجباری است",
"PhoneNumberFormat": "فرمت شماره تلفن اشتباه است",
"OTPFormat": "کد فعالسازی کامل نیست"
}
}