frontend/src/components/AdminGate.tsx   A
last analyzed

Complexity

Total Complexity 5
Complexity/F 5

Size

Lines of Code 49
Function Count 1

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 85.71%

Importance

Changes 0
Metric Value
wmc 5
eloc 39
mnd 4
bc 4
fnc 1
dl 0
loc 49
rs 10
bpm 4
cpm 5
noi 0
c 0
b 0
f 0
ccs 18
cts 21
cp 0.8571

1 Function

Rating   Name   Duplication   Size   Complexity  
B AdminGate.tsx ➔ AdminGate 0 39 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 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