1
|
|
|
import { useEffect, useState } from 'react' |
2
|
|
|
|
3
|
|
|
import { useSelector } from 'react-redux'; |
4
|
|
|
import { RootState } from '../redux/store/store'; |
5
|
|
|
import axios, { AxiosError } from 'axios'; |
6
|
|
|
import { API_URL, getHeader } from '../helpers/config'; |
7
|
|
|
import { useNavigate } from "react-router-dom"; |
8
|
|
|
import { toast } from 'react-toastify'; |
9
|
|
|
|
10
|
|
|
|
11
|
|
|
export default function AdminGate() { |
12
|
30 |
|
const {isLoggedIn, token, user } = useSelector((state: RootState) => state.auth); |
13
|
22 |
|
const navigate = useNavigate(); |
14
|
|
|
|
15
|
22 |
|
const [myAuthorizations, setMyAuthorizations] = useState<string[]>([]) |
16
|
|
|
|
17
|
|
|
|
18
|
22 |
|
useEffect(() => { |
19
|
|
|
|
20
|
8 |
|
const getMyAuthorizations = async () => { |
21
|
8 |
|
if (isLoggedIn) { |
22
|
2 |
|
try { |
23
|
2 |
|
const response = await axios.get(`${API_URL}/auth/me`, getHeader(token)); |
24
|
2 |
|
setMyAuthorizations(response.data.roles); |
25
|
|
|
} catch (error) { |
26
|
|
|
const axiosError = error as AxiosError; |
27
|
|
|
toast.error(axiosError.message); |
28
|
|
|
setMyAuthorizations(['NotLoggedIn']); |
29
|
|
|
} |
30
|
|
|
} else { |
31
|
6 |
|
setMyAuthorizations(['NotLoggedIn']); |
32
|
|
|
} |
33
|
|
|
} |
34
|
8 |
|
getMyAuthorizations(); |
35
|
|
|
}, [user, token, isLoggedIn]) |
36
|
|
|
|
37
|
22 |
|
useEffect(() => { |
38
|
16 |
|
if (myAuthorizations.length < 1) |
39
|
8 |
|
return; |
40
|
|
|
|
41
|
8 |
|
if ( !myAuthorizations.includes("admin")) { |
42
|
7 |
|
toast.error("This page requires admin access, sending you back to homepage"); |
43
|
7 |
|
navigate("/"); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
}, [myAuthorizations, navigate]); |
47
|
22 |
|
return null; |
48
|
|
|
} |
49
|
|
|
|