import { createSignal, createEffect, onCleanup, Show } from "solid-js"; import { A, useNavigate, useSearchParams, redirect, query } from "@solidjs/router"; import { Title, Meta } from "@solidjs/meta"; import { getEvent } from "vinxi/http"; import GoogleLogo from "~/components/icons/GoogleLogo"; import GitHub from "~/components/icons/GitHub"; import Eye from "~/components/icons/Eye"; import EyeSlash from "~/components/icons/EyeSlash"; import CountdownCircleTimer from "~/components/CountdownCircleTimer"; import PasswordStrengthMeter from "~/components/PasswordStrengthMeter"; import { isValidEmail, validatePassword } from "~/lib/validation"; import { getClientCookie } from "~/lib/cookies.client"; import { env } from "~/env/client"; import { VALIDATION_CONFIG, COUNTDOWN_CONFIG } from "~/config"; const checkAuth = query(async () => { "use server"; const { checkAuthStatus } = await import("~/server/utils"); const event = getEvent()!; const { isAuthenticated } = await checkAuthStatus(event); if (isAuthenticated) { throw redirect("/account"); } return { isAuthenticated }; }, "loginAuthCheck"); export const route = { load: () => checkAuth() }; export default function LoginPage() { const navigate = useNavigate(); const [searchParams] = useSearchParams(); const register = () => searchParams.mode === "register"; const usePassword = () => searchParams.auth === "password"; const [error, setError] = createSignal(""); const [loading, setLoading] = createSignal(false); const [countDown, setCountDown] = createSignal(0); const [emailSent, setEmailSent] = createSignal(false); const [showPasswordError, setShowPasswordError] = createSignal(false); const [showPasswordSuccess, setShowPasswordSuccess] = createSignal(false); const [showPasswordInput, setShowPasswordInput] = createSignal(false); const [showPasswordConfInput, setShowPasswordConfInput] = createSignal(false); const [passwordsMatch, setPasswordsMatch] = createSignal(false); const [password, setPassword] = createSignal(""); const [passwordConf, setPasswordConf] = createSignal(""); let emailRef: HTMLInputElement | undefined; let passwordRef: HTMLInputElement | undefined; let passwordConfRef: HTMLInputElement | undefined; let rememberMeRef: HTMLInputElement | undefined; let timerInterval: number | undefined; const googleClientId = env.VITE_GOOGLE_CLIENT_ID; const githubClientId = env.VITE_GITHUB_CLIENT_ID; const domain = env.VITE_DOMAIN || "https://www.freno.me"; const calcRemainder = (timer: string) => { const expires = new Date(timer); const remaining = expires.getTime() - Date.now(); const remainingInSeconds = remaining / 1000; if (remainingInSeconds <= 0) { setCountDown(0); if (timerInterval) { clearInterval(timerInterval); } } else { setCountDown(remainingInSeconds); } }; createEffect(() => { const timer = getClientCookie("emailLoginLinkRequested"); if (timer) { timerInterval = setInterval( () => calcRemainder(timer), 1000 ) as unknown as number; } onCleanup(() => { if (timerInterval) { clearInterval(timerInterval); } }); }); createEffect(() => { const errorParam = searchParams.error; if (errorParam) { const errorMessages: Record = { missing_code: "OAuth authorization failed - missing code", auth_failed: "Authentication failed - please try again", server_error: "Server error - please try again later", missing_params: "Invalid login link - missing parameters", link_expired: "Login link has expired - please request a new one", access_denied: "Access denied - you cancelled the login", email_in_use: "This email is already associated with another account. Please sign in with that account instead." }; setError(errorMessages[errorParam] || "An error occurred during login"); } }); const formHandler = async (e: Event) => { e.preventDefault(); setLoading(true); setError(""); setShowPasswordError(false); setShowPasswordSuccess(false); try { if (register()) { if (!emailRef || !passwordRef || !passwordConfRef) { setError("Please fill in all fields"); setLoading(false); return; } const email = emailRef.value; const password = passwordRef.value; const passwordConf = passwordConfRef.value; if (!isValidEmail(email)) { setError("Invalid email address"); setLoading(false); return; } const passwordValidation = validatePassword(password); if (!passwordValidation.isValid) { setError(passwordValidation.errors[0] || "Invalid password"); setLoading(false); return; } if (password !== passwordConf) { setError("passwordMismatch"); setLoading(false); return; } const response = await fetch("/api/trpc/auth.emailRegistration", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, password, passwordConfirmation: passwordConf }) }); const result = await response.json(); if (response.ok && result.result?.data) { navigate("/account", { replace: true }); } else { const errorMsg = result.error?.message || result.result?.data?.message || "Registration failed"; const errorCode = result.error?.data?.code; if ( errorCode === "TOO_MANY_REQUESTS" || errorMsg.includes("Too many attempts") ) { setError(errorMsg); } else if ( errorMsg.includes("duplicate") || errorMsg.includes("already exists") ) { setError("duplicate"); } else { setError(errorMsg); } } } else if (usePassword()) { if (!emailRef || !passwordRef || !rememberMeRef) { setError("Please fill in all fields"); setLoading(false); return; } const email = emailRef.value; const password = passwordRef.value; const rememberMe = rememberMeRef.checked; const response = await fetch("/api/trpc/auth.emailPasswordLogin", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, password, rememberMe }) }); const result = await response.json(); if (response.ok && result.result?.data?.success) { setShowPasswordSuccess(true); setTimeout(() => { navigate("/account", { replace: true }); }, 500); } else { const errorMessage = result.error?.message || ""; const errorCode = result.error?.data?.code; if ( errorCode === "TOO_MANY_REQUESTS" || errorMessage.includes("Too many attempts") ) { setError(errorMessage); } else if ( errorCode === "FORBIDDEN" || errorMessage.includes("Account locked") || errorMessage.includes("Account is locked") ) { setError(errorMessage); } else { setShowPasswordError(true); } } } else { if (!emailRef || !rememberMeRef) { setError("Please enter your email"); setLoading(false); return; } const email = emailRef.value; const rememberMe = rememberMeRef.checked; if (!isValidEmail(email)) { setError("Invalid email address"); setLoading(false); return; } const response = await fetch("/api/trpc/auth.requestEmailLinkLogin", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, rememberMe }) }); const result = await response.json(); if (response.ok && result.result?.data?.success) { setEmailSent(true); const timer = getClientCookie("emailLoginLinkRequested"); if (timer) { if (timerInterval) { clearInterval(timerInterval); } timerInterval = setInterval( () => calcRemainder(timer), 1000 ) as unknown as number; } } else { const errorMsg = result.error?.message || result.result?.data?.message || "Failed to send email"; const errorCode = result.error?.data?.code; if ( errorCode === "TOO_MANY_REQUESTS" || errorMsg.includes("countdown not expired") || errorMsg.includes("Too many attempts") ) { setError( errorMsg.includes("countdown") ? "Please wait before requesting another email link" : errorMsg ); } else { setError(errorMsg); } } } } catch (err: any) { console.error("Login error:", err); setError(err.message || "An error occurred"); } finally { setLoading(false); } }; const renderTime = ({ remainingTime }: { remainingTime: number }) => { return (
{remainingTime.toFixed(0)}
); }; const checkForMatch = (newPassword: string, newPasswordConf: string) => { setPasswordsMatch(newPassword === newPasswordConf); }; const handlePasswordChange = (e: Event) => { const target = e.currentTarget as HTMLInputElement; setPassword(target.value); }; const handlePasswordConfChange = (e: Event) => { const target = e.currentTarget as HTMLInputElement; setPasswordConf(target.value); checkForMatch(password(), target.value); }; return ( <> Login | Michael Freno
Passwords did not match!
Email Already Exists!
🔒 Account Locked
{error()}
⏱️ Rate Limit Exceeded
{error()}
{error()}
{register() ? "Register" : "Login"}
Already have an account? Click here to Login
} >
Don't have an account yet? Click here to Register
= VALIDATION_CONFIG.MIN_PASSWORD_CONF_LENGTH_FOR_ERROR ? "" : "opacity-0 select-none" } text-red text-center transition-opacity duration-200 ease-in-out`} > Passwords do not match!
Remember Me
Credentials did not match any record Login Success! Redirecting...
0} fallback={ } > {renderTime} Use Password Use Email Link
Trouble Logging In?{" "} Reset Password
Email Sent!
Or
); }