From 34e19a569328c3fc0f5fba5d384cd853616ff1be Mon Sep 17 00:00:00 2001 From: Sven Czarnian Date: Thu, 3 Nov 2022 23:37:26 +0100 Subject: [PATCH] introduce the auth provider --- src/App.tsx | 4 ++- src/contexts/authcontext.tsx | 69 ++++++++++++++++++++++++++++++++++++ src/contexts/index.ts | 3 ++ 3 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 src/contexts/authcontext.tsx create mode 100644 src/contexts/index.ts diff --git a/src/App.tsx b/src/App.tsx index c187f08..3248e83 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,18 +1,20 @@ import React from 'react'; import { BrowserRouter, Routes, Route } from 'react-router-dom'; import { Auth } from './components/auth'; -import { Login } from './components/login'; +import { AuthProvider } from './contexts'; import './App.css'; import { Overview } from './components/overview'; const App: React.FC = () => ( <> + } /> } /> } /> + ); diff --git a/src/contexts/authcontext.tsx b/src/contexts/authcontext.tsx new file mode 100644 index 0000000..6d0ae33 --- /dev/null +++ b/src/contexts/authcontext.tsx @@ -0,0 +1,69 @@ +import axios from 'axios'; +import { createContext, Dispatch, SetStateAction, useEffect, useState } from 'react'; +import { useNavigate } from 'react-router-dom'; +import { Configuration } from '../services'; + +export interface User { + vatsimId: string; + fullName: string; + administrator: boolean; + airportConfigurationAccess: string[]; +}; + +const AuthContext = createContext<{ + auth: { valid: boolean; user: User }; + setAuth: Dispatch>; +}>({ auth: { + valid: false, + user: { + vatsimId: '', + fullName: '', + administrator: false, + airportConfigurationAccess: [], + }, +}, setAuth: () => {} }); + +export const AuthProvider = ({ children }: { children: any }) => { + const [auth, setAuth] = useState<{ valid: boolean; user: User }>({ + valid: false, + user: { + vatsimId: '', + fullName: '', + administrator: false, + airportConfigurationAccess: [], + }, + }); + const navigate = useNavigate(); + + useEffect(() => { + axios.get(`${Configuration.resourceServer}/auth/user`, { + headers: { + Authorization: `Bearer ${sessionStorage.getItem('token')}`, + }, + }).then((response) => { + setAuth({ valid: true, user: response.data }); + }).catch(() => { + setAuth({ + valid: false, + user: { + vatsimId: '', + fullName: '', + administrator: false, + airportConfigurationAccess: [], + }, + }); + navigate('/'); + }) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + return ( + <> + + {children} + + + ); +}; + +export default AuthContext; diff --git a/src/contexts/index.ts b/src/contexts/index.ts new file mode 100644 index 0000000..b61094b --- /dev/null +++ b/src/contexts/index.ts @@ -0,0 +1,3 @@ +import AuthContext, { AuthProvider } from "./authcontext"; + +export { AuthContext, AuthProvider };