Commit 75154cde by Madhankumar

auth guard

parent 83a46bc1
REACT_APP_BASE_URL=http://192.168.1.91:5000
\ No newline at end of file
......@@ -11,10 +11,27 @@
{
"mobile": "9999999998",
"id": 3
},
{
"mobile": "8888888880",
"id": 4
}
],
"reservedSeats": [
{
"seats": [
"H7",
"G6"
],
"id": 2
},
{
"seats": [
"F2",
"F3",
"F1"
],
"id": 3
}
]
}
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -6,7 +6,9 @@
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"crypto-browserify": "^3.12.0",
"json-server": "^0.17.4",
"path-browserify": "^1.0.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.16.0",
......
import "./App.css";
import {
BrowserRouter as Router,
Route,
Routes,
useNavigate,
} from "react-router-dom";
import { useEffect } from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import { _Login } from "../src/pages/login";
import { _Seatlayout } from "../src/pages/seat-layout";
import { _Confirmation } from "../src/pages/confirmation";
import { AuthGuard } from "./auth/index";
import { _seatLimit } from "../src/pages/seat-limit";
function App() {
// const navigate = useNavigate();
// useEffect(() => {
// // Redirect to the "Example Page" when the page is reloaded
// navigate("/");
// }, []);
return (
<div className="App">
<Router>
<Routes>
<Route path="/" element={<_Login />} />
<Route
path="/seat-limit/:id"
path="/seat-limit"
element={<AuthGuard component={_seatLimit} />}
/>
<Route
path="/booking/:id/:limit?"
path="/booking"
element={<AuthGuard component={_Seatlayout} />}
/>
<Route
path="/confirmation"
element={<AuthGuard component={_Confirmation} />}
/>
{/* Default route */}
<Route path="*" element={_Login} />
</Routes>
</Router>
</div>
......
......@@ -8,44 +8,62 @@ export function ContextProvider({ children }) {
const [userseats, setUserSeats] = useState([]);
const LoginOrRegister = async ({ mobile }) => {
try {
const response = await api.LoginOrRegister({ mobile });
localStorage.setItem("isLogged", 1);
return response;
const user = await api.GetUserByMobile({ mobile });
if (!user.length) {
//register
const response = await api.Register({ mobile });
return await response;
} else {
//login
return await user[0];
}
} catch (err) {
toast.error(err.message);
}
};
const AddOrUpdateSeats = async ({ id, seats }) => {
try {
const response = await api.AddOrUpdateSeats({
id,
seats,
});
if (response.isAddSeat) {
setUserSeats([...userseats, response.response]);
const userSeats = await api.GetSeatById(id);
if (!Object.keys(userSeats).length) {
//add seats
const response = await api.AddSeats({ seats });
setUserSeats([...userseats, response]);
} else {
const result = userseats.map((e) =>
e.id === id ? response.response : e
);
//update seats
const response = await api.UpdateSeats({ id, seats });
const result = userseats.map((e) => (e[id] == id ? response : e));
setUserSeats(result);
}
} catch (err) {
toast.error(err.message);
}
};
const GetAllReservedSeats = async () => {
const GetAllSeats = async () => {
try {
//to clear the data for glitch
setUserSeats([]);
const response = await api.GetAllSeats();
setUserSeats(response);
} catch (err) {
toast.error(err.message);
}
};
const GetSeatById = async (id) => {
try {
const response = await api.GetSeatById(id);
return response;
} catch (err) {
toast.error(err.message);
}
};
const value = {
userseats,
LoginOrRegister,
AddOrUpdateSeats,
GetAllReservedSeats,
GetAllSeats,
GetSeatById,
};
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
}
import React from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
// import { _Login } from "../pages/login";
export function AuthGuard({ component: Component, ...props }) {
const isLogged = localStorage.getItem("isLogged");
const isLogged = sessionStorage.getItem("userId") != null ? true : false;
console.log("didid", isLogged);
const navigate = useNavigate();
const location = useLocation();
const currentPath = sessionStorage.getItem("currentPath");
console.log("pod", location.pathname, currentPath);
useEffect(() => {
console.log("yrtrtry");
if (!isLogged) {
sessionStorage.removeItem("userId");
sessionStorage.removeItem("seatLimit");
// Redirect to the home page if the user is not logged in
navigate("/");
} else if (isLogged && location.pathname != currentPath) {
navigate(currentPath);
}
}, [isLogged, location.pathname, navigate]);
if (!isLogged) {
// Redirect to the home page if the user is not logged in
navigate("/");
return null; // You can return null or another component if needed
// If logged in (session has a value), render the protected component
if (isLogged && location.pathname == currentPath) {
console.log("jjsj");
return <Component {...props} />;
}
return <Component {...props} />;
// If not logged in, you can choose to redirect to the home page or handle it differently
return null; // Return null or render a login component or a message
}
......@@ -15,7 +15,7 @@ function Confirmation({ seatCount, seats, onLogOut, onEdit }) {
<span>
Booked Seats:
<h3> {seats.toString()}</h3>
<h3> {seats?.toString()}</h3>
</span>
<Button onClick={onEdit}>Modify</Button>
<div className={style.logout} onClick={onLogOut}>
......
......@@ -36,7 +36,9 @@ function Login({ onSubmit }) {
maxLength={10}
onChange={handleChange}
/>
{iserror && <span>Please enter 10 digits</span>}
{iserror && (
<span className={styles.span}>Please enter 10 digits</span>
)}
</div>
<Button>Submit</Button>
</form>
......
......@@ -12,8 +12,8 @@ function SeatLayout({
selectedSeats,
seatLimit,
onClick,
...props
}) {
console.log("poo", userId);
const [selectedseat, setSelectedSeat] = useState([...selectedSeats]);
const handleSeats = (seat) => {
......@@ -36,7 +36,7 @@ function SeatLayout({
toast.error(`please select upto ${seatLimit} `);
} else {
onClick({
id: parseInt(userId) || 1,
id: parseInt(userId),
seats: selectedseat,
});
}
......@@ -74,9 +74,7 @@ function SeatLayout({
</div>
</div>
<Button onClick={handleConfirm} {...props}>
Confirm
</Button>
<Button onClick={handleConfirm}>Confirm</Button>
<div className={styles["seat-status"]}>
<div className={styles.selected}>
<div></div>
......
import { toast } from "react-toastify";
const BASE_URL = "http://192.168.1.91:5000";
const BASE_URL = process.env.REACT_APP_BASE_URL;
export async function LoginOrRegister({ mobile }) {
try {
// Attempt to fetch user data
const response = await fetch(
`http://192.168.1.91:5000/users?mobile=${mobile}`
);
const result = await response.json();
export async function Login({ mobile }) {
// Attempt to fetch user data
const response = await fetch(`${BASE_URL}/users?mobile=${mobile}`);
const result = await response.json();
return result;
}
if (!result.length) {
// User not found, register
const user = await fetch(`${BASE_URL}/users`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ mobile }),
});
export async function Register({ mobile }) {
// User not found, register
const user = await fetch(`${BASE_URL}/users`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ mobile }),
});
return await user.json();
} else {
// User data found, return JSON
return result?.[0];
}
} catch (err) {
toast.error(err.message);
}
return await user.json();
}
export async function AddOrUpdateSeats({ id, seats }) {
try {
const userSeat = await fetch(
`http://192.168.1.91:5000/reservedSeats/${id}`
);
const result = await userSeat.json();
console.log("oidufuf", result);
if (!Object.keys(result).length) {
//add seat
const response = await fetch(BASE_URL + "/reservedSeats", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id, seats }),
});
const res = await response.json();
return {
response: res,
isAddSeat: true,
};
} else {
//update
console.log("patch");
const response = await fetch(
`http://192.168.1.91:5000/reservedSeats/${id}`,
{
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ seats }),
}
);
const res = await response.json();
export async function AddSeats({ id, seats }) {
//add seat
const response = await fetch(`${BASE_URL}/reservedSeats `, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id, seats }),
});
return await response.json();
}
return {
response: res,
isAddSeat: false,
};
}
} catch (err) {
toast.error(err.message);
}
export async function UpdateSeats({ id, seats }) {
//update
const response = await fetch(`${BASE_URL}/reservedSeats/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ seats }),
});
return await response.json();
}
export async function GetAllSeats() {
try {
const response = await fetch(BASE_URL + "/reservedSeats");
return await response.json();
} catch (err) {
toast.error(err.message);
}
const response = await fetch(`${BASE_URL}/reservedSeats`);
return await response.json();
}
export async function GetUserByMobile({ mobile }) {
const response = await fetch(`${BASE_URL}/users?mobile=${mobile}`);
return await response.json();
}
export async function GetSeatById(id) {
const response = await fetch(`${BASE_URL}/reservedSeats/${id}`);
return await response.json();
}
import Confirmation from "../components/top-level/confirmation";
import { useLocation } from "react-router-dom";
import { useNavigate } from "react-router-dom";
import { useAppContext } from "../_context";
import { useEffect, useState } from "react";
export function _Confirmation() {
const location = useLocation();
const seatCount = location.state.seatCount;
const seats = location.state.seats;
const id = location.state.id;
const seatLimit = location.state.limit;
const { GetSeatById } = useAppContext();
const [count, setCount] = useState(0);
const [reservedseat, setReservedSeat] = useState([]);
const navigate = useNavigate();
useEffect(() => {
getSeatById();
}, []);
const getSeatById = async () => {
const id = sessionStorage.getItem("userId");
const userReservedSeat = await GetSeatById(id);
setCount(userReservedSeat?.seats?.length);
setReservedSeat(userReservedSeat.seats);
};
const handleModify = (e) => {
e.preventDefault();
navigate(`/booking/${id}/${seatLimit}`);
sessionStorage.setItem("currentPath", "/booking");
navigate("/booking");
};
return (
<Confirmation
id={id}
seatCount={seatCount}
seats={seats}
seatCount={count}
seats={reservedseat}
onEdit={handleModify}
/>
);
......
......@@ -5,20 +5,25 @@ import { useNavigate } from "react-router-dom";
export function _Login() {
const navigate = useNavigate();
const { userseats, LoginOrRegister, GetAllReservedSeats } = useAppContext();
const { userseats, LoginOrRegister, GetAllSeats } = useAppContext();
useEffect(() => {
GetAllReservedSeats();
GetAllSeats();
sessionStorage.clear();
}, []);
const handleLogin = async ({ mobile }) => {
const users = await LoginOrRegister({ mobile });
if (users != null) {
const userstate = userseats.filter((e) =>
e.id == users.id ? true : false
e.id === users.id ? true : false
);
if (userstate.length) {
navigate(`/booking/${userstate[0].id}/${userstate[0].seats.length}`);
sessionStorage.setItem("userId", users.id);
sessionStorage.setItem("seatLimit", userstate[0].seats.length);
sessionStorage.setItem("currentPath", "/booking");
navigate("/booking");
} else {
navigate(`/seat-limit/${users.id}`);
sessionStorage.setItem("currentPath", "/seat-limit");
navigate("/seat-limit");
}
}
};
......
import { useEffect, useLayoutEffect, useState } from "react";
import SeatLayout from "../components/top-level/seat-layout";
import { useAppContext } from "../_context";
import { useParams } from "react-router-dom";
import { useNavigate } from "react-router-dom";
import { bookingSeats } from "./seed";
export function _Seatlayout({ ...props }) {
const { userseats, AddOrUpdateSeats, GetAllReservedSeats } = useAppContext();
export function _Seatlayout() {
const { userseats, AddOrUpdateSeats, GetAllSeats } = useAppContext();
const [reservedSeat, setReservedSeat] = useState([]);
const [selectedSeat, setSelectedSeat] = useState([]);
const navigate = useNavigate();
const { id, limit } = useParams();
const userId = sessionStorage.getItem("userId");
const seatLimit = sessionStorage.getItem("seatLimit");
useLayoutEffect(() => {
GetAllReservedSeats();
GetAllSeats();
}, []);
useEffect(() => {
handleReservedSeats();
......@@ -22,7 +22,7 @@ export function _Seatlayout({ ...props }) {
const handleReservedSeats = () => {
let seatArray = [];
const reservedSeats = userseats?.filter((e) => e.id != id);
const reservedSeats = userseats?.filter((e) => e.id != userId);
reservedSeats.forEach((element) => {
element.seats.forEach((e) => {
......@@ -30,7 +30,7 @@ export function _Seatlayout({ ...props }) {
setReservedSeat(seatArray);
});
});
const selectedSeats = userseats?.find((e) => e.id == id);
const selectedSeats = userseats?.find((e) => e.id == userId);
const results = selectedSeats?.seats;
setSelectedSeat(results);
};
......@@ -39,21 +39,18 @@ export function _Seatlayout({ ...props }) {
await AddOrUpdateSeats({ id, seats });
const count = seats?.length;
navigate("/confirmation", {
state: { seatCount: count ?? 0, seats: seats, id, limit },
});
sessionStorage.setItem("currentPath", "/confirmation");
navigate("/confirmation");
};
return (
<SeatLayout
userId={id}
seatLimit={limit}
userId={userId}
seatLimit={seatLimit}
seats={bookingSeats}
selectedSeats={selectedSeat}
reservedSeats={reservedSeat}
onClick={handleConfirmed}
{...props}
/>
);
}
import SeatLimit from "../components/top-level/seat-limit";
import { useParams, useNavigate } from "react-router-dom";
import { useNavigate } from "react-router-dom";
export function _seatLimit() {
const { id } = useParams();
const navigate = useNavigate();
const handleLimit = (e) => {
navigate(`/booking/${id}/${e.limit}`);
navigate("/booking");
};
return <SeatLimit onLimit={handleLimit} />;
}
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