reset password api integration done

This commit is contained in:
Senthamilselvi 2025-10-28 19:23:37 +05:30
parent e76dc7b82e
commit 3c942de90d
3 changed files with 565 additions and 526 deletions

View File

@ -1,208 +1,192 @@
import React from 'react';
import Logo from '../../assets/images/FCSCLogo.svg';
import { useNavigate } from 'react-router-dom';
import { changePassword } from '../../services/auth/authService.js';
import React from "react";
import Logo from "../../assets/images/FCSCLogo.svg";
import { useNavigate, useLocation } from "react-router-dom";
import apiClient from "../../services/api/apiClient.js";
const ChangePassword = () => {
const navigate = useNavigate();
const [currentPassword, setCurrentPassword] = React.useState('');
const [newPassword, setNewPassword] = React.useState('');
const [confirmPassword, setConfirmPassword] = React.useState('');
const [showCurrentPassword, setShowCurrentPassword] = React.useState(false);
const location = useLocation();
const registeredEmail = location.state?.email || "";
const [otp, setOtp] = React.useState("");
const [newPassword, setNewPassword] = React.useState("");
const [confirmPassword, setConfirmPassword] = React.useState("");
const [showOtp, setShowOtp] = React.useState(false);
const [showNewPassword, setShowNewPassword] = React.useState(false);
const [showConfirmPassword, setShowConfirmPassword] = React.useState(false);
const [loading, setLoading] = React.useState(false);
const [error, setError] = React.useState('');
const [success, setSuccess] = React.useState('');
const [error, setError] = React.useState("");
const [success, setSuccess] = React.useState("");
const handleSubmit = async (event) => {
event.preventDefault();
setError('');
setSuccess('');
const handleSubmit = async (e) => {
e.preventDefault();
setError("");
setSuccess("");
if (!currentPassword || !newPassword) {
setError('Please fill in all required fields.');
if (!registeredEmail) {
setError("Missing registered email. Please restart the process.");
return;
}
if (!otp || !newPassword || !confirmPassword) {
setError("Please fill in all fields.");
return;
}
if (newPassword !== confirmPassword) {
setError('New password and confirmation do not match.');
setError("Passwords do not match.");
return;
}
setLoading(true);
try {
const response = await changePassword({ currentPassword, newPassword });
const status = response?.status ?? 'success';
const message = response?.message || 'Password updated successfully. Please sign in again with your new password.';
if (status !== 'success') {
throw new Error(message);
const payload = {
registered_email: registeredEmail,
otp: otp.trim(),
password: newPassword,
confirm_password: confirmPassword,
};
const response = await apiClient.post("/forgot-password/verify-otp", payload);
if (response?.data) {
setSuccess("Password changed successfully. Redirecting to login...");
setTimeout(() => navigate("/login"), 1500);
} else {
setError("Something went wrong. Please try again.");
}
try {
sessionStorage.removeItem('auth_token');
sessionStorage.removeItem('user_profile');
sessionStorage.removeItem('user_role');
sessionStorage.removeItem('establishment_id');
} catch (storageError) {
console.warn('Unable to clear stored session', storageError);
}
setSuccess(message);
setTimeout(() => {
navigate('/login');
}, 1500);
} catch (err) {
const message = err?.response?.data?.message || err?.message || 'Unable to change password.';
setError(message);
const msg =
err.response?.data?.message ||
err.message ||
"Password change failed. Please verify the details.";
setError(msg);
} finally {
setLoading(false);
}
};
const ToggleableInput = ({ label, type = "password", value, onChange, show, toggleShow, placeholder }) => (
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
{label}
</label>
<div className="relative">
<input
type={show ? "text" : type}
value={value}
onChange={onChange}
placeholder={placeholder}
className="block w-full h-10 rounded-md border-2 border-[#92722A] focus:border-[#92722A] focus:ring-0 px-4 pr-11 text-sm bg-white"
required
/>
<button
type="button"
className="absolute inset-y-0 right-0 px-3 flex items-center cursor-pointer"
onClick={toggleShow}
aria-label="Toggle visibility"
>
{show ? (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-[#92722A]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M13.875 18.825A10.05 10.05 0 0 1 12 19c-5.523 0-10-4.477-10-10a9.96 9.96 0 0 1 2.122-6.21m3.086-1.955A9.953 9.953 0 0 1 12 3c5.523 0 10 4.477 10 10 0 1.591-.372 3.093-1.034 4.432M9.88 9.88a3 3 0 1 0 4.24 4.24"
/>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="m3 3 18 18"
/>
</svg>
) : (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-[#92722A]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12z" />
<circle cx="12" cy="12" r="3" strokeWidth="2" />
</svg>
)}
</button>
</div>
</div>
);
return (
<div className="min-h-screen bg-[#F7F7F7] flex items-center justify-center px-4">
<div className="w-full max-w-md">
<div className="bg-white rounded-lg shadow-sm ring-1 ring-gray-200 overflow-hidden">
<div className="px-7 py-8 border-b border-gray-200 bg-[#F2ECCF] text-center">
<img src={Logo} alt="FCSC" className="w-[188px] h-[58px] mx-auto mb-2" />
<h1 className="text-base font-semibold text-[#92722A]">Change Password</h1>
<p className="mt-1 text-sm text-gray-600">Keep your account secure by updating your password.</p>
<h1 className="text-base font-semibold text-[#92722A]">Reset Password</h1>
<p className="mt-1 text-sm text-gray-600">
Enter the verification code sent to your registered email and set a new password.
</p>
</div>
<form onSubmit={handleSubmit} className="px-7 py-8 space-y-4">
{error && <div className="text-sm text-red-700 bg-red-50 border border-red-200 rounded px-3 py-2">{error}</div>}
{success && <div className="text-sm text-green-700 bg-green-50 border border-green-200 rounded px-3 py-2">{success}</div>}
{error && (
<div className="text-sm text-red-700 bg-red-50 border border-red-200 rounded px-3 py-2">
{error}
</div>
)}
{success && (
<div className="text-sm text-green-700 bg-green-50 border border-green-200 rounded px-3 py-2">
{success}
</div>
)}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Current Password</label>
<div className="relative">
<input
type={showCurrentPassword ? 'text' : 'password'}
value={currentPassword}
onChange={(e) => setCurrentPassword(e.target.value)}
placeholder="Enter current password"
className="block w-full h-10 rounded-md border-2 border-[#92722A] focus:border-[#92722A] focus:ring-0 px-4 pr-11 text-sm bg-white"
required
/>
<button
type="button"
className="absolute inset-y-0 right-0 px-3 flex items-center cursor-pointer"
onClick={() => setShowCurrentPassword((v) => !v)}
aria-label="Toggle current password visibility"
>
{showCurrentPassword ? (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-[#92722A]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M13.875 18.825A10.05 10.05 0 0 1 12 19c-5.523 0-10-4.477-10-10a9.96 9.96 0 0 1 2.122-6.21m3.086-1.955A9.953 9.953 0 0 1 12 3c5.523 0 10 4.477 10 10 0 1.591-.372 3.093-1.034 4.432M9.88 9.88a3 3 0 1 0 4.24 4.24"
/>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="m3 3 18 18"
/>
</svg>
) : (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-[#92722A]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12z" />
<circle cx="12" cy="12" r="3" strokeWidth="2" />
</svg>
)}
</button>
</div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Registered Email
</label>
<input
type="email"
value={registeredEmail}
disabled
className="block w-full h-10 rounded-md border-2 border-gray-300 px-4 text-sm bg-gray-50 cursor-not-allowed"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">New Password</label>
<div className="relative">
<input
type={showNewPassword ? 'text' : 'password'}
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
placeholder="Enter new password"
className="block w-full h-10 rounded-md border-2 border-[#92722A] focus:border-[#92722A] focus:ring-0 px-4 pr-11 text-sm bg-white"
required
/>
<button
type="button"
className="absolute inset-y-0 right-0 px-3 flex items-center cursor-pointer"
onClick={() => setShowNewPassword((v) => !v)}
aria-label="Toggle new password visibility"
>
{showNewPassword ? (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-[#92722A]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M13.875 18.825A10.05 10.05 0 0 1 12 19c-5.523 0-10-4.477-10-10a9.96 9.96 0 0 1 2.122-6.21m3.086-1.955A9.953 9.953 0 0 1 12 3c5.523 0 10 4.477 10 10 0 1.591-.372 3.093-1.034 4.432M9.88 9.88a3 3 0 1 0 4.24 4.24"
/>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="m3 3 18 18"
/>
</svg>
) : (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-[#92722A]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12z" />
<circle cx="12" cy="12" r="3" strokeWidth="2" />
</svg>
)}
</button>
</div>
</div>
<ToggleableInput
label="Verification Code"
type="password"
value={otp}
onChange={(e) => setOtp(e.target.value)}
show={showOtp}
toggleShow={() => setShowOtp((v) => !v)}
placeholder="Enter 6-digit code"
/>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Confirm New Password</label>
<div className="relative">
<input
type={showConfirmPassword ? 'text' : 'password'}
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
placeholder="Re-enter new password"
className="block w-full h-10 rounded-md border-2 border-[#92722A] focus:border-[#92722A] focus:ring-0 px-4 pr-11 text-sm bg-white"
required
/>
<button
type="button"
className="absolute inset-y-0 right-0 px-3 flex items-center cursor-pointer"
onClick={() => setShowConfirmPassword((v) => !v)}
aria-label="Toggle confirm password visibility"
>
{showConfirmPassword ? (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-[#92722A]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M13.875 18.825A10.05 10.05 0 0 1 12 19c-5.523 0-10-4.477-10-10a9.96 9.96 0 0 1 2.122-6.21m3.086-1.955A9.953 9.953 0 0 1 12 3c5.523 0 10 4.477 10 10 0 1.591-.372 3.093-1.034 4.432M9.88 9.88a3 3 0 1 0 4.24 4.24"
/>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="m3 3 18 18"
/>
</svg>
) : (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-[#92722A]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12z" />
<circle cx="12" cy="12" r="3" strokeWidth="2" />
</svg>
)}
</button>
</div>
</div>
<ToggleableInput
label="New Password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
show={showNewPassword}
toggleShow={() => setShowNewPassword((v) => !v)}
placeholder="Enter new password"
/>
<ToggleableInput
label="Confirm New Password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
show={showConfirmPassword}
toggleShow={() => setShowConfirmPassword((v) => !v)}
placeholder="Re-enter new password"
/>
<button
type="submit"
disabled={loading}
className={`inline-flex items-center justify-center gap-2 w-full h-12 rounded-lg text-white ${loading ? 'bg-[#bfa06a] cursor-not-allowed' : 'bg-[#92722A] hover:bg-[#7b5c1f] cursor-pointer'} transition-colors`}
className={`inline-flex items-center justify-center w-full h-12 rounded-lg text-white ${
loading
? "bg-[#bfa06a] cursor-not-allowed"
: "bg-[#92722A] hover:bg-[#7b5c1f]"
} transition-colors`}
>
{loading ? 'Updating…' : 'Update Password'}
{loading ? "Processing…" : "Reset Password"}
</button>
<button
@ -219,4 +203,4 @@ const ChangePassword = () => {
);
};
export default ChangePassword;
export default ChangePassword;

View File

@ -12,28 +12,27 @@ const Login = () => {
const [loading, setLoading] = React.useState(false);
const [error, setError] = React.useState('');
const [toast, setToast] = React.useState(null);
const [captcha, setCaptcha] = React.useState('');
const [userCaptcha, setUserCaptcha] = React.useState('');
const [captchaError, setCaptchaError] = React.useState('');
const toastTimeoutRef = React.useRef(null);
const navigateTimeoutRef = React.useRef(null);
React.useEffect(() => {
try {
const remembered = sessionStorage.getItem('remember_me');
if (remembered === 'true') {
setRememberMe(true);
const storedEmail = sessionStorage.getItem('remembered_email');
const storedPassword = sessionStorage.getItem('remembered_password');
if (storedEmail) {
setEmail(storedEmail);
}
if (storedPassword) {
setPassword(storedPassword);
}
}
} catch (storageError) {
console.warn('Unable to read remembered credentials', storageError);
const generateCaptcha = React.useCallback(() => {
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
let code = '';
for (let i = 0; i < 6; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
setCaptcha(code);
}, []);
React.useEffect(() => {
generateCaptcha();
}, [generateCaptcha]);
const closeToast = React.useCallback(() => {
if (toastTimeoutRef.current) {
window.clearTimeout(toastTimeoutRef.current);
@ -55,31 +54,51 @@ const Login = () => {
}, 4000);
}, []);
const scheduleNavigate = React.useCallback((path) => {
if (!path) return;
if (navigateTimeoutRef.current) {
window.clearTimeout(navigateTimeoutRef.current);
navigateTimeoutRef.current = null;
}
navigateTimeoutRef.current = window.setTimeout(() => {
navigate(path);
navigateTimeoutRef.current = null;
}, 500);
}, [navigate]);
const scheduleNavigate = React.useCallback(
(path) => {
if (!path) return;
if (navigateTimeoutRef.current) {
window.clearTimeout(navigateTimeoutRef.current);
navigateTimeoutRef.current = null;
}
navigateTimeoutRef.current = window.setTimeout(() => {
navigate(path);
navigateTimeoutRef.current = null;
}, 500);
},
[navigate]
);
React.useEffect(() => () => {
if (toastTimeoutRef.current) {
window.clearTimeout(toastTimeoutRef.current);
}
if (navigateTimeoutRef.current) {
window.clearTimeout(navigateTimeoutRef.current);
}
}, []);
React.useEffect(
() => () => {
if (toastTimeoutRef.current) {
window.clearTimeout(toastTimeoutRef.current);
}
if (navigateTimeoutRef.current) {
window.clearTimeout(navigateTimeoutRef.current);
}
},
[]
);
const handleCaptchaChange = (e) => {
setUserCaptcha(e.target.value.toUpperCase());
setCaptchaError('');
};
const submit = async (e) => {
e.preventDefault();
setError('');
setCaptchaError('');
setLoading(true);
if (userCaptcha !== captcha) {
setCaptchaError('Incorrect CAPTCHA. Please try again.');
generateCaptcha();
setLoading(false);
return;
}
try {
const response = await login({ email, password });
if (response?.status !== 'success' || !response?.data) {
@ -87,80 +106,50 @@ const Login = () => {
}
const token = response.data;
try {
sessionStorage.setItem('auth_token', token);
} catch (storageError) {
console.error('Failed to persist auth token', storageError);
}
sessionStorage.setItem('auth_token', token);
let payload;
try {
const [, base64Payload] = token.split('.');
const json = atob(base64Payload);
payload = JSON.parse(json);
} catch (decodeError) {
console.error('Failed to decode token', decodeError);
} catch {
throw new Error('Received invalid token.');
}
const role = payload?.role ?? (payload?.is_admin ? 'Admin' : undefined);
if (role) {
try {
sessionStorage.setItem('user_role', role);
} catch (storageError) {
console.warn('Unable to persist user role', storageError);
}
}
if (role) sessionStorage.setItem('user_role', role);
try {
const profile = {
name: payload?.name || payload?.username || '',
email: payload?.email || '',
};
sessionStorage.setItem('user_profile', JSON.stringify(profile));
} catch (storageError) {
console.warn('Unable to persist user profile', storageError);
}
const profile = {
name: payload?.name || payload?.username || '',
email: payload?.email || '',
};
sessionStorage.setItem('user_profile', JSON.stringify(profile));
const establishmentId = payload?.establishment_id ?? payload?.establishmentId;
const isAdmin = String(role || '').toLowerCase() === 'admin' || payload?.is_admin === true;
const isAdmin =
String(role || '').toLowerCase() === 'admin' || payload?.is_admin === true;
const successMessage = response?.message || 'Login successful.';
if (isAdmin) {
try {
sessionStorage.removeItem('establishment_id');
} catch (storageError) {
console.warn('Unable to clear establishment ID', storageError);
}
sessionStorage.removeItem('establishment_id');
showToast('success', successMessage);
scheduleNavigate('/admin/dashboard');
return;
}
if (rememberMe) {
try {
sessionStorage.setItem('remember_me', 'true');
sessionStorage.setItem('remembered_email', email);
sessionStorage.setItem('remembered_password', password);
} catch (storageError) {
console.warn('Unable to persist remember-me preference', storageError);
}
sessionStorage.setItem('remember_me', 'true');
sessionStorage.setItem('remembered_email', email);
sessionStorage.setItem('remembered_password', password);
} else {
try {
sessionStorage.removeItem('remember_me');
sessionStorage.removeItem('remembered_email');
sessionStorage.removeItem('remembered_password');
} catch (storageError) {
console.warn('Unable to clear remembered credentials', storageError);
}
sessionStorage.removeItem('remember_me');
sessionStorage.removeItem('remembered_email');
sessionStorage.removeItem('remembered_password');
}
if (establishmentId) {
try {
sessionStorage.setItem('establishment_id', String(establishmentId));
} catch (storageError) {
console.warn('Unable to persist establishment ID', storageError);
}
sessionStorage.setItem('establishment_id', String(establishmentId));
showToast('success', successMessage);
scheduleNavigate('/dashboard');
} else {
@ -180,9 +169,10 @@ const Login = () => {
<div className="min-h-screen bg-[#F7F7F7] flex items-center justify-center px-4">
{loading && (
<div className="fixed inset-0 z-40 flex items-center justify-center bg-black/20 backdrop-blur-sm">
<div className="h-12 w-12 animate-spin rounded-full border-[3px] border-white border-t-transparent" aria-label="Loading" />
<div className="h-12 w-12 animate-spin rounded-full border-[3px] border-white border-t-transparent" />
</div>
)}
{toast && (
<div className="fixed top-6 inset-x-0 z-50 flex justify-center px-4">
<div
@ -193,53 +183,31 @@ const Login = () => {
}`}
>
<div className="flex items-start gap-2">
{toast.type === 'success' ? (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="h-4 w-4 mt-0.5">
<path
fillRule="evenodd"
d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25Zm4.28 7.28a.75.75 0 0 0-1.06-1.06l-4.22 4.22-1.22-1.22a.75.75 0 0 0-1.06 1.06l1.75 1.75c.293.293.767.293 1.06 0l4.75-4.75Z"
clipRule="evenodd"
/>
</svg>
) : (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="h-4 w-4 mt-0.5">
<path
fillRule="evenodd"
d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25Zm-1.5 5.25a.75.75 0 0 1 1.5 0v4.5a.75.75 0 0 1-1.5 0v-4.5Zm.75 7.5a1 1 0 1 1 0 2 1 1 0 0 1 0-2Z"
clipRule="evenodd"
/>
</svg>
)}
<span>{toast.message}</span>
</div>
<button
type="button"
aria-label="Close"
className="flex h-6 w-6 items-center justify-center rounded hover:bg-black/5"
onClick={closeToast}
>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="h-4 w-4">
<path
fillRule="evenodd"
d="m12 10.94 3.97-3.97a.75.75 0 1 1 1.06 1.06L13.06 12l3.97 3.97a.75.75 0 1 1-1.06 1.06L12 13.06l-3.97 3.97a.75.75 0 1 1-1.06-1.06L10.94 12 6.97 8.03a.75.75 0 1 1 1.06-1.06L12 10.94Z"
clipRule="evenodd"
/>
</svg>
</button>
</div>
</div>
)}
<div className="w-full max-w-md">
<div className="bg-white rounded-lg shadow-sm ring-1 ring-gray-200 overflow-hidden">
<div className="px-7 py-8 border-b border-gray-200 bg-[#F2ECCF]">
<div className="flex flex-col items-center text-center gap-2">
<img src={Logo} alt="FCSC" className="w-[188px] h-[58px] mx-auto" />
<h1 className="text-base font-semibold text-[#92722A]">IPI Survey Platform</h1>
</div>
<div className="px-7 py-8 border-b border-gray-200 bg-[#F2ECCF] text-center">
<img src={Logo} alt="FCSC" className="w-[188px] h-[58px] mx-auto mb-2" />
<h1 className="text-base font-semibold text-[#92722A]">IPI Survey Platform</h1>
</div>
<form onSubmit={submit} className="px-7 py-8 space-y-4">
{error && (
<div className="text-sm text-red-700 bg-red-50 border border-red-200 rounded px-3 py-2">{error}</div>
<div className="text-sm text-red-700 bg-red-50 border border-red-200 rounded px-3 py-2">
{error}
</div>
)}
<div>
@ -255,38 +223,84 @@ const Login = () => {
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Password</label>
<div className="relative">
<input
type={showPassword ? 'text' : 'password'}
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter password"
className="block w-full h-10 rounded-md border-2 border-[#92722A] focus:border-[#92722A] focus:ring-0 px-4 pr-12 text-sm bg-white"
required
/>
<label className="block text-sm font-medium text-gray-700 mb-1">Password</label>
<div className="relative">
<input
type={showPassword ? 'text' : 'password'}
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter password"
className="block w-full h-10 rounded-md border-2 border-[#92722A] focus:border-[#92722A] focus:ring-0 px-4 pr-11 text-sm bg-white"
required
/>
<button
type="button"
className="absolute inset-y-0 right-0 px-3 flex items-center cursor-pointer"
onClick={() => setShowPassword((v) => !v)}
aria-label="Toggle password visibility"
>
{showPassword ? (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-[#92722A]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M13.875 18.825A10.05 10.05 0 0 1 12 19c-5.523 0-10-4.477-10-10a9.96 9.96 0 0 1 2.122-6.21m3.086-1.955A9.953 9.953 0 0 1 12 3c5.523 0 10 4.477 10 10 0 1.591-.372 3.093-1.034 4.432M9.88 9.88a3 3 0 1 0 4.24 4.24"
/>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="m3 3 18 18"
/>
</svg>
) : (
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-[#92722A]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12z" />
<circle cx="12" cy="12" r="3" strokeWidth="2" />
</svg>
)}
</button>
</div>
</div>
<div className="mt-4">
<label className="block text-sm font-medium text-gray-700 mb-1">
CAPTCHA Verification <span className="text-red-500">*</span>
</label>
<div className="flex items-center gap-3">
<div
className="flex justify-center items-center font-mono text-lg tracking-widest bg-gray-100 border-2 border-[#92722A] rounded-md px-4 py-2 select-none"
aria-hidden="true"
>
{captcha}
</div>
<button
type="button"
onClick={() => setShowPassword((s) => !s)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-[#92722A] hover:text-[#7b5c1f] cursor-pointer"
aria-label={showPassword ? 'Hide password' : 'Show password'}
title={showPassword ? 'Hide password' : 'Show password'}
onClick={generateCaptcha}
className="text-sm text-[#92722A] hover:underline"
>
{showPassword ? (
// Eye-off icon
<svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 3l18 18" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10.58 10.58A2 2 0 0012 14a2 2 0 001.42-.58M16.68 16.68C15.28 17.54 13.69 18 12 18 7 18 3.73 14.82 2 12c.58-.9 1.34-1.83 2.26-2.68M9.88 4.13C10.56 4.05 11.27 4 12 4c5 0 8.27 3.18 10 6-.46.72-1.03 1.43-1.71 2.1" />
</svg>
) : (
// Eye icon
<svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12z" />
<circle cx="12" cy="12" r="3" strokeWidth="2" />
</svg>
)}
Refresh
</button>
</div>
<p className="text-xs text-gray-500 mt-1">
If you cannot read the code, click "Refresh" or type:{" "}
<span className="font-mono">{captcha}</span>
</p>
<input
type="text"
name="captcha"
value={userCaptcha}
onChange={handleCaptchaChange}
placeholder="Enter the code shown above"
className={`mt-2 block w-full h-10 rounded-md border-2 ${
captchaError ? 'border-red-500' : 'border-[#92722A]'
} focus:border-[#92722A] focus:ring-0 px-4 text-sm bg-white`}
/>
{captchaError && (
<p className="text-xs text-red-600 mt-1">{captchaError}</p>
)}
</div>
<div className="flex items-center justify-between text-sm">
@ -301,7 +315,7 @@ const Login = () => {
</label>
<button
type="button"
className="text-[#92722A] hover:underline cursor-pointer"
className="text-[#92722A] hover:underline"
onClick={() => navigate('/reset-password')}
>
Forgot password?
@ -310,34 +324,15 @@ const Login = () => {
<button
type="submit"
disabled={loading}
className={`inline-flex items-center justify-center gap-2 w-full h-12 rounded-lg text-white ${loading ? 'bg-[#bfa06a] cursor-not-allowed' : 'bg-[#92722A] hover:bg-[#7b5c1f] cursor-pointer'} transition-colors`}
disabled={loading || !userCaptcha}
className={`inline-flex items-center justify-center w-full h-12 rounded-lg text-white ${
loading || !userCaptcha
? 'bg-[#bfa06a] cursor-not-allowed'
: 'bg-[#92722A] hover:bg-[#7b5c1f]'
} transition-colors`}
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-5 w-5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
{/* Arrow right */}
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M10 8l4 4-4 4M14 12H3"
/>
{/* Bracket (door) on the right */}
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M15 6h5v12h-5"
/>
</svg>
{loading ? 'Signing in…' : 'Sign in'}
</button>
</form>
</div>
</div>
@ -345,4 +340,4 @@ const Login = () => {
);
};
export default Login;
export default Login;

View File

@ -10,9 +10,9 @@ const PublicContactForm = () => {
establishmentName: "",
establishmentId: "",
email: "",
contactName: "",
contactPhone: "",
notes: "",
// contactName: "",
// contactPhone: "",
// notes: "",
});
const [errors, setErrors] = useState({});
@ -23,8 +23,11 @@ const PublicContactForm = () => {
const [loading, setLoading] = useState(false);
const [success, setSuccess] = useState("");
const [errorMsg, setErrorMsg] = useState("");
const [otpStep, setOtpStep] = useState(false);
const [otp, setOtp] = useState("");
const [otpMsg, setOtpMsg] = useState("");
const [otpError, setOtpError] = useState("");
// Generate simple CAPTCHA code
const generateCaptcha = () => {
const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
let code = "";
@ -38,45 +41,40 @@ const PublicContactForm = () => {
generateCaptcha();
}, []);
// Validation rules
const validate = (data = formData) => {
const newErrors = {};
if (!data.establishmentName.trim()) newErrors.establishmentName = "Establishment Name is required.";
if (!data.email.trim()) newErrors.email = "Registered Email is required.";
else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) newErrors.email = "Enter a valid email address.";
if (!data.contactName.trim()) newErrors.contactName = "Contact Person Name is required.";
if (!data.contactPhone.trim()) {
newErrors.contactPhone = "Contact Phone is required.";
} else if (!/^\d{10,12}$/.test(data.contactPhone)) {
newErrors.contactPhone = "Enter a valid phone number (1012 digits).";
}
else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email))
newErrors.email = "Enter a valid email address.";
// if (!data.contactName.trim()) newErrors.contactName = "Contact Person Name is required.";
// if (!data.contactPhone.trim()) {
// newErrors.contactPhone = "Contact Phone is required.";
// } else if (!/^\d{10,12}$/.test(data.contactPhone)) {
// newErrors.contactPhone = "Enter a valid phone number (1012 digits).";
// }
setErrors(newErrors);
setIsValid(Object.keys(newErrors).length === 0);
return newErrors;
};
// Restrict Contact Name: only letters and spaces
const handleNameChange = (e) => {
const { value } = e.target;
const filtered = value.replace(/[^A-Za-z\s]/g, ""); // remove numbers/special chars
setFormData((prev) => ({ ...prev, contactName: filtered }));
validate({ ...formData, contactName: filtered });
};
const handlePhoneChange = (e) => {
let { value } = e.target;
// Allow only numbers
value = value.replace(/\D/g, ""); // remove all non-numeric characters
// Limit to 12 digits
if (value.length > 12) value = value.slice(0, 12);
setFormData((prev) => ({ ...prev, contactPhone: value }));
validate({ ...formData, contactPhone: value });
};
// const handleNameChange = (e) => {
// const { value } = e.target;
// const filtered = value.replace(/[^A-Za-z\s]/g, "");
// setFormData((prev) => ({ ...prev, contactName: filtered }));
// validate({ ...formData, contactName: filtered });
// };
// const handlePhoneChange = (e) => {
// let { value } = e.target;
// value = value.replace(/\D/g, "");
// if (value.length > 12) value = value.slice(0, 12);
// setFormData((prev) => ({ ...prev, contactPhone: value }));
// validate({ ...formData, contactPhone: value });
// };
const handleChange = (e) => {
const { name, value } = e.target;
const updated = { ...formData, [name]: value };
@ -84,13 +82,11 @@ const handleNameChange = (e) => {
validate(updated);
};
// CAPTCHA validation
const handleCaptchaChange = (e) => {
setUserCaptcha(e.target.value.toUpperCase());
setCaptchaError("");
};
// Form submit
const handleSubmit = async (e) => {
e.preventDefault();
setErrorMsg("");
@ -105,196 +101,260 @@ const handleNameChange = (e) => {
return;
}
// Simulate processing
setLoading(true);
setTimeout(() => {
try {
const payload = {
establishment_name: formData.establishmentName.trim(),
establishment_code: formData.establishmentId.trim(),
registered_email: formData.email.trim(),
};
const response = await apiClient.post("/forgot-password/request-otp", payload);
if (response?.data) {
navigate("/change-password", {
state: { email: formData.email.trim() },
});
} else {
setErrorMsg("Something went wrong. Please try again.");
}
} catch (err) {
const msg =
err.response?.data?.message ||
err.message ||
"Failed to send OTP. Please check your details and try again.";
setErrorMsg(msg);
} finally {
setLoading(false);
}
};
const handleConfirmOtp = async () => {
if (!otp.trim()) {
setOtpError("Please enter the verification code.");
return;
}
// Show success toast/message
setSuccess("Reset Password request successful.");
setOtpError("");
setLoading(true);
setErrorMsg("");
setSuccess("");
// Clear fields and regenerate CAPTCHA
setFormData({
establishmentName: "",
establishmentId: "",
email: "",
contactName: "",
contactPhone: "",
notes: "",
});
setUserCaptcha("");
generateCaptcha();
try {
const payload = {
registered_email: formData.email.trim(),
otp: otp.trim(),
};
// After 3 seconds clear session + route to login
setTimeout(() => {
try {
sessionStorage.removeItem("auth_token");
sessionStorage.removeItem("user_profile");
sessionStorage.removeItem("user_role");
sessionStorage.removeItem("establishment_id");
} catch {
// ignore storage errors
}
navigate("/login");
}, 3000);
}, 1000); // small delay to simulate "submitting"
const response = await apiClient.post("/forgot-password/verify-otp", payload);
if (response?.data) {
setSuccess("OTP verified successfully. Redirecting to change password...");
setTimeout(() => navigate("/change-password"), 1500);
} else {
setOtpError("Invalid verification code. Please try again.");
}
} catch (err) {
const msg =
err.response?.data?.message ||
err.message ||
"Verification failed. Please check the code and try again.";
setOtpError(msg);
} finally {
setLoading(false);
}
};
const handleResendOtp = () => {
setOtpMsg("A new OTP has been sent to your registered email.");
setOtp("");
};
return (
<div className="min-h-screen bg-[#F7F7F7] flex items-center justify-center px-4">
<div className="w-full max-w-md">
<div className="bg-white rounded-lg shadow-sm ring-1 ring-gray-200 overflow-hidden">
{/* Header */}
<div className="px-7 py-8 border-b border-gray-200 bg-[#F2ECCF] text-center">
<img src={Logo} alt="FCSC" className="w-[188px] h-[58px] mx-auto mb-2" />
<h1 className="text-base font-semibold text-[#92722A]">
Contact Establishment Info
{!otpStep ? "Contact Establishment Info" : "Verify Your Email"}
</h1>
<p className="mt-1 text-sm text-gray-600">
Provide details to contact your establishment.
{!otpStep
? "Provide details to contact your establishment."
: "Enter the verification code sent to your registered email."}
</p>
</div>
<form onSubmit={handleSubmit} className="px-7 py-8 space-y-4">
{errorMsg && (
<div className="text-sm text-red-700 bg-red-50 border border-red-200 rounded px-3 py-2">
{errorMsg}
</div>
)}
{success && (
<div className="text-sm text-green-700 bg-green-50 border border-green-200 rounded px-3 py-2">
{success}
</div>
)}
{/* Inputs */}
<InputField
label="Establishment Name"
name="establishmentName"
required
value={formData.establishmentName}
onChange={handleChange}
error={errors.establishmentName}
/>
<InputField
label="Establishment ID (if known)"
name="establishmentId"
value={formData.establishmentId}
onChange={handleChange}
/>
<InputField
label="Registered Email"
name="email"
type="email"
required
value={formData.email}
onChange={handleChange}
error={errors.email}
/>
<InputField
label="Contact Person Name"
name="contactName"
required
value={formData.contactName}
onChange={handleNameChange} // new handler
error={errors.contactName}
/>
<InputField
label="Contact Phone"
name="contactPhone"
value={formData.contactPhone}
onChange={handlePhoneChange}
error={errors.contactPhone}
placeholder="Enter phone number"
maxLength={12} // extra safeguard
/>
{/* Notes */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Additional Notes
</label>
<textarea
name="notes"
rows="3"
value={formData.notes}
onChange={handleChange}
className="block w-full rounded-md border-2 border-[#92722A] focus:border-[#92722A] focus:ring-0 px-4 py-2 text-sm bg-white"
></textarea>
</div>
{/* CAPTCHA */}
<div className="mt-4">
<label className="block text-sm font-medium text-gray-700 mb-1">
CAPTCHA Verification <span className="text-red-500">*</span>
</label>
<div className="flex items-center gap-3">
<div
className="flex justify-center items-center font-mono text-lg tracking-widest bg-gray-100 border-2 border-[#92722A] rounded-md px-4 py-2 select-none"
aria-hidden="true"
>
{captcha}
{!otpStep ? (
<form onSubmit={handleSubmit} className="px-7 py-8 space-y-4">
{errorMsg && (
<div className="text-sm text-red-700 bg-red-50 border border-red-200 rounded px-3 py-2">
{errorMsg}
</div>
)}
{success && (
<div className="text-sm text-green-700 bg-green-50 border border-green-200 rounded px-3 py-2">
{success}
</div>
)}
<InputField
label="Establishment Name"
name="establishmentName"
required
value={formData.establishmentName}
onChange={handleChange}
error={errors.establishmentName}
/>
<InputField
label="Establishment ID (if known)"
name="establishmentId"
value={formData.establishmentId}
onChange={handleChange}
/>
<InputField
label="Registered Email"
name="email"
type="email"
required
value={formData.email}
onChange={handleChange}
error={errors.email}
/>
{/* <InputField
label="Contact Person Name"
name="contactName"
required
value={formData.contactName}
onChange={handleNameChange}
error={errors.contactName}
/>
<InputField
label="Contact Phone"
name="contactPhone"
value={formData.contactPhone}
onChange={handlePhoneChange}
error={errors.contactPhone}
placeholder="Enter phone number"
maxLength={12}
/>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Additional Notes
</label>
<textarea
name="notes"
rows="3"
value={formData.notes}
onChange={handleChange}
className="block w-full rounded-md border-2 border-[#92722A] focus:border-[#92722A] focus:ring-0 px-4 py-2 text-sm bg-white"
></textarea>
</div> */}
<div className="mt-4">
<label className="block text-sm font-medium text-gray-700 mb-1">
CAPTCHA Verification <span className="text-red-500">*</span>
</label>
<div className="flex items-center gap-3">
<div
className="flex justify-center items-center font-mono text-lg tracking-widest bg-gray-100 border-2 border-[#92722A] rounded-md px-4 py-2 select-none"
aria-hidden="true"
>
{captcha}
</div>
<button
type="button"
onClick={generateCaptcha}
className="text-sm text-[#92722A] hover:underline"
>
Refresh
</button>
</div>
<input
type="text"
name="captcha"
value={userCaptcha}
onChange={handleCaptchaChange}
placeholder="Enter the code shown above"
className={`mt-2 block w-full h-10 rounded-md border-2 ${
captchaError ? "border-red-500" : "border-[#92722A]"
} focus:border-[#92722A] focus:ring-0 px-4 text-sm bg-white`}
/>
{captchaError && <p className="text-xs text-red-600 mt-1">{captchaError}</p>}
</div>
<button
type="submit"
disabled={!isValid || loading || !userCaptcha}
className={`inline-flex items-center justify-center w-full h-12 rounded-lg text-white ${
!isValid || loading || !userCaptcha
? "bg-[#bfa06a] cursor-not-allowed"
: "bg-[#92722A] hover:bg-[#7b5c1f]"
} transition-colors`}
>
{loading ? "Submitting…" : "Submit"}
</button>
<button
type="button"
onClick={() => navigate(-1)}
className="w-full h-10 rounded-md border border-[#92722A] text-[#92722A] hover:bg-[#92722A]/10 text-sm"
>
Cancel
</button>
</form>
) : (
<div className="px-7 py-8 space-y-4">
{otpMsg && (
<div className="text-sm text-green-700 bg-green-50 border border-green-200 rounded px-3 py-2">
{otpMsg}
</div>
)}
<InputField
label="Verification Code"
name="otp"
value={otp}
onChange={(e) => setOtp(e.target.value)}
placeholder="Enter the 6-digit code"
error={otpError}
/>
<div className="flex gap-3">
<button
type="button"
onClick={generateCaptcha}
className="text-sm text-[#92722A] hover:underline"
onClick={handleConfirmOtp}
className="flex-1 h-10 rounded-md bg-[#92722A] text-white hover:bg-[#7b5c1f] text-sm"
>
Refresh
Confirm
</button>
<button
onClick={handleResendOtp}
className="flex-1 h-10 rounded-md border border-[#92722A] text-[#92722A] hover:bg-[#92722A]/10 text-sm"
>
Resend
</button>
</div>
{/* Accessible alternative */}
<p className="text-xs text-gray-500 mt-1">
If you cannot read the code, click "Refresh" or type the following:{" "}
<span className="font-mono">{captcha}</span>
</p>
<input
type="text"
name="captcha"
value={userCaptcha}
onChange={handleCaptchaChange}
placeholder="Enter the code shown above"
className={`mt-2 block w-full h-10 rounded-md border-2 ${
captchaError ? "border-red-500" : "border-[#92722A]"
} focus:border-[#92722A] focus:ring-0 px-4 text-sm bg-white`}
/>
{captchaError && (
<p className="text-xs text-red-600 mt-1">{captchaError}</p>
)}
</div>
{/* Submit */}
<button
type="submit"
disabled={!isValid || loading || !userCaptcha}
className={`inline-flex items-center justify-center w-full h-12 rounded-lg text-white ${
!isValid || loading || !userCaptcha
? "bg-[#bfa06a] cursor-not-allowed"
: "bg-[#92722A] hover:bg-[#7b5c1f]"
} transition-colors`}
>
{loading ? "Submitting…" : "Submit"}
</button>
<button
type="button"
onClick={() => navigate(-1)}
className="w-full h-10 rounded-md border border-[#92722A] text-[#92722A] hover:bg-[#92722A]/10 text-sm"
>
Cancel
</button>
</form>
)}
</div>
</div>
</div>
);
};
// Input component
const InputField = ({ label, name, value, onChange, placeholder, required, error, type = "text" }) => (
const InputField = ({
label,
name,
value,
onChange,
placeholder,
required,
error,
type = "text",
}) => (
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
{label} {required && <span className="text-red-500">*</span>}