#25 Refactor login and logout requests to utils file #26

Merged
juggy1233 merged 2 commits from #25-request-refactor into master 2023-03-21 12:27:28 -04:00
6 changed files with 126 additions and 35 deletions

View File

@@ -12,7 +12,7 @@ const AuthenticatedRoute = ({ children, isAuthenticated }) => {
} else if (!isAuthenticated && currentUser?.id) { } else if (!isAuthenticated && currentUser?.id) {
setLocation("/"); setLocation("/");
} }
}, [currentUser]); }, [currentUser, setLocation, isAuthenticated]);
return children; return children;
}; };

View File

@@ -0,0 +1,52 @@
import { Card, Container } from "react-bootstrap";
import { Link } from "wouter";
const CoursesWidget = ({ className = "" }) => {
const dummyData = [
{
course_id: 1,
course_title: "Advanced Website Design",
couse_code: "COMP 2707",
instructor: "Saja Al Mamoori",
},
{
course_id: 2,
course_title: "Introduction to Roman Civilization",
couse_code: "GRST 1200",
instructor: "Max Nelson",
},
{
course_id: 3,
course_title: "Software Verification and Testing",
couse_code: "COMP 4110",
instructor: "Serif Saad",
},
{
course_id: 1,
course_title: "Advanced Website Design",
couse_code: "COMP 2707",
instructor: "Saja Al Mamoori",
},
];
return (
<Container
className={`${className} py-3 d-flex flex-wrap justify-content-around`}
>
{dummyData.map((course, i) => {
return (
<Link is="a" key={i} href={`/course/${course.course_id}`}>
<Card role="button" className="m-2" style={{ width: "300px" }}>
<h2 className="text-center py-5 border">{course.couse_code}</h2>
<Card.Body>
<Card.Title>{course.course_title}</Card.Title>
<Card.Text>{course.instructor}</Card.Text>
</Card.Body>
</Card>
</Link>
);
})}
</Container>
);
};
export default CoursesWidget;

View File

@@ -1,5 +1,6 @@
import { useContext } from "react"; import { useContext } from "react";
import { Container } from "react-bootstrap"; import { Container } from "react-bootstrap";
import CoursesWidget from "../components/CoursesWidget";
import MyNavbar from "../components/MyNavbar"; import MyNavbar from "../components/MyNavbar";
import UserContext from "../contexts/UserContext"; import UserContext from "../contexts/UserContext";
@@ -13,6 +14,13 @@ const HomePage = () => {
<div> <div>
<h1>Welcome back {currentUser?.username}!</h1> <h1>Welcome back {currentUser?.username}!</h1>
</div> </div>
<br />
<br />
<br />
<div>
<h2>Courses</h2>
<CoursesWidget className="ms-0 w-75 border" />
</div>
</Container> </Container>
</div> </div>
); );

View File

@@ -3,7 +3,7 @@ import { Button, Col, Container, Form, Row, Alert } from "react-bootstrap";
import { Link, useLocation } from "wouter"; import { Link, useLocation } from "wouter";
import MyNavbar from "../components/MyNavbar"; import MyNavbar from "../components/MyNavbar";
import UserContext from "../contexts/UserContext"; import UserContext from "../contexts/UserContext";
import { makeRequest } from "../utils.ts"; import { sendLogoutRequest, sendLoginRequest } from "../utils.ts";
const LoginPage = () => { const LoginPage = () => {
const [username, setUsername] = useState(""); const [username, setUsername] = useState("");
@@ -15,29 +15,28 @@ const LoginPage = () => {
useEffect(() => { useEffect(() => {
if (currentUser?.id) { if (currentUser?.id) {
gotoHome(); setLocation("/");
} }
}, [currentUser]); }, [currentUser, setLocation]);
const gotoHome = () => { const formCb = async (e) => {
setLocation("/");
};
const sendLoginRequest = async (e) => {
e?.preventDefault(); e?.preventDefault();
await makeRequest({ const res = await sendLoginRequest(username, password);
url: "http://localhost:5000/login",
method: "POST", if (res?.isError) {
body: { username, password }, if (res.message.includes("already")) {
}) setError({
.then((resp) => resp.json()) ...res,
.then((data) => { message: "An error occured. Try logging in again.",
if (data.error) { });
setError(data); await sendLogoutRequest();
return; return;
} }
setCurrentUser(data); setError(res);
}); return;
}
setCurrentUser(res);
setLocation("/");
}; };
return ( return (
@@ -53,7 +52,7 @@ const LoginPage = () => {
)} )}
<h2>Login</h2> <h2>Login</h2>
<br /> <br />
<Form onSubmit={sendLoginRequest}> <Form onSubmit={formCb}>
<Form.Group as={Row} className="mb-3" controlId="username"> <Form.Group as={Row} className="mb-3" controlId="username">
<Form.Label column sm={2} className="me-2"> <Form.Label column sm={2} className="me-2">
Username Username

View File

@@ -3,23 +3,18 @@ import { useContext, useEffect } from "react";
import { Container } from "react-bootstrap"; import { Container } from "react-bootstrap";
import MyNavbar from "../components/MyNavbar"; import MyNavbar from "../components/MyNavbar";
import UserContext from "../contexts/UserContext"; import UserContext from "../contexts/UserContext";
import { makeRequest } from "../utils.ts"; import { sendLogoutRequest } from "../utils.ts";
const LogoutPage = () => { const LogoutPage = () => {
const { setCurrentUser } = useContext(UserContext); const { setCurrentUser } = useContext(UserContext);
useEffect(() => { useEffect(() => {
const cleanup = async () => { (async () => {
await makeRequest({ await sendLogoutRequest();
url: "http://localhost:5000/logout",
method: "POST",
});
await setCurrentUser({}); await setCurrentUser({});
localStorage.removeItem("currentUser"); localStorage.removeItem("currentUser");
window.location.href = "/login"; window.location.href = "/login";
}; })();
cleanup(); }, [setCurrentUser]);
}, []);
return ( return (
<React.Fragment> <React.Fragment>

View File

@@ -1,4 +1,4 @@
const makeRequest = ({ url, method, body }): Promise<Response> => { const makeRequest = ({ url, method, body = {} }): Promise<Response> => {
return fetch(url, { return fetch(url, {
method: method, method: method,
credentials: "include", credentials: "include",
@@ -8,4 +8,41 @@ const makeRequest = ({ url, method, body }): Promise<Response> => {
}); });
}; };
export { makeRequest }; const sendLoginRequest = async (
username: string,
password: string
): Promise<object> => {
const p: Promise<object> = new Promise(async (res) => {
await makeRequest({
url: "http://localhost:5000/login",
method: "POST",
body: { username, password },
})
.then((resp) => resp.json())
.then((data) => {
if (data.error) {
res({ isError: true, ...data });
}
res({ isError: false, ...data });
});
res({ isError: true });
});
return p;
};
const sendLogoutRequest = async (): Promise<object> => {
const p: Promise<object> = new Promise(async (res) => {
await makeRequest({
url: "http://localhost:5000/logout",
method: "POST",
})
.then((resp) => resp.json())
.then((data) => {
res({ isError: false, ...data });
});
res({ isError: true });
});
return p;
};
export { makeRequest, sendLoginRequest, sendLogoutRequest };