Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 35 additions & 35 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,49 +14,49 @@ import ProfilePage from "./shared/pages/Profile.js";
import LoginRedirection from "./auth/Login.tsx";
import LogoutRedirection from "./auth/Logout.tsx";
import StickyFooter from "./shared/components/Navigation/StickyFooter.tsx";
import IsAuthenticated from "./auth/Auth.tsx";
import Token from "./auth/Token.tsx";
import { HelmetProvider } from 'react-helmet-async';
import { AuthProvider } from './context/AuthContext.tsx';

function App() {

const authenticated = IsAuthenticated();

return (
<HelmetProvider>
<section>
<MainNavigation authenticated={authenticated} />
<main className="container-xl p-8">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/health" element={<p>App is Healthy</p>} />
<Route path="/callback" element={<Token />} />
<Route path="/signin" element={<LoginRedirection />} />
<Route path="/login" element={<LoginRedirection />} />
<Route path="/signout" element={<LogoutRedirection authenticated={authenticated} />} />
<Route path="/logout" element={<LogoutRedirection authenticated={authenticated} />} />
<AuthProvider>
<HelmetProvider>
<section>
<MainNavigation />
<main className="container-xl p-8">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/health" element={<p>App is Healthy</p>} />
<Route path="/callback" element={<Token />} />
<Route path="/signin" element={<LoginRedirection />} />
<Route path="/login" element={<LoginRedirection />} />
<Route path="/signout" element={<LogoutRedirection />} />
<Route path="/logout" element={<LogoutRedirection />} />

<Route path="/jobs" element={<Jobs />} />
<Route path="/profile" element={<ProfilePage />} />
<Route
path="/staff/department/:department"
element={<Department authenticated={authenticated} />}
/>
<Route path="/staff" element={<Departments authenticated={authenticated} />} />
<Route path="/staff/:staffId" element={<StaffPage authenticated={authenticated} />} />
<Route path="/create" element={<CreatePost edit={false} authenticated={authenticated} />} />
<Route
path="/edit/:postID"
element={<CreatePost edit={true} authenticated={authenticated} />}
/>
<Route path="/post/:postID" element={<IndividualPost />} />
<Route path="/jobs" element={<Jobs />} />
<Route path="/profile" element={<ProfilePage />} />
<Route
path="/staff/department/:department"
element={<Department />}
/>
<Route path="/staff" element={<Departments />} />
<Route path="/staff/:staffId" element={<StaffPage />} />
<Route path="/create" element={<CreatePost edit={false} />} />
<Route
path="/edit/:postID"
element={<CreatePost edit={true} />}
/>
<Route path="/post/:postID" element={<IndividualPost />} />

<Route path="/*" element={<PageNotFound />} />
</Routes>
</main>
<StickyFooter authenticated={authenticated} />
</section>
</HelmetProvider>
<Route path="/*" element={<PageNotFound />} />
</Routes>
</main>
<StickyFooter />
</section>
</HelmetProvider>
</AuthProvider>
);
}

Expand Down
11 changes: 0 additions & 11 deletions src/auth/Auth.tsx

This file was deleted.

14 changes: 9 additions & 5 deletions src/auth/Login.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
const LoginRedirection = () => {
window.location.href = `${process.env.REACT_APP_BACKEND_SERVER}/login`;
return null; // No need to render anything, as the redirection happens immediately
};
import { useAuth } from "../context/AuthContext.tsx";

export default LoginRedirection;
export default function LoginRedirection() {
const { auth } = useAuth();
if (auth.isAuthenticated) {
window.location.href = "/";
}
window.location.href = `${process.env.REACT_APP_BACKEND_SERVER}/login`;
return null;
};
67 changes: 29 additions & 38 deletions src/auth/Logout.tsx
Original file line number Diff line number Diff line change
@@ -1,47 +1,38 @@
import { useEffect } from "react";
import { useAuth } from "../context/AuthContext.tsx";

const logout = async (token: string) => {
try {
const response = await fetch(
`${process.env.REACT_APP_BACKEND_SERVER}/logout`,
{
method: "GET",
credentials: "include", // to send cookies or session data
headers: {
Authorization: `Bearer ${token}`,
},
}
);
if (response.ok) {
// Clear local storage or tokens
localStorage.removeItem("jwt");

// Redirect to the homepage or login page
const intervalId = setInterval(() => {
if (!localStorage.getItem("jwt")) {
clearInterval(intervalId); // Clear the interval once condition is met
window.location.href = "/";
}
}, 5); // Check every 5ms (adjust as needed)
} else {
console.error("Failed to logout");
}
} catch (error) {
console.error("Error logging out:", error);
window.location.href = "/";
}
};
export default function LogoutRedirection() {
const { auth, logout } = useAuth();

const LogoutRedirection = (authenticated) => {
if (!authenticated.authenticated[1]) {
if (!auth.isAuthenticated) {
window.location.href = "/";
}
console.log("Logging out...");
useEffect(() => {
logout(authenticated.authenticated[0]);
}, []); // Run only on component mount
async function logoutUser() {
try {
const response = await fetch(
`${process.env.REACT_APP_BACKEND_SERVER}/logout`,
{
method: "GET",
credentials: "include", // to send cookies or session data
headers: {
Authorization: `Bearer ${auth.token}`,
},
}
);
if (response.ok) {
logout();
} else {
console.error("Failed to logout");
}
} catch (error) {
console.error("Error logging out:", error);
window.location.href = "/";
}
}
logoutUser();
}, [auth, logout]);

return null; // Since this component doesn't need to render anything
};

export default LogoutRedirection;
};
25 changes: 9 additions & 16 deletions src/auth/Token.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
const Token = () => {
import { useAuth } from "../context/AuthContext.tsx";

export default function Token() {

const { login } = useAuth();

const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get("code");

console.log("Code:", code);
if (code) {
fetch(`${process.env.REACT_APP_BACKEND_SERVER}/token`, {
method: "POST",
Expand All @@ -14,26 +17,16 @@ const Token = () => {
})
.then((response) => response.json())
.then((data) => {
console.log("Data:", data);
const token = data.token;
console.log("Token:", token);
if (token) {
localStorage.setItem("jwt", token);

// Periodically check if both jwt and jwt-time are set
const intervalId = setInterval(() => {
if (localStorage.getItem("jwt")) {
clearInterval(intervalId); // Clear the interval once condition is met
window.location.href = "/";
}
}, 5); // Check every 5ms (adjust as needed)
login(token);
return null;
}
})
.catch((error) => console.error("Error fetching token:", error));
} else {
window.location.href = "/";
}

return null;
}

export default Token;
}
53 changes: 53 additions & 0 deletions src/context/AuthContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import React, { createContext, useState, useContext } from 'react';

const AuthContext = createContext<{
auth: { isAuthenticated: boolean; token: string | null };
login: (token: string) => void;
logout: () => void;
loadToken: () => void;
}>({
auth: { isAuthenticated: false, token: null },
login: () => { },
logout: () => { },
loadToken: () => { }
});

import { ReactNode } from 'react';

interface AuthProviderProps {
children: ReactNode;
}

export const AuthProvider = ({ children }: AuthProviderProps) => {
const [auth, setAuth] = useState<{ isAuthenticated: boolean; token: string | null }>({
isAuthenticated: false,
token: null,
});

const login = (token: string) => {
setAuth({ isAuthenticated: true, token });
// Save token to localStorage for persistence
localStorage.setItem('jwt', token);
};

const logout = () => {
setAuth({ isAuthenticated: false, token: null });
// Clear token from localStorage
localStorage.removeItem('jwt');
};

const loadToken = () => {
const savedToken = localStorage.getItem('jwt');
if (savedToken) {
setAuth({ isAuthenticated: true, token: savedToken });
}
};

return (
<AuthContext.Provider value={{ auth, login, logout, loadToken }}>
{children}
</AuthContext.Provider>
);
};

export const useAuth = () => useContext(AuthContext);
5 changes: 0 additions & 5 deletions src/context/global/GlobalContext.js

This file was deleted.

57 changes: 0 additions & 57 deletions src/context/global/GlobalContextProvider.js

This file was deleted.

Loading
Loading