finish login, logout, session context

This commit is contained in:
afazio1
2024-04-11 16:48:58 -04:00
parent c89b282e9a
commit 16c8e4377b
5 changed files with 121 additions and 53 deletions

View File

@@ -1,31 +1,56 @@
import "./styles/App.css";
import { Link } from 'react-router-dom';
import { Link, useNavigate } from 'react-router-dom';
import MainSearch from './components/MainSearch';
import { SessionContext, destroySessionCookie, getSessionCookie } from "./contexts/session";
import { useState, useEffect, useContext } from "react";
export default function App() {
const [session, setSession] = useState(getSessionCookie());
const navigate = useNavigate();
// Redirect to login if session is undefined
useEffect(
() => {
setSession(getSessionCookie());
if (session === undefined) {
navigate("/login");
}
},
[session, navigate]
);
return (
<>
<Navbar />
<div className="App" style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', height: '90vh' , gap: 15}}>
<img
src="/PeerNotes.png"
alt="PeerNotes Logo"
style={{
height: "100px"
}}
/>
<MainSearch />
</div>
<SessionContext.Provider value={session}>
<Navbar />
<div className="App" style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', height: '90vh' , gap: 15}}>
<img
src="/PeerNotes.png"
alt="PeerNotes Logo"
style={{
height: "100px"
}}
/>
<MainSearch />
</div>
</SessionContext.Provider>
</>
)
}
function Navbar() {
const session = useContext(SessionContext);
const links = session ? (
<>
<Link to="/">Home</Link>
<Link to="/login" onClick={destroySessionCookie}>Logout</Link>
</>
): (
<Link to="/login">Login</Link>
)
return (
<nav>
<Link to="/">Home</Link>
<Link to="/logout">Logout</Link>
{links}
</nav>
);
}

View File

@@ -0,0 +1,17 @@
import React from "react";
type SessionContextType = string | undefined;
export const getSessionCookie = () => {
const sessionCookie = document.cookie
.split('; ')
.find(row => row.startsWith('token='))
?.split('=')[1];
return sessionCookie;
}
export const destroySessionCookie = () => {
document.cookie = "token=; Max-Age=0;"
}
export const SessionContext = React.createContext<SessionContextType>(getSessionCookie());

View File

@@ -0,0 +1,14 @@
import { useEffect, useContext } from "react";
import { useNavigate } from "react-router-dom";
import { SessionContext } from "../contexts/session";
export const useSessionRedirect = () => {
const session = useContext(SessionContext);
const navigate = useNavigate();
// Redirect to home if session is defined
useEffect(() => {
if (session !== undefined) {
navigate('/');
}
}, [session, navigate])
}

View File

@@ -1,40 +1,48 @@
import { Link } from "react-router-dom"
import { Link, useNavigate } from "react-router-dom"
import "../styles/Login.css"
import { FormEvent } from "react";
import { useSessionRedirect } from "../hooks/sessionRedirect";
export default function Login() {
function handleSubmit(e: FormEvent) {
e.preventDefault();
const formData = new FormData(e.target as HTMLFormElement);
const username = formData.get('username');
const password = formData.get('password');
fetch('http://localhost:8000/api/login/', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password }),
})
.catch((error) => {
console.error('Error:', error);
});
}
return (
<main>
<form className="login-container" onSubmit={handleSubmit}>
<h1>Login</h1>
<div className="form-input">
<label htmlFor="username">Username</label>
<input type="text" name="username" id="username" />
</div>
<div className="form-input">
<label htmlFor="password">Password</label>
<input type="password" name="password" id="password" />
</div>
<button className="submit-button">Login</button>
<p>or <Link to="/signup">Sign up</Link></p>
</form>
</main>
);
const navigate = useNavigate();
useSessionRedirect();
function handleSubmit(e: FormEvent) {
e.preventDefault();
const formData = new FormData(e.target as HTMLFormElement);
const username = formData.get('username');
const password = formData.get('password');
fetch('http://localhost:8000/api/login/', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password }),
})
.then(() => {
navigate('/');
})
.catch((error) => {
console.error('Error:', error);
});
}
return (
<main>
<form className="login-container" onSubmit={handleSubmit}>
<h1>Login</h1>
<div className="form-input">
<label htmlFor="username">Username</label>
<input type="text" name="username" id="username" />
</div>
<div className="form-input">
<label htmlFor="password">Password</label>
<input type="password" name="password" id="password" />
</div>
<button className="submit-button">Login</button>
<p>or <Link to="/signup">Sign up</Link></p>
</form>
</main>
);
}

View File

@@ -1,7 +1,11 @@
import { Link } from "react-router-dom";
import { Link, useNavigate } from "react-router-dom";
import "../styles/Login.css"
import { FormEvent } from "react";
import { useSessionRedirect } from "../hooks/sessionRedirect";
export default function Signup() {
const navigate = useNavigate();
useSessionRedirect();
function handleSubmit(e: FormEvent) {
e.preventDefault();
const formData = new FormData(e.target as HTMLFormElement);
@@ -16,8 +20,8 @@ export default function Signup() {
body: JSON.stringify({ email, username, password }),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
.then(() => {
navigate('/login');
})
.catch((error) => {
console.error('Error:', error);