Compare commits

..

No commits in common. "b389839b9470d969ab078bc6552ae750afb88c21" and "9a9ff4460f721407763e0c22691a75980663ce46" have entirely different histories.

View File

@ -18,8 +18,8 @@ const otpSchema = z.object({
const LoginWithOtp = () => { const LoginWithOtp = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const [loading, setLoading] = useState(false); const [ loading, setLoading ] = useState( false );
const [timeLeft, setTimeLeft] = useState(0); const [ timeLeft, setTimeLeft ] = useState( 0 );
const inputRefs = useRef([]); const inputRefs = useRef([]);
@ -29,64 +29,59 @@ const LoginWithOtp = () => {
handleSubmit, handleSubmit,
formState: { errors, isSubmitted }, formState: { errors, isSubmitted },
getValues, getValues,
setValue,
trigger,
} = useForm({ } = useForm({
resolver: zodResolver(otpSchema), resolver: zodResolver(otpSchema),
}); });
const onSubmit = async (data) => { const onSubmit = async (data) => {
const finalOtp = data.otp1 + data.otp2 + data.otp3 + data.otp4; const finalOtp = data.otp1 + data.otp2 + data.otp3 + data.otp4;
const username = localStorage.getItem("otpUsername"); const username = localStorage.getItem( "otpUsername" );
setLoading(true); setLoading(true);
try { try {
let requestedData = { let requestedData = {
email: username, email: username,
otp: finalOtp otp:finalOtp
} }
const response = await AuthRepository.verifyOTP(requestedData) const response = await AuthRepository.verifyOTP( requestedData )
localStorage.setItem("jwtToken", response.data.token); localStorage.setItem("jwtToken", response.data.token);
localStorage.setItem("refreshToken", response.data.refreshToken); localStorage.setItem("refreshToken", response.data.refreshToken);
setLoading(false); setLoading( false );
localStorage.removeItem("otpUsername"); localStorage.removeItem( "otpUsername" );
localStorage.removeItem("otpSentTime"); localStorage.removeItem( "otpSentTime" );
navigate("/dashboard"); navigate( "/dashboard" );
} catch (err) { } catch (err) {
showToast("Invalid or expired OTP.", "error"); showToast( "Invalid or expired OTP.", "error" );
setLoading(false); setLoading(false);
} }
}; };
const formatTime = (seconds) => { const formatTime = (seconds) => {
const min = Math.floor(seconds / 60).toString().padStart(2, "0"); const min = Math.floor(seconds / 60).toString().padStart(2, "0");
const sec = (seconds % 60).toString().padStart(2, "0"); const sec = (seconds % 60).toString().padStart(2, "0");
return `${min}:${sec}`; return `${min}:${sec}`;
}; };
// Time Logic for OTP expiry useEffect(() => {
useEffect(() => {
const otpSentTime = localStorage.getItem("otpSentTime"); const otpSentTime = localStorage.getItem("otpSentTime");
const now = Date.now(); const now = Date.now();
if (otpSentTime) { if (otpSentTime) {
const elapsed = Math.floor((now - Number(otpSentTime)) / 1000); //in seconds const elapsed = Math.floor((now - Number(otpSentTime)) / 1000); // in seconds
const remaining = Math.max(OTP_EXPIRY_SECONDS - elapsed, 0); //prevent negatives const remaining = Math.max(OTP_EXPIRY_SECONDS - elapsed, 0); // prevent negatives
setTimeLeft(remaining); setTimeLeft(remaining);
} }
}, []); }, []);
useEffect(() => {
useEffect(() => {
if (timeLeft <= 0) return; if (timeLeft <= 0) return;
const timer = setInterval(() => { const timer = setInterval(() => {
setTimeLeft((prev) => { setTimeLeft((prev) => {
if (prev <= 1) { if (prev <= 1) {
clearInterval(timer); clearInterval(timer);
localStorage.removeItem("otpSentTime"); localStorage.removeItem( "otpSentTime" );
localStorage.removeItem("otpUsername"); localStorage.removeItem("otpUsername");
return 0; return 0;
} }
@ -95,31 +90,7 @@ const LoginWithOtp = () => {
}, 1000); }, 1000);
return () => clearInterval(timer); return () => clearInterval(timer);
}, [timeLeft]); }, [timeLeft]);
// Handle Paste Event
const handlePaste = (e) => {
e.preventDefault();
const pastedData = e.clipboardData.getData("text/plain").trim();
if (pastedData.match(/^\d{4}$/)) {
for (let i = 0; i < pastedData.length; i++) {
setValue(`otp${i + 1}`, pastedData[i], { shouldValidate: true });
if (inputRefs.current[i + 1]) {
inputRefs.current[i + 1].focus();
}
}
trigger(["otp1", "otp2", "otp3", "otp4"]);
} else {
showToast("Invalid OTP format pasted. Please enter 4 digits")
for (let i = 0; i < 4; i++) {
setValue(`otp${i + 1}`, "")
}
}
}
return ( return (
@ -138,7 +109,8 @@ const LoginWithOtp = () => {
key={num} key={num}
type="text" type="text"
maxLength={1} maxLength={1}
className={`form-control text-center ${errors[`otp${num}`] ? "is-invalid" : "" className={`form-control text-center ${
errors[`otp${num}`] ? "is-invalid" : ""
}`} }`}
ref={(el) => { ref={(el) => {
inputRefs.current[idx] = el; inputRefs.current[idx] = el;
@ -149,9 +121,6 @@ const LoginWithOtp = () => {
onChange(e); onChange(e);
if (/^\d$/.test(val) && idx < 3) { if (/^\d$/.test(val) && idx < 3) {
inputRefs.current[idx + 1]?.focus(); inputRefs.current[idx + 1]?.focus();
} else if (val === "" && idx > 0) {
inputRefs.current[idx - 1]?.focus();
} }
}} }}
onKeyDown={(e) => { onKeyDown={(e) => {
@ -163,8 +132,6 @@ const LoginWithOtp = () => {
inputRefs.current[idx - 1]?.focus(); inputRefs.current[idx - 1]?.focus();
} }
}} }}
onPaste={idx === 0 ? handlePaste : undefined}
style={{ width: "40px", height: "40px", fontSize: "15px" }} style={{ width: "40px", height: "40px", fontSize: "15px" }}
{...rest} {...rest}
/> />
@ -204,7 +171,7 @@ const LoginWithOtp = () => {
> >
OTP has expired. Please request a new one. OTP has expired. Please request a new one.
</p> </p>
<a className="text-primary cursor-pointer" onClick={() => navigate('/auth/login')}>Try Again</a> <a className="text-primary cursor-pointer" onClick={()=>navigate('/auth/login')}>Try Again</a>
</div> </div>
)} )}