1 | import logo from './logo.svg';
|
---|
2 | import './App.css';
|
---|
3 | import {useDispatch, useSelector} from "react-redux";
|
---|
4 | import {BrowserRouter} from "react-router-dom";
|
---|
5 | import {Header} from "./views/static/Header";
|
---|
6 | import RoutesConfig from "./auth/RoutesConfig";
|
---|
7 | import React, {useEffect, useState} from "react";
|
---|
8 | import {AuthActions} from "./redux/actions/authActions";
|
---|
9 | import {AUTH_TOKEN} from "./axios/axiosInstance";
|
---|
10 | import {jwtDecode} from "jwt-decode";
|
---|
11 | import {NoAccess} from "./views/static/NoAccess";
|
---|
12 | import {Loading} from "./views/static/Loading";
|
---|
13 | import {ToastContainer} from "react-toastify";
|
---|
14 |
|
---|
15 | function App() {
|
---|
16 | const dispatch = useDispatch();
|
---|
17 |
|
---|
18 | useEffect(() => {
|
---|
19 | dispatch(AuthActions.updateToken(localStorage.getItem(AUTH_TOKEN)))
|
---|
20 | }, [dispatch])
|
---|
21 |
|
---|
22 | const [user, setUser] = useState(null);
|
---|
23 | const [loading, setLoading] = useState(true);
|
---|
24 | const [minimumLoadingTime, setMinimumLoadingTime] = useState(true);
|
---|
25 |
|
---|
26 | const auth = useSelector(state => state.auth);
|
---|
27 |
|
---|
28 | useEffect(() => {
|
---|
29 | // Simulate a minimum loading time of 1 second
|
---|
30 | const timer = setTimeout(() => {
|
---|
31 | setMinimumLoadingTime(false);
|
---|
32 | }, 1000);
|
---|
33 |
|
---|
34 | // Clear timeout if component unmounts
|
---|
35 | return () => clearTimeout(timer);
|
---|
36 | }, []);
|
---|
37 |
|
---|
38 | useEffect(() => {
|
---|
39 | const token = localStorage.getItem(AUTH_TOKEN);
|
---|
40 | if (token !== null) {
|
---|
41 | try {
|
---|
42 | const decodedToken = jwtDecode(token);
|
---|
43 | setUser({
|
---|
44 | name: decodedToken.name,
|
---|
45 | role: decodedToken.role,
|
---|
46 | hasAccess: decodedToken.access,
|
---|
47 | id: decodedToken.id
|
---|
48 | });
|
---|
49 | setLoading(false);
|
---|
50 | } catch (error) {
|
---|
51 | console.error('Failed to decode token', error);
|
---|
52 | setLoading(false);
|
---|
53 | }
|
---|
54 | } else {
|
---|
55 | setLoading(false);
|
---|
56 | }
|
---|
57 | }, [auth]);
|
---|
58 |
|
---|
59 | if (loading || minimumLoadingTime) {
|
---|
60 | return <Loading />; // Replace LoadingSpinner with your loading indicator component
|
---|
61 | }
|
---|
62 |
|
---|
63 | return (
|
---|
64 | <div className="App">
|
---|
65 | <BrowserRouter>
|
---|
66 | {user === null ? (
|
---|
67 | <>
|
---|
68 | <Header />
|
---|
69 | <RoutesConfig />
|
---|
70 | </>
|
---|
71 | ) : user.hasAccess ? (
|
---|
72 | <>
|
---|
73 | <Header />
|
---|
74 | <RoutesConfig />
|
---|
75 | {/*<Loading/>*/}
|
---|
76 | </>
|
---|
77 | ) : (
|
---|
78 | <NoAccess user={user}/>
|
---|
79 | )}
|
---|
80 | </BrowserRouter>
|
---|
81 | <ToastContainer/>
|
---|
82 | </div>
|
---|
83 | );
|
---|
84 | }
|
---|
85 |
|
---|
86 | export default App;
|
---|