Add Auth Context

This commit is contained in:
sosokker 2023-11-14 01:41:26 +07:00
parent 4be0efc0bb
commit b47e83e5cf
5 changed files with 36 additions and 9 deletions

View File

@ -1,9 +1,10 @@
import React from "react";
import { Navigate, Outlet } from "react-router-dom";
import IsAuthenticated from "./hooks/authentication/IsAuthenticated";
import { useAuth } from "./hooks/authentication/IsAuthenticated";
const PrivateRoute = () => {
const auth = IsAuthenticated();
const { isAuthenticated, setIsAuthenticated } = useAuth();
const auth = isAuthenticated;
return auth ? <Outlet /> : <Navigate to="/login" />;
};

View File

@ -5,9 +5,13 @@ import { useGoogleLogin } from "@react-oauth/google";
import refreshAccessToken from "./refreshAcesstoken";
import axiosapi from "../../api/AuthenticationApi";
import { useAuth } from "../../hooks/authentication/IsAuthenticated";
function LoginPage() {
const Navigate = useNavigate();
const { isAuthenticated, setIsAuthenticated } = useAuth();
useEffect(() => {
if (!refreshAccessToken()) {
Navigate("/");
@ -39,11 +43,13 @@ function LoginPage() {
localStorage.setItem("access_token", res.data.access);
localStorage.setItem("refresh_token", res.data.refresh);
axiosapi.axiosInstance.defaults.headers["Authorization"] = "Bearer " + res.data.access;
setIsAuthenticated(true);
Navigate("/");
})
.catch(err => {
console.log("Login failed");
console.log(err);
setIsAuthenticated(false);
});
};
@ -58,10 +64,12 @@ function LoginPage() {
localStorage.setItem("access_token", access_token);
localStorage.setItem("refresh_token", refresh_token);
setIsAuthenticated(true);
Navigate("/");
}
} catch (error) {
console.error("Error with the POST request:", error);
setIsAuthenticated(false);
}
},
onError: errorResponse => console.log(errorResponse),

View File

@ -1,7 +1,7 @@
import * as React from "react";
import { useNavigate } from "react-router-dom";
import IsAuthenticated from "../../hooks/authentication/IsAuthenticated";
import axiosapi from "../../api/AuthenticationApi";
import { useAuth } from "../../hooks/authentication/IsAuthenticated";
const settings = {
Profile: "/update_profile",
@ -11,10 +11,11 @@ const settings = {
function NavBar() {
const Navigate = useNavigate();
const isAuthenticated = IsAuthenticated();
const { isAuthenticated, setIsAuthenticated } = useAuth();
const logout = () => {
axiosapi.apiUserLogout();
setIsAuthenticated(false);
Navigate("/");
};

View File

@ -1,6 +1,8 @@
import { useEffect, useState } from "react";
import React, { createContext, useContext, useState, useEffect } from "react";
function IsAuthenticated() {
const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState(() => {
const access_token = localStorage.getItem("access_token");
return !!access_token;
@ -12,6 +14,8 @@ function IsAuthenticated() {
setIsAuthenticated(!!newAccessToken);
};
handleTokenChange();
window.addEventListener("storage", handleTokenChange);
return () => {
@ -19,7 +23,17 @@ function IsAuthenticated() {
};
}, []);
return isAuthenticated;
}
return (
<AuthContext.Provider value={{ isAuthenticated, setIsAuthenticated }}>
{children}
</AuthContext.Provider>
);
};
export default IsAuthenticated;
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
};

View File

@ -3,6 +3,7 @@ import ReactDOM from "react-dom/client";
import App from "./App";
import { GoogleOAuthProvider } from "@react-oauth/google";
import { BrowserRouter } from "react-router-dom";
import { AuthProvider } from "./hooks/authentication/IsAuthenticated";
const GOOGLE_CLIENT_ID = import.meta.env.VITE_GOOGLE_CLIENT_ID;
@ -10,7 +11,9 @@ ReactDOM.createRoot(document.getElementById("root")).render(
<GoogleOAuthProvider clientId={GOOGLE_CLIENT_ID}>
<BrowserRouter>
<Fragment>
<AuthProvider>
<App />
</AuthProvider>
</Fragment>
</BrowserRouter>
</GoogleOAuthProvider>