diff --git a/src/components/AuthPages/Login/index2.jsx b/src/components/AuthPages/Login/index2.jsx new file mode 100644 index 0000000..98f59f6 --- /dev/null +++ b/src/components/AuthPages/Login/index2.jsx @@ -0,0 +1,591 @@ +import React, { useEffect, useLayoutEffect, useState } from "react"; +import { Link, useLocation, useNavigate } from "react-router-dom"; +import linkedInLogo from "../../../assets/images/Linkedin.png"; +import appleLogo from "../../../assets/images/apple-black.svg"; +import facebookLogo from "../../../assets/images/facebook-4.svg"; +import googleLogo from "../../../assets/images/google-logo.svg"; +import WrenchBoard from "../../../assets/images/wrenchboard-logo-text.png"; +import usersService from "../../../services/UsersService"; +import InputCom from "../../Helpers/Inputs/InputCom"; +import AuthLayout from "../AuthLayout"; +// import { GoogleOAuthProvider } from '@react-oauth/google'; +import { useGoogleLogin } from "@react-oauth/google"; + +import { useDispatch } from "react-redux"; +import { updateUserDetails } from "../../../store/UserDetails"; + +import ReCAPTCHA from "react-google-recaptcha"; + +export default function Login() { + // eslint-disable-next-line no-restricted-globals + const queryParams = new URLSearchParams(location?.search); + // const sessionExpired = queryParams.get("sessionExpired"); + + const dispatch = useDispatch(); + const { state } = useLocation(); + + const [sessionExpired, setSessionExpired] = useState(queryParams.get("sessionExpired")) + + const [validCaptcha, setValidCaptcha] = useState({ show: false, valid: "" }); // FOR CAPTCHA + + let [loginType, setLoginType] = useState(""); + + const [loginLoading, setLoginLoading] = useState(false); + + const [showPassword, setShowPassword] = useState(false); + + //login error state + const [loginError, setLoginError] = useState(false); + // for the catch error + const [msgError, setMsgError] = useState(""); + + // To Show and Hide Password + const togglePasswordVisibility = () => { + setShowPassword(!showPassword); + }; + + //FUNCTION TO DETERMINE/CHANGE LOGIN COMPONENT + const handleLoginType = ({ target: { name } }) => { + setLoginType(name); + let currentDate = new Date(); + let expirationDate = new Date(currentDate.getTime() + 24 * 60 * 60 * 1000); + // Convert the expiration date to the appropriate format + let expirationDateString = expirationDate.toUTCString(); + document.cookie = `loginType=${name}; expires=${expirationDateString}; path=/;`; + }; + + // email + const [email, setMail] = useState(""); + const handleEmail = (e) => { + setMail(e.target.value); + }; + // password + const [password, setPassword] = useState(""); + const handlePassword = (e) => { + setPassword(e.target.value); + }; + const navigate = useNavigate(); + const userApi = new usersService(); + + // FUNCTION TO HANDLE USER LOGIN + const doLogin = ({ target: { name } }) => { + setMsgError(""); + setLoginError(false); + setLoginLoading(true); + let postData; // Post Data for API + if (!email || !password) { + setLoginLoading(false); + setMsgError("Please fill all the fields"); + setTimeout(() => { + setMsgError(""); + }, Number(process.env.REACT_APP_LOGIN_ERROR_TIMEOUT)); + return; + } + + if (name == "full") { + //checks if email is a valid email address + let regEx = /^[^0-9][a-zA-Z0-9._%+-]+@[a-zA-Z]+(\.[a-zA-Z]+)+$/; + if (regEx.test(email) == false) { + setLoginLoading(false); + setMsgError("Invalid Email"); + return setTimeout(() => { + setMsgError(""); + }, 3000); + } + // Post Data Info for normal Login + postData = { + username: email, + password: password, + sessionid: "STARTING", + login_mode: 1100, + action: 11025, + }; + } else if (name == "family") { + // Post Data Info for family Login + postData = { + username: email, + pin: password, + sessionid: "20067A92714", + login_mode: 1105, + action: 11025, + }; + } else { + setLoginLoading(false); + setMsgError("Invalid Login Type. Consider refreshing the page"); + setTimeout(() => { + setMsgError(""); + }, Number(process.env.REACT_APP_LOGIN_ERROR_TIMEOUT)); + return; + } + if (name == "full" && !validCaptcha.valid && validCaptcha.show) { + // RUNS AND DISPLAYS CAPTCHA, IF ERROR OCCURED DURING LOGIN FOR FULL LOGIN ALONE + setMsgError("Please Verify Captcha"); + setLoginLoading(false); + setTimeout(() => { + setMsgError(""); + }, Number(process.env.REACT_APP_LOGIN_ERROR_TIMEOUT)); + return; + } + userApi + .logInUser(postData) + .then((res) => { + if ( + res.status != 200 || + res.data.internal_return < 0 || + !res.data.member_id || + !res.data.uid || + !res.data.session + ) { + // setMsgError("Wrong, email/password"); + setLoginError(true); + setLoginLoading(false); + setValidCaptcha((prev) => ({ ...prev, show: true })); // DISPLAYS CAPTCHA IF ERROR + return; + } + localStorage.setItem("member_id", `${res.data.member_id}`); + localStorage.setItem("uid", `${res.data.uid}`); + localStorage.setItem("session_token", `${res.data.session}`); + if (name === "family") { + sessionStorage.setItem("family_uid", res.data?.family_uid); + } + // localStorage.setItem("session", `${res.data.session}`); + dispatch(updateUserDetails({ ...res.data })); + setTimeout(() => { + navigate("/", { replace: true }); + setLoginLoading(false); + }, 2000); + }) + .catch((error) => { + setMsgError("Unable to login, try again"); + setLoginLoading(false); + setValidCaptcha((prev) => ({ ...prev, show: true })); // DISPLAYS CAPTCHA IF ERROR + }) + .finally(() => { + setTimeout(() => { + setLoginError(false); + setMsgError(""); + setLoginLoading(false); + }, Number(process.env.REACT_APP_LOGIN_ERROR_TIMEOUT)); + }); + }; + + function captchaChecker(value) { + // FUNCTION TO VALIDATE CAPTCHA + if (value) { + setValidCaptcha({ show: true, valid: value }); + } else { + setValidCaptcha({ show: true, valid: "" }); + } + } + + const googleLogin = useGoogleLogin({ + flow: "auth-code", + ux_mode: "redirect", + redirect_uri: process.env.REACT_APP_GOOGLE_REDIRECT_URL, + onSuccess: async (codeResponse) => { + console.log("GOOGLE LOGIN GOOD --- ", codeResponse); + }, + onError: (errorResponse) => console.log(errorResponse), + }); + + // In order to update the selected login type whenever the component renders + // useEffect(() => { + // Clear the loginType cookie if the user switches to loginfull + // document.cookie ="loginType=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; + // }, []); + + useLayoutEffect(() => { + // checks the cookie in order to set the login type before components mounts + // if(document.cookie.includes("loginType=family")){ + // setLoginType('family') + // }else if(document.cookie.includes("loginType=full")){ + // setLoginType('full') + // }else{ + // setLoginType('full') + // } + function readCookie(cname) { + // checks the cookie in order to set the login type before components mounts + let name = cname + "="; + let decoded_cookie = decodeURIComponent(document.cookie); + let carr = decoded_cookie.split(";"); + for (let i = 0; i < carr.length; i++) { + let c = carr[i]; + while (c.charAt(0) == " ") { + c = c.substring(1); + } + if (c.indexOf(name) == 0) { + return c.substring(name.length, c.length); + } + } + return "full"; + } + let loginValue = readCookie("loginType"); + setLoginType(loginValue); + + if (state?.error) { + //check if the login path has an error state indicating any social handle login with error + setMsgError("Unexpected Error, Please try again soon."); + setTimeout(() => { + setMsgError(""); + navigate("/login", { replace: true }); + }, 4000); + } + }, []); + + useEffect(() => { + setMail(""); + setPassword(""); + }, [loginType]); + + + // EFFECT TO CLEAR SESSION EXPIRY IF IT EXISTS AFTER SOME SECONDS + useEffect(()=>{ + let timer; + if(sessionExpired == "true"){ + timer = setTimeout(()=>{ + setSessionExpired(false) + },5000) + } + return () => { + clearTimeout(timer) + } + }, []) + + return ( + <> + +
+
+ + wrenchboard + +
+ {/*
*/} +
+
+ {/* HIDES THIS IF USER SESSION HAS EXPIRED */} + {sessionExpired != "true" && ( +
+ {/*

+ Sign In to WrenchBoard +

*/} + + New Here?{" "} + + Create an Account + + +
+ )} + + {/* SHOWS THIS IF USER SESSION HAS EXPIRED */} + {sessionExpired == "true" && ( +
+

+ Your session expired and will need to login again +

+
+ )} + + {/* switch login component */} +
+ + +
+ + {/* END of switch login component */} + + {/* for login component */} + { + loginType == "full" ? ( + //user login component +
+
+ +
+ +
+ +
+ + {/* hCaptha clone for the time being */} + {validCaptcha.show && ( +
+ +
+ )} + + {loginError && ( +
+ Invalid username or password- Please{" "} + + reset your password + {" "} + or{" "} + + create a new account + +
+ )} + {msgError && ( +
+ {msgError} +
+ )} +
+
+ +
+
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+
+ ) : ( + // END of user login compoenent + // family login compoenent +
+
+ +
+ +
+ +
+ {loginError && ( +
+ Invalid username or password{" "} + {/* + reset your password + {" "} + or{" "} + + create a new account + */} +
+ )} + {msgError && ( +
+ {msgError} +
+ )} +
+
+ +
+
+
+ ) + // END of family login compoenent + } + {/* END of login component */} + + {loginType == "full" && ( +
+ This site is protected by a Captcha. Our Privacy Policy and + Terms of Service apply. +
+ )} +
+
+
+ + + ); +} + +const BrandBtn = ({ + link, + imgSrc, + brand, + onClick, + isAnchor = false, + style = { visibility: "visible" }, +}) => { + // const doGoogle = async () => { + // alert("start google"); + // }; + + // onSuccess: (codeResponse) => setUser(codeResponse), + + // const doGoogle = useGoogleLogin({ + // onSuccess: (codeResponse) => console.log('Login onSuccess:', codeResponse), + // onError: (error) => console.log('Login Failed:', error) + // }); + + // const doApple = async () => { + // alert("start apple"); + // }; + + // const doFacebook = async () => { + // alert("start facebook"); + // }; + return ( +
+ {isAnchor ? ( + + logo-icon(s) + + Continue with {brand} + + + ) : ( + + )} +
+ ); +};