From e14b5ba9e63733645fdd2e672459ad3c8ddd9465 Mon Sep 17 00:00:00 2001 From: trinity-y Date: Thu, 28 Nov 2024 22:00:41 -0500 Subject: [PATCH] refactor login + redirect to create password page --- frontend/src/components/auth/Login.tsx | 101 +++++++++++++------------ 1 file changed, 53 insertions(+), 48 deletions(-) diff --git a/frontend/src/components/auth/Login.tsx b/frontend/src/components/auth/Login.tsx index bc58407..2ad1e14 100644 --- a/frontend/src/components/auth/Login.tsx +++ b/frontend/src/components/auth/Login.tsx @@ -1,79 +1,84 @@ -import React, { useContext, useState } from "react"; +import React, { useContext, useState, useEffect } from "react"; import { Redirect } from "react-router-dom"; import { isSignInWithEmailLink } from "firebase/auth"; import auth from "../../firebase/firebase"; import authAPIClient from "../../APIClients/AuthAPIClient"; -import { HOME_PAGE } from "../../constants/Routes"; +import { CREATE_PASSWORD_PAGE, HOME_PAGE } from "../../constants/Routes"; import AuthContext from "../../contexts/AuthContext"; import { AuthenticatedUser } from "../../types/AuthTypes"; -let didInit = false; - const Login = (): React.ReactElement => { const { authenticatedUser, setAuthenticatedUser } = useContext(AuthContext); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); - const onLogInClick = async () => { - const user: AuthenticatedUser = await authAPIClient.login(email, password); - setAuthenticatedUser(user); - }; - const checkIfSignInLink = async () => { - if (!authenticatedUser) { + const [redirectTo, setRedirectTo] = useState(null); + + useEffect(() => { + const checkIfSignInLink = async () => { const url = window.location.href; const urlSearchParams = new URLSearchParams(window.location.search); const signInEmail = urlSearchParams.get("email"); // passed in from actionCode const isSignInLink = isSignInWithEmailLink(auth, url); + if (signInEmail && isSignInLink) { const user: AuthenticatedUser = await authAPIClient.loginWithSignInLink( url, signInEmail, ); setAuthenticatedUser(user); + setRedirectTo(CREATE_PASSWORD_PAGE); } + }; + + if (authenticatedUser) { + setRedirectTo(HOME_PAGE); + } else { + checkIfSignInLink(); } - // alert: user is already logged in, please log out before trying again - }; + }, [authenticatedUser, setAuthenticatedUser]); - if (authenticatedUser) { - return ; + if (redirectTo) { + return ; } - if (!didInit) { - didInit = true; - checkIfSignInLink(); - } + const onLogInClick = async () => { + const user: AuthenticatedUser = await authAPIClient.login(email, password); + setAuthenticatedUser(user); + }; return ( -
-

Login

-
-
- setEmail(event.target.value)} - placeholder="username@domain.com" - /> -
-
- setPassword(event.target.value)} - placeholder="password" - /> -
-
- -
-
-
+ <> +
+

Login

+
+
+ setEmail(event.target.value)} + placeholder="username@domain.com" + /> +
+
+ setPassword(event.target.value)} + placeholder="password" + /> +
+
+ +
+
+
+ ); };