import React, { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import { all_routes } from "../router/all_routes";
import {
checkAuthAccess,
DecodeToken,
loginUser,
showLockCountdownToast,
} from "../../api/authService";
import { useDispatch } from "react-redux";
import { login } from "../../core/data/redux/authSlice";
import { toast } from "react-toastify";
import {
setupAutoLogoutWatcher,
setupRefreshTokenWatcher,
} from "../../api/token";
import { checkRazorpayAccess } from "../../api/razorpay";
import { startAutoLockWatcher } from "../../api/autolock";
const slides = [
// { img: "/assets/img/loginpage.png", text: "Track Leads Faster" },
// { img: "/assets/img/loginpage2.jpeg", text: "Sales Pipeline" },
// { img: "/assets/img/loginpage3.png", text: "Workflow Automation" },
// { img: "/assets/img/loginpage4.png", text: "Multi-User CRM" },
// { img: "/assets/img/loginpage5.png", text: "Analytics & Reporting" },
{ img: "/assets/img/authentication/email-img.png", text: "Analytics & Reporting" },
{ img: "/assets/img/authentication/login-img.png", text: "Analytics & Reporting" },
{ img: "/assets/img/authentication/register-img.png", text: "Analytics & Reporting" },
{ img: "/assets/img/authentication/success-img.png", text: "Analytics & Reporting" },
{ img: "/assets/img/authentication/verify-img.png", text: "Analytics & Reporting" },
];
const LeftImage = () => {
const [randomImage, setRandomImage] = useState(slides[0].img);
useEffect(() => {
const rand = Math.floor(Math.random() * slides.length);
setRandomImage(slides[rand].img);
}, []);
return (
);
};
const Login: React.FC = () => {
const navigate = useNavigate();
const dispatch = useDispatch();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [rememberMe, setRememberMe] = useState(false);
const [isPasswordVisible, setPasswordVisible] = useState(false);
const [emailError, setEmailError] = useState("");
const [passwordError, setPasswordError] = useState("");
const [loading, setLoading] = useState(false);
useEffect(() => {
const styleId = "animated-badge-keyframes";
if (!document.getElementById(styleId)) {
const styleSheet = document.createElement("style");
styleSheet.id = styleId;
styleSheet.innerText = `
@keyframes shine {
0% {
transform: skewX(-20deg) translateX(-150%);
}
50% {
transform: skewX(-20deg) translateX(150%);
}
100% {
transform: skewX(-20deg) translateX(150%);
}
}
`;
document.head.appendChild(styleSheet);
}
}, []);
useEffect(() => {
setLoading(false);
setEmail("");
setPassword("");
setEmailError("");
setPasswordError("");
setRememberMe(false);
}, []);
useEffect(() => {
const token = localStorage.getItem("authToken");
const role = localStorage.getItem("role");
if (window.location.pathname === "/login" && token && role) {
if (role === "superadmin") {
navigate(all_routes.superadminDashboard, { replace: true });
} else if (role === "client") {
navigate(all_routes.manageusers, { replace: true });
} else if (role === "admin") {
navigate(all_routes.dealsDashboard, { replace: true });
} else {
navigate(all_routes.leadsDashboard, { replace: true });
}
}
}, [navigate]);
// EMAIL VALIDATION - Live on every change
const validateEmail = (value: string) => {
const trimmed = value.trim();
if (!trimmed) return "Email is required";
if (/[A-Z]/.test(trimmed)) {
return "Email must be in lowercase only";
}
if (trimmed.length > 100) return "Email must not exceed 100 characters";
if (/\s{2,}/.test(value)) return "Email cannot contain consecutive spaces";
if (/<[^>]*>/g.test(value))
return "Email cannot contain HTML or script tags";
const allowedCharsRegex = /^[A-Za-z0-9@$&\/\-_. ,]+$/;
if (!allowedCharsRegex.test(value))
return "Email contains invalid special characters";
if (/^\d+$/.test(trimmed)) return "Email cannot contain only numbers";
if (/^[^A-Za-z0-9]+$/.test(trimmed))
return "Email cannot contain only symbols";
if (/(.)\1{4,}/.test(trimmed))
return "Email contains too many repeated characters";
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(trimmed)) return "Enter a valid email address";
const blockedDomains = [
"tempmail.com",
"10minutemail.com",
"mailinator.com",
];
const domain = trimmed.split("@")[1]?.toLowerCase();
if (domain && blockedDomains.includes(domain))
return "Temporary email addresses are not allowed";
const localPart = trimmed.split("@")[0];
if (/^[._-]|[._-]$/.test(localPart))
return "Email cannot start or end with special characters";
if (/\.\./.test(trimmed)) return "Email cannot contain consecutive dots";
return "";
};
// PASSWORD VALIDATION - Live on every change
const validatePassword = (value: string) => {
if (!value) return "Password is required";
if (value.length < 8) return "Password must be at least 8 characters";
if (value.length > 50) return "Password must not exceed 50 characters";
if (!/[A-Z]/.test(value))
return "Password must contain at least one uppercase letter";
if (!/[a-z]/.test(value))
return "Password must contain at least one lowercase letter";
if (!/\d/.test(value)) return "Password must contain at least one number";
if (!/[@$!%*?&]/.test(value))
return "Password must contain at least one special character (@$!%*?&)";
if (/\s{2,}/.test(value))
return "Password cannot contain consecutive spaces";
if (/(.)\1{5,}/.test(value))
return "Password contains too many repeated characters";
return "";
};
const handleEmailChange = (e: React.ChangeEvent) => {
const value = e.target.value;
setEmail(value);
setEmailError(validateEmail(value)); // Live validation
};
const handlePasswordChange = (e: React.ChangeEvent) => {
const value = e.target.value;
setPassword(value);
setPasswordError(validatePassword(value)); // Live validation
};
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
const emailErr = validateEmail(email);
const passErr = validatePassword(password);
setEmailError(emailErr);
setPasswordError(passErr);
if (emailErr || passErr) {
if (emailErr) toast.error(emailErr);
if (passErr) toast.error(passErr);
return;
}
setLoading(true);
try {
const data = await loginUser(
email.trim().toLowerCase(),
password,
rememberMe
);
if (!data.access_token) {
toast.error("Invalid credentials");
setLoading(false);
return;
}
// FIXED: Store full "Bearer xxx" token
const fullToken = `Bearer ${data.access_token}`;
localStorage.setItem("authToken", fullToken);
//const userInfo = await DecodeToken();
const userInfo = await checkAuthAccess();
// Save user info
Object.entries(userInfo).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
localStorage.setItem(key, String(value));
}
});
Object.entries(userInfo).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
localStorage.setItem(key, String(value));
}
});
if (rememberMe) {
localStorage.setItem("remember_me", "true");
} else {
localStorage.removeItem("remember_me");
}
dispatch(
login({
token: fullToken,
refreshToken: data.refresh_token ?? "",
role: userInfo.role,
client_id: userInfo.client_id,
user_id: userInfo.user_id,
e_mail: userInfo.email,
username: userInfo.username,
})
);
//setupRefreshTokenWatcher();
// Set up auto logout watcher after login
if (userInfo.expires_at) {
setupAutoLogoutWatcher();
}
const userRole = userInfo.role;
// Superadmin → always allowed
if (userRole === "superadmin") {
navigate(all_routes.superadminDashboard,{ replace: true });
return;
}
// Client → special handling
if (userRole === "client") {
if (userInfo.access) {
navigate(all_routes.manageusers,{ replace: true });
} else {
navigate(all_routes.payments,{ replace: true });
}
return;
}
if (!userRole) {
toast.error("Invalid session. Please login again.");
return;
}
// 🔒 Admin & others → must have access
if (!userInfo.access) {
toast.error("You don't have an active subscription, Contact admin.");
return; // ⛔ stay on login
}
toast.success("Login successfully");
// ✅ Access granted
if (userRole === "admin") {
navigate(all_routes.dealsDashboard, { replace: true });
} else {
navigate(all_routes.leadsDashboard, { replace: true });
}
startAutoLockWatcher(navigate);
} catch (err: any) {
const message = err.message || "Login failed";
const match = message.match(/after\s+(\d+)\s*minute/i);
if (match) {
const minutes = parseInt(match[1], 10);
showLockCountdownToast(minutes);
return;
}
// ⚠️ Password reset required → WARNING
if (err?.type === "warning") {
toast.warning(message, {
autoClose: 6000,
});
return;
}
// ❌ Default error
toast.error(message);
} finally {
setLoading(false);
}
};
return (
{/* LEFT SIDE IMAGE */}
{/* RIGHT SIDE CARD */}
{/* STYLES - Fixed layout collapse */}
);
};
export default Login;