Test Failed
Pull Request — development (#77)
by Vad
11:33
created

frontend/src/components/AdminGate.tsx   A

Complexity

Total Complexity 5
Complexity/F 5

Size

Lines of Code 48
Function Count 1

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 39
dl 0
loc 48
rs 10
c 0
b 0
f 0
wmc 5
mnd 4
bc 4
fnc 1
bpm 4
cpm 5
noi 0

1 Function

Rating   Name   Duplication   Size   Complexity  
B AdminGate.tsx ➔ AdminGate 0 38 5
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
    const {isLoggedIn, token, user } = useSelector((state: RootState) =>  state.auth);
13
    const navigate = useNavigate();
14
15
    const [myAuthorizations, setMyAuthorizations] = useState<string[]>([])
16
17
    const getMyAuthorizations = async () => {
18
        if (isLoggedIn) {
19
                try {
20
                    const response = await axios.get(`${API_URL}/auth/me`, getHeader(token));
21
                    setMyAuthorizations(response.data.roles);
22
                } catch (error) {
23
                    const axiosError = error as AxiosError;
24
                    toast.error(axiosError.message);
25
                    setMyAuthorizations(['NotLoggedIn']);
26
                }
27
            }  else {
28
                setMyAuthorizations(['NotLoggedIn']);
29
            }
30
        }
31
   
32
    useEffect(() => {
33
        getMyAuthorizations();
34
    }, [user, isLoggedIn, token])
35
36
    useEffect(() => {
37
        if (myAuthorizations.length < 1) 
38
            return;
39
40
        if ( !myAuthorizations.includes("admin")) {
41
            toast.error("This page requires admin access, sending you back to homepage");
42
            navigate("/");
43
        } 
44
   
45
    }, [myAuthorizations]);
46
  return null;
47
}
48