Commit 45e53639 by Madhankumar

auth guard removed

parent b6d296a7
{ {
"bookingSeats": [
[
0,
"A1",
"A2",
"A3",
0,
"A4",
"A5",
"A6",
0
],
[
"B1",
"B2",
"B3",
"B4",
0,
"B5",
"B6",
"B7",
"B8"
],
[
"C1",
"C2",
"C3",
"C4",
0,
"C5",
"C6",
"C7",
"C8"
],
[
"D1",
"D2",
"D3",
"D4",
0,
"D5",
"D6",
"D7",
"D8"
],
[
"E1",
"E2",
"E3",
"E4",
0,
"E5",
"E6",
"E7",
"E8"
],
[
"F1",
"F2",
"F3",
"F4",
0,
"F5",
"F6",
"F7",
"F8"
],
[
"G1",
"G2",
"G3",
"G4",
0,
"G5",
"G6",
"G7",
"G8"
],
[
0,
"H1",
"H2",
"H3",
0,
"H4",
"H5",
"H7",
0
]
],
"users": [ "users": [
{ {
"mobile": "9999999999", "mobile": "9999999999",
...@@ -7,23 +97,35 @@ ...@@ -7,23 +97,35 @@
{ {
"mobile": "9999999998", "mobile": "9999999998",
"id": 2 "id": 2
},
{
"mobile": "9999999997",
"id": 3
} }
], ],
"reservedSeats": [ "reservedSeats": [
{ {
"seats": [ "seats": [
"D8", "F4"
"F7"
], ],
"id": 1 "id": 1
}, },
{ {
"seats": [ "seats": [
"F2", "H2",
"F3", "H3",
"F1" "H1"
], ],
"id": 2 "id": 2
},
{
"seats": [
"G3",
"G2",
"G1",
"G4"
],
"id": 3
} }
] ]
} }
\ No newline at end of file
{ {
"name": "seat-book", "name": "seat-book",
"version": "0.1.0", "version": "1.1.0",
"private": true, "private": true,
"dependencies": { "dependencies": {
"@testing-library/jest-dom": "^5.17.0", "@testing-library/jest-dom": "^5.17.0",
......
...@@ -3,7 +3,6 @@ import { BrowserRouter as Router, Route, Routes } from "react-router-dom"; ...@@ -3,7 +3,6 @@ import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import { _Login } from "../src/pages/login"; import { _Login } from "../src/pages/login";
import { _Seatlayout } from "../src/pages/seat-layout"; import { _Seatlayout } from "../src/pages/seat-layout";
import { _Confirmation } from "../src/pages/confirmation"; import { _Confirmation } from "../src/pages/confirmation";
import { AuthGuard } from "./auth/index";
import { _seatLimit } from "../src/pages/seat-limit"; import { _seatLimit } from "../src/pages/seat-limit";
function App() { function App() {
...@@ -12,20 +11,11 @@ function App() { ...@@ -12,20 +11,11 @@ function App() {
<Router> <Router>
<Routes> <Routes>
<Route path="/" element={<_Login />} /> <Route path="/" element={<_Login />} />
<Route <Route path="/seat-limit" element={<_seatLimit />} />
path="/seat-limit" <Route path="/booking" element={<_Seatlayout />} />
element={<AuthGuard component={_seatLimit} />} <Route path="/confirmation" element={<_Confirmation />} />
/>
<Route
path="/booking"
element={<AuthGuard component={_Seatlayout} />}
/>
<Route
path="/confirmation"
element={<AuthGuard component={_Confirmation} />}
/>
{/* Default route */} {/* Default route */}
<Route path="*" element={_Login} /> <Route path="*" element={<_Login />} />
</Routes> </Routes>
</Router> </Router>
</div> </div>
......
...@@ -6,22 +6,18 @@ export const useAppContext = () => useContext(AppContext); ...@@ -6,22 +6,18 @@ export const useAppContext = () => useContext(AppContext);
export function ContextProvider({ children }) { export function ContextProvider({ children }) {
const [userseats, setUserSeats] = useState([]); const [userseats, setUserSeats] = useState([]);
const [seats, setSeats] = useState([]);
const [isLoading, setisLoading] = useState(false);
const LoginOrRegister = async ({ mobile }) => { const LoginOrRegister = async ({ mobile }) => {
try { try {
const user = await api.GetUserByMobile({ mobile }); const user = await api.GetUserByMobile({ mobile });
if (!user.length) { if (!user.length) {
//register //register
const response = await api.Register({ mobile }); const response = await api.Register({ mobile });
return { return await response;
response: response,
isRegistered: true,
};
} else { } else {
//login //login
return { return await user[0];
response: user[0],
isRegistered: false,
};
} }
} catch (err) { } catch (err) {
toast.error(err.message); toast.error(err.message);
...@@ -46,20 +42,25 @@ export function ContextProvider({ children }) { ...@@ -46,20 +42,25 @@ export function ContextProvider({ children }) {
} }
}; };
const GetAllSeats = async () => { const GetAllSeats = async () => {
setisLoading(false);
try { try {
//to clear the data for glitch //to clear the data for glitch
setUserSeats([]); setUserSeats([]);
const response = await api.GetAllSeats(); const response = await api.GetAllSeats();
setUserSeats(response); setUserSeats(response);
setisLoading(true);
} catch (err) { } catch (err) {
toast.error(err.message); toast.error(err.message);
} }
}; };
const GetSeatById = async (id) => { const GetSeats = async () => {
setisLoading(false);
try { try {
const response = await api.GetSeatById(id); setSeats([]);
return response; const response = await api.GetSeats();
setSeats(response);
setisLoading(true);
} catch (err) { } catch (err) {
toast.error(err.message); toast.error(err.message);
} }
...@@ -67,10 +68,12 @@ export function ContextProvider({ children }) { ...@@ -67,10 +68,12 @@ export function ContextProvider({ children }) {
const value = { const value = {
userseats, userseats,
isLoading,
seats,
LoginOrRegister, LoginOrRegister,
AddOrUpdateSeats, AddOrUpdateSeats,
GetAllSeats, GetAllSeats,
GetSeatById, GetSeats,
}; };
return <AppContext.Provider value={value}>{children}</AppContext.Provider>; return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
} }
...@@ -5,19 +5,22 @@ export function AuthGuard({ component: Component, ...props }) { ...@@ -5,19 +5,22 @@ export function AuthGuard({ component: Component, ...props }) {
const isLogged = sessionStorage.getItem("userId") != null ? true : false; const isLogged = sessionStorage.getItem("userId") != null ? true : false;
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation(); // const location = useLocation();
const currentPath = sessionStorage.getItem("currentPath"); // const currentPath = sessionStorage.getItem("currentPath");
useEffect(() => { // useEffect(() => {
if (!isLogged) { // if (!isLogged) {
sessionStorage.clear(); // sessionStorage.clear();
navigate("/"); // navigate("/");
} else if (isLogged && location.pathname != currentPath) { // } else if (isLogged && location.pathname != currentPath) {
navigate(currentPath); // navigate(currentPath);
} // }
}, [isLogged, location.pathname, navigate]); // }, [isLogged, location.pathname, navigate]);
// If logged in (session has a value), render the protected component // If logged in (session has a value), render the protected component
if (isLogged && location.pathname == currentPath) { // if (isLogged && location.pathname == currentPath) {
// return <Component {...props} />;
// }
if (isLogged) {
return <Component {...props} />; return <Component {...props} />;
} }
......
...@@ -8,7 +8,7 @@ function Confirmation({ seatCount, seats, onLogOut, onEdit }) { ...@@ -8,7 +8,7 @@ function Confirmation({ seatCount, seats, onLogOut, onEdit }) {
return ( return (
<Layout title="Booking Confirmed"> <Layout title="Booking Confirmed">
<div className={style.confirmation}> <div className={style.confirmation}>
<img src={Image} loading="lazy" /> <img src={Image} loading="lazy" alt="image" />
<span> <span>
Seat's Count:<h4>{seatCount}</h4> Seat's Count:<h4>{seatCount}</h4>
</span> </span>
......
...@@ -11,9 +11,9 @@ function SeatLayout({ ...@@ -11,9 +11,9 @@ function SeatLayout({
selectedSeats, selectedSeats,
seatLimit, seatLimit,
onClick, onClick,
isLoading,
}) { }) {
const [selectedseat, setSelectedSeat] = useState([...selectedSeats]); const [selectedseat, setSelectedSeat] = useState([...selectedSeats]);
const handleSeats = (seat) => { const handleSeats = (seat) => {
if (!selectedseat?.includes(seat) && selectedseat.length < seatLimit) { if (!selectedseat?.includes(seat) && selectedseat.length < seatLimit) {
setSelectedSeat([...selectedseat, seat]); setSelectedSeat([...selectedseat, seat]);
...@@ -40,54 +40,64 @@ function SeatLayout({ ...@@ -40,54 +40,64 @@ function SeatLayout({
return ( return (
<> <>
<div className={styles.container}> {isLoading && seats?.length ? (
<h1>Choose Seats</h1> <div className={styles.container}>
<div className="booking"> <h1>Choose Seats</h1>
<div className={styles.curve}> <div className="booking">
<div className={styles["curve-shadow"]}></div> <div className={styles.curve}>
</div> <div className={styles["curve-shadow"]}></div>
<div className={styles["seat-container"]}> </div>
{seats?.map((seat, i) => ( <div className={styles["seat-container"]}>
<div key={i} className={styles.seat}> {seats?.map((seat, i) => (
{seat?.map((e, i) => ( <div key={i} className={styles.seat}>
<div {seat?.map((e, i) => (
key={i} <div
className={`${e === 0 ? styles["remove-seats"] : ""}`} key={i}
> className={`${e === 0 ? styles["remove-seats"] : ""}`}
<Seat >
seatNo={e} <Seat
onChange={() => handleSeats(e)} seatNo={e}
status={ onChange={() => handleSeats(e)}
selectedseat?.includes(e) status={
? "selected" selectedseat?.includes(e)
: reservedSeats?.includes(e) ? "selected"
? "reserved" : reservedSeats?.includes(e)
: "available" ? "reserved"
} : "available"
/> }
</div> />
))} </div>
</div> ))}
))} </div>
))}
</div>
</div> </div>
</div>
<Button onClick={handleConfirm}>Confirm</Button> <Button onClick={handleConfirm}>Confirm</Button>
<div className={styles["seat-status"]}> <div className={styles["seat-status"]}>
<div className={styles.selected}> <div className={styles.selected}>
<div></div> <div></div>
<p>Selected</p> <p>Selected</p>
</div> </div>
<div className={styles.reserved}> <div className={styles.reserved}>
<div></div> <div></div>
<p>Reserved</p> <p>Reserved</p>
</div> </div>
<div className={styles.available}> <div className={styles.available}>
<div></div> <div></div>
<p>Available</p> <p>Available</p>
</div>
</div> </div>
</div> </div>
</div> ) : (
<div className={styles["loader-container"]}>
<div className={styles["dot"]}></div>
<div className={styles["dot"]}></div>
<div className={styles["dot"]}></div>
<div className={styles["dot"]}></div>
<div className={styles["dot"]}></div>
</div>
)}
</> </>
); );
} }
......
...@@ -96,3 +96,46 @@ ...@@ -96,3 +96,46 @@
clip-path: polygon(30% 0, 73% 0, 80% 100%, 22% 99%); clip-path: polygon(30% 0, 73% 0, 80% 100%, 22% 99%);
} }
} }
.loader-container {
display: flex;
}
.loader-container .dot {
width: 15px;
height: 15px;
background-color: white;
border-radius: 50%;
margin: 0 5px;
animation: bounce 1.1s ease infinite;
}
.loader-container .dot:nth-child(1) {
animation-delay: 0s;
}
.loader-container .dot:nth-child(2) {
animation-delay: 0.1s;
}
.loader-container .dot:nth-child(3) {
animation-delay: 0.2s;
}
.loader-container .dot:nth-child(4) {
animation-delay: 0.3s;
}
.loader-container .dot:nth-child(5) {
animation-delay: 0.4s;
}
@keyframes bounce {
0%,
20%,
50%,
80%,
100% {
transform: translateY(0);
}
40% {
transform: translateY(-60px);
}
60% {
transform: translateY(25px);
}
}
...@@ -43,6 +43,11 @@ export async function GetAllSeats() { ...@@ -43,6 +43,11 @@ export async function GetAllSeats() {
return await response.json(); return await response.json();
} }
export async function GetSeats() {
const response = await fetch(`${BASE_URL}/bookingSeats`);
return await response.json();
}
export async function GetUserByMobile({ mobile }) { export async function GetUserByMobile({ mobile }) {
const response = await fetch(`${BASE_URL}/users?mobile=${mobile}`); const response = await fetch(`${BASE_URL}/users?mobile=${mobile}`);
return await response.json(); return await response.json();
......
...@@ -26,8 +26,6 @@ export function _Confirmation() { ...@@ -26,8 +26,6 @@ export function _Confirmation() {
const handleModify = (e) => { const handleModify = (e) => {
e.preventDefault(); e.preventDefault();
//for Auth Guard
sessionStorage.setItem("currentPath", "/booking");
navigate("/booking"); navigate("/booking");
}; };
......
import { useEffect } from "react"; import { useEffect, useState } from "react";
import { useAppContext } from "../_context"; import { useAppContext } from "../_context";
import Login from "../components/top-level/login"; import Login from "../components/top-level/login";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
export function _Login() { export function _Login() {
const navigate = useNavigate(); const navigate = useNavigate();
const { LoginOrRegister } = useAppContext(); const { userseats, LoginOrRegister, GetAllSeats } = useAppContext();
const [isLogged, setIsLogged] = useState(false);
useEffect(() => { useEffect(() => {
sessionStorage.clear(); sessionStorage.clear();
}, []); }, []);
useEffect(() => {
isLogged && handleSeats();
}, [isLogged]);
const handleLogin = async ({ mobile }) => { const handleLogin = async ({ mobile }) => {
//get all seats and then login
const users = await LoginOrRegister({ mobile }); const users = await LoginOrRegister({ mobile });
sessionStorage.setItem("userId", users.response.id); sessionStorage.setItem("userId", users?.id);
if (users.isRegistered) {
//for Auth Guard await GetAllSeats();
sessionStorage.setItem("currentPath", "/seat-limit"); setIsLogged(true);
};
const handleSeats = async () => {
const id = sessionStorage.getItem("userId");
const userReservedSeats = userseats.filter((e) => e.id == id);
if (!userReservedSeats.length) {
navigate("/seat-limit"); navigate("/seat-limit");
} else { } else {
//for Auth Guard sessionStorage.setItem("seatLimit", userReservedSeats[0].seats.length);
sessionStorage.setItem("currentPath", "/booking"); navigate("/booking", { state: { seats: userseats } });
navigate("/booking");
} }
}; };
return <Login onSubmit={handleLogin} />; return <Login onSubmit={handleLogin} />;
} }
import { useEffect, useLayoutEffect, useState } from "react"; import { useEffect, useState } from "react";
import SeatLayout from "../components/top-level/seat-layout"; import SeatLayout from "../components/top-level/seat-layout";
import { useAppContext } from "../_context"; import { useAppContext } from "../_context";
import { useNavigate } from "react-router-dom"; import { useLocation, useNavigate } from "react-router-dom";
import { bookingSeats } from "./seed";
export function _Seatlayout() { export function _Seatlayout() {
let { userseats, AddOrUpdateSeats, GetAllSeats } = useAppContext(); let { userseats, isLoading, seats, AddOrUpdateSeats, GetAllSeats, GetSeats } =
useAppContext();
const [reservedSeat, setReservedSeat] = useState([]); const [reservedSeat, setReservedSeat] = useState([]);
const [selectedSeat, setSelectedSeat] = useState([]); const [selectedSeat, setSelectedSeat] = useState([]);
const [seatLimit, setSeatLimit] = useState(0);
const navigate = useNavigate(); const navigate = useNavigate();
const userId = sessionStorage.getItem("userId"); const userId = sessionStorage.getItem("userId");
const seatLimit = sessionStorage.getItem("seatLimit");
const location = useLocation();
useEffect(() => {
GetSeats();
if (!location?.state?.seats.length) {
GetAllSeats();
}
const handleBeforeUnload = (event) => {
// Check if the page is about to unload or refresh
if (event.type === "beforeunload") {
navigate("/booking", { replace: true });
}
};
window.addEventListener("beforeunload", handleBeforeUnload);
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
};
}, []);
// useEffect(() => {
// GetSeats();
// const handleBeforeUnload = (event) => {
// // Check if the page is about to unload or refresh
// if (event.type === "beforeunload") {
// sessionStorage.setItem("pageload", true);
// }
// };
// window.addEventListener("beforeunload", handleBeforeUnload);
// return () => {
// window.removeEventListener("beforeunload", handleBeforeUnload);
// };
// }, []);
// useEffect(() => {
// const reloadPage = sessionStorage.getItem("pageload");
// reloadPage && GetAllSeats();
// }, []);
useEffect(() => { useEffect(() => {
handleReservedSeats(); handleReservedSeats();
}, [userseats]); }, [userseats]);
useLayoutEffect(() => {
GetAllSeats();
}, []);
const handleReservedSeats = async () => { const handleReservedSeats = async () => {
let seatArray = []; let seatArray = [];
const selectedSeats = await userseats?.find((e) => e.id == userId);
const results = selectedSeats?.seats;
setSelectedSeat(results);
const reservedSeats = userseats?.filter((e) => e.id != userId); const reservedSeats = userseats?.filter((e) => e.id != userId);
reservedSeats.forEach((element) => { reservedSeats?.forEach((element) => {
element.seats.forEach((e) => { element?.seats.forEach((e) => {
seatArray = [...seatArray, e]; seatArray = [...seatArray, e];
setReservedSeat(seatArray); setReservedSeat(seatArray);
}); });
}); });
const selectedSeats = await userseats?.find((e) => e.id == userId);
const results = selectedSeats?.seats;
setSelectedSeat(results);
const sessionSeatLimit = sessionStorage.getItem("seatLimit");
setTimeout(() => {
sessionStorage.setItem("seatLimit", sessionSeatLimit ?? results?.length);
setSeatLimit(sessionStorage.getItem("seatLimit"));
}, 500);
}; };
const handleConfirmed = async ({ id, seats }) => { const handleConfirmed = async ({ id, seats }) => {
await AddOrUpdateSeats({ id, seats }); await AddOrUpdateSeats({ id, seats });
sessionStorage.setItem("currentPath", "/confirmation");
navigate("/confirmation", { state: { seats: seats } }); navigate("/confirmation", { state: { seats: seats } });
}; };
return ( return (
<SeatLayout <SeatLayout
isLoading={isLoading}
userId={userId} userId={userId}
seatLimit={seatLimit} seatLimit={seatLimit}
seats={bookingSeats} seats={seats}
selectedSeats={selectedSeat} selectedSeats={selectedSeat}
reservedSeats={reservedSeat} reservedSeats={reservedSeat}
onClick={handleConfirmed} onClick={handleConfirmed}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment