Save auth in localstorage and use it

Also consistently call it "email".
This commit is contained in:
Eli Ribble 2024-08-27 11:11:54 -07:00
parent 34ea77f7c3
commit 913856c11b
2 changed files with 24 additions and 16 deletions

View File

@ -7,18 +7,28 @@ import AuthModal from "./AuthModal";
import React, { useEffect, useState } from "react";
interface IAuth {
email: string;
password: string;
username: string;
}
const App = () => {
const [state, setInternalState] = useState<IAuth | null>(null);
const doLogin = (email: string, password: string) => {
const domain = email.split("@")[1];
// When the user provides credentials
const onLogin = (email: string, password: string) => {
// Store the provided credentials for now
const auth = {email: email, password: password}
setInternalState(auth);
localStorage.setItem("auth", JSON.stringify(auth));
doLogin(auth);
};
// Make the request to get system metadata
const doLogin = (auth: IAuth) => {
const domain = auth.email.split("@")[1];
const well_known_url = "https://" + domain + "/.well-known/jmap"
let headers = new Headers();
headers.append("Authorization", "Basic " + base64.encode(email + ":" + password));
headers.append("Authorization", "Basic " + base64.encode(auth.email + ":" + auth.password));
fetch(well_known_url, {
method: "GET",
headers: headers,
@ -27,24 +37,22 @@ const App = () => {
.then(data => console.log(data))
.catch(error => console.error(error));
};
const loadAuth = () => {
const auth = localStorage.getItem("auth");
if (!auth) return;
setInternalState(JSON.parse(auth));
};
const setState = (auth: IAuth) => {
localStorage.setItem("auth", JSON.stringify(auth));
const loadAuth = () => {
const data = localStorage.getItem("auth");
if (!data) return;
const auth = JSON.parse(data);
setInternalState(auth);
doLogin(auth);
};
useEffect(() => {
loadAuth();
//fetchUserData()
}, []);
return (
<div className="App">
{state ? <p>{state.username}</p> : <AuthModal doLogin={doLogin}></AuthModal>}
{state ? <p>{state.email}</p> : <AuthModal onLogin={onLogin}></AuthModal>}
</div>
);
};

View File

@ -5,10 +5,10 @@ import Modal from "react-bootstrap/Modal"
import React, {useState} from "react"
type AuthProps = {
doLogin: (email: string, password: string) => void;
onLogin: (email: string, password: string) => void;
}
const AuthModal: React.FC<AuthProps> = ({ doLogin }) => {
const AuthModal: React.FC<AuthProps> = ({ onLogin }) => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
@ -23,7 +23,7 @@ const AuthModal: React.FC<AuthProps> = ({ doLogin }) => {
</Modal.Header>
<Modal.Body>
<Form onSubmit={(e) => {e.preventDefault(); doLogin(email, password)}}>
<Form onSubmit={(e) => {e.preventDefault(); onLogin(email, password)}}>
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" placeholder="Enter email" onChange={e => setEmail(e.target.value)}/>