Skip to content

Commit

Permalink
Register & Login (#9)
Browse files Browse the repository at this point in the history
* comment out console.logs

* comment out failed attempt at making a custom hook

* remove dispatch to set provider in auth slice - edit router.push

* edit to use isConnected prop

* edit to use isConnected from redux state and pass to checkUserAuth

* add use of isConnected from redux state, clean up code

* move WatchPathname inside of store provider

* integrate web3auth, edit inputs, integrate redux state

* edit register page/form, integrate web3auth, edit inputs
  • Loading branch information
Spencer-Sch authored Dec 5, 2023
1 parent 641159b commit 8d936fc
Show file tree
Hide file tree
Showing 13 changed files with 400 additions and 127 deletions.
10 changes: 6 additions & 4 deletions packages/nextjs/auth/checkUserAuthentication.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { web3auth } from "~~/auth/web3auth";
// import { web3auth } from "~~/auth/web3auth";

export default function checkUserAuthentication(path: string) {
console.log("from checkUserAuthentication - Path = ", path);
export default function checkUserAuthentication(path: string, isConnected: boolean) {
// export default function checkUserAuthentication(path: string) {
// console.log("from checkUserAuthentication - Path = ", path);

const protectedRoutes = [
"/dapp/dashboard",
Expand All @@ -16,7 +17,8 @@ export default function checkUserAuthentication(path: string) {
"/dapp/integration",
];

if (!web3auth.connected && protectedRoutes.includes(path)) {
// if (!web3auth.connected && protectedRoutes.includes(path)) {
if (!isConnected && protectedRoutes.includes(path)) {
return false;
}
return true;
Expand Down
79 changes: 79 additions & 0 deletions packages/nextjs/auth/web3auth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
// import { useEffect, useState } from "react";
import { Web3Auth } from "@web3auth/modal";

// import { createWalletClient, custom } from "viem";
// import { polygonMumbai } from "viem/chains";
// import { AuthProvider, setAuthProvider, setIsConnected } from "~~/auth/authSlice";
// import { MyState, useMyDispatch, useMySelector } from "~~/components/dash-wind/app/store";

export const web3auth = new Web3Auth({
clientId: "BM0SLNkhMCfIygw0Xi79dG6qbWGMN0o0mEeDjRT0dxlP3BEok9pnu5aqxCNfj2TZ9XT7sQaXm0ltuWbCQ1tsRNI", // Get your Client ID from the Web3Auth Dashboard
web3AuthNetwork: "sapphire_devnet", // Web3Auth Network
Expand All @@ -21,3 +27,76 @@ export async function web3AuthInit() {
console.error(error);
}
}

// Failed attempt at making a custom hook
// Saving for future reference / another try
// export function useWeb3auth() {
// const [provider, setProvider] = useState<AuthProvider>(null);
// const [loggedIn, setLoggedIn] = useState(false);

// // useEffect(() => {
// // console.log(`web3auth useEffect - provider: ${!!provider} | loggedIn: ${isConnected}`);
// // }, [provider, isConnected]);
// // useEffect(() => {
// // console.log(`web3auth useEffect - provider: ${!!provider} | loggedIn: ${loggedIn}`);
// // }, [provider, loggedIn]);

// // async function web3AuthInit() {
// // console.log("web3Auth Init...");
// // try {
// // await web3auth.initModal();
// // console.log("web3AuthProvider - from init: ", web3auth.provider);
// // setProvider(web3auth.provider);

// // if (web3auth.connected) {
// // console.log("web3Auth Init connected?: ", web3auth.connected);
// // dispatch(setIsConnected({ isConnected: true }));
// // // setLoggedIn(true);
// // }
// // } catch (error) {
// // console.error(error);
// // }
// // }

// async function loginW3A() {
// try {
// const web3authProvider = await web3auth.connect();
// // dispatch(setAuthProvider({ provider: web3authProvider }));
// console.log("web3AuthProvider - from loginW3A: ", web3authProvider);
// setProvider(web3authProvider);
// if (web3auth.connected) {
// dispatch(setIsConnected({ isConnected: true }));
// console.log("web3Auth - loggedIn: ", loggedIn);
// setLoggedIn(true);
// }
// } catch (error) {
// console.error(error);
// }
// }

// async function logoutW3A() {
// await web3auth.logout();
// setProvider(null);
// setLoggedIn(false);
// console.log("logged out");
// }

// async function getAccountsW3A() {
// if (!provider) {
// // uiConsole("provider not initialized yet");
// console.log("from getAccountsW3A: provider not defined");
// return;
// }
// const client = createWalletClient({
// chain: polygonMumbai,
// transport: custom(provider),
// });

// // Get user's Ethereum public address
// const [address] = await client.getAddresses();
// // toast message?
// return address;
// }

// return { provider, loggedIn, web3AuthInit, loginW3A, logoutW3A, getAccountsW3A };
// }
5 changes: 2 additions & 3 deletions packages/nextjs/components/dash-wind/containers/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import Bars3Icon from "@heroicons/react/24/outline/Bars3Icon";
import BellIcon from "@heroicons/react/24/outline/BellIcon";
import MoonIcon from "@heroicons/react/24/outline/MoonIcon";
import SunIcon from "@heroicons/react/24/outline/SunIcon";
import { setAuthProvider, setIsConnected } from "~~/auth/authSlice";
import { setIsConnected } from "~~/auth/authSlice";
import { web3auth } from "~~/auth/web3auth";
// import UserIcon from "@heroicons/react/24/outline/UserIcon";
import { MyState, useMyDispatch, useMySelector } from "~~/components/dash-wind/app/store";
Expand Down Expand Up @@ -42,9 +42,8 @@ function Header() {

async function logoutUser() {
await web3auth.logout();
dispatch(setAuthProvider({ provider: null }));
dispatch(setIsConnected({ isConnected: false }));
router.push("/");
router.push("/login");
}

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ function Charts() {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const handleDatePickerValueChange = (newValue: DateValueType, e?: HTMLInputElement | null | undefined) => {
if (newValue !== null) {
console.log("newValue:", newValue);
// console.log("newValue:", newValue);
setDateValue(newValue);
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ function DashboardTopBar({ updateDashboardPeriod }: props) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const handleDatePickerValueChange = (newValue: DateValueType, e?: HTMLInputElement | null | undefined) => {
if (newValue !== null) {
console.log("newValue:", newValue);
// console.log("newValue:", newValue);
setDateValue(newValue);
updateDashboardPeriod(newValue);
}
Expand Down
73 changes: 28 additions & 45 deletions packages/nextjs/components/dash-wind/features/user/Login.tsx
Original file line number Diff line number Diff line change
@@ -1,58 +1,50 @@
import { useEffect, useState } from "react";
import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/router";
import InputText from "../../components/Input/InputText";
import ErrorText from "../../components/Typography/ErrorText";
import { UpdateFormValues } from "../../types/FormTypes";
import LandingIntro from "./LandingIntro";
import { setAuthProvider, setIsConnected } from "~~/auth/authSlice";
import { setIsConnected } from "~~/auth/authSlice";
import { web3auth } from "~~/auth/web3auth";
import { useMyDispatch } from "~~/components/dash-wind/app/store";
import { MyState, useMyDispatch, useMySelector } from "~~/components/dash-wind/app/store";

function Login() {
const INITIAL_LOGIN_OBJ = {
password: "",
contractAddress: "",
emailId: "",
};

const [loading, setLoading] = useState(false);
// const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
const [loginObj, setLoginObj] = useState(INITIAL_LOGIN_OBJ);
const { isConnected } = useMySelector((state: MyState) => state.auth);

const router = useRouter();
const dispatch = useMyDispatch();

// Web3Auth
useEffect(() => {
const init = async () => {
try {
const web3authProvider = await web3auth.connect();
dispatch(setAuthProvider({ provider: web3authProvider }));
if (web3auth.connected) {
dispatch(setIsConnected({ isConnected: true }));
}
async function login() {
if (isConnected) {
router.push("/dapp/dashboard");
}
try {
await web3auth.connect();
if (web3auth.connected) {
dispatch(setIsConnected({ isConnected: true }));
router.push("/dapp/dashboard");
} catch (error) {
console.error(error);
}
};
init();
});
} catch (error) {
console.error(error);
}
}

const submitForm = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setErrorMessage("");

if (loginObj.emailId.trim() === "") return setErrorMessage("Email Id is required! (use any value)");
if (loginObj.password.trim() === "") return setErrorMessage("Password is required! (use any value)");
else {
setLoading(true);
// Call API to check user credentials and save token in localstorage
localStorage.setItem("token", "DumyTokenHere");
setLoading(false);
router.push("/dapp/welcome");
// window.location.href = "/dapp/welcome";
}
if (loginObj.emailId.trim() === "") return setErrorMessage("Email is required!");
if (loginObj.contractAddress.trim() === "") return setErrorMessage("Contract Address is required!");
};

const updateFormValue = ({ updateType, value }: UpdateFormValues) => {
Expand All @@ -72,34 +64,25 @@ function Login() {
<form onSubmit={e => submitForm(e)}>
<div className="mb-4">
<InputText
type="emailId"
defaultValue={loginObj.emailId}
updateType="emailId"
defaultValue={loginObj.contractAddress}
updateType="contractAddress"
containerStyle="mt-4"
labelTitle="Email Id"
labelTitle="Contract Address"
updateFormValue={updateFormValue}
/>

<InputText
defaultValue={loginObj.password}
type="password"
updateType="password"
type="emailId"
defaultValue={loginObj.emailId}
updateType="emailId"
containerStyle="mt-4"
labelTitle="Password"
labelTitle="Email"
updateFormValue={updateFormValue}
/>
</div>

<div className="text-right text-primary">
<Link href="/forgot-password">
<span className="text-sm inline-block hover:text-primary hover:underline hover:cursor-pointer transition duration-200">
Forgot Password?
</span>
</Link>
</div>

<ErrorText styleClass="mt-8">{errorMessage}</ErrorText>
<button type="submit" className={"btn mt-2 w-full btn-primary" + (loading ? " loading" : "")}>
<button onClick={login} className="btn mt-2 w-full btn-primary">
Login
</button>

Expand Down
Loading

0 comments on commit 8d936fc

Please sign in to comment.