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