From f32fe4faa5c841a9f3de9ec1a3945342890ec0c6 Mon Sep 17 00:00:00 2001 From: Alberto Defendi <1369-ahl-berto@users.noreply.gitlab.inf.unibz.it> Date: Thu, 27 May 2021 09:13:40 +0200 Subject: [PATCH] Reintegrate lost folder. --- src/hooks/useAuth.ts | 28 ++++++++++++++++++++++++++++ src/hooks/useCookie.ts | 27 +++++++++++++++++++++++++++ src/hooks/useRole.ts | 24 ++++++++++++++++++++++++ 3 files changed, 79 insertions(+) create mode 100644 src/hooks/useAuth.ts create mode 100644 src/hooks/useCookie.ts create mode 100644 src/hooks/useRole.ts diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.ts new file mode 100644 index 0000000..0479313 --- /dev/null +++ b/src/hooks/useAuth.ts @@ -0,0 +1,28 @@ +import { isAuthenticated } from 'api/isAuthenticated'; +import { useEffect, useState } from 'react'; + +/** + * Custom hook that uses the call is_authenticated. + * {@link isAuthenticated} + * + * @returns {boolean | null} isAuth: true if user is authenticated, false otherwise or null if the request has not finished. + */ +export const useAuth = (): [ + boolean, + React.Dispatch<React.SetStateAction<boolean>>, +] => { + let isMounted = true; + const [isAuth, setIsAuth] = useState<boolean>(false); + useEffect(() => { + isAuthenticated().then((state) => { + if (isMounted) { + setIsAuth(state); + } + }); + + return () => { + isMounted = false; + }; + }, []); + return [isAuth, setIsAuth]; +}; diff --git a/src/hooks/useCookie.ts b/src/hooks/useCookie.ts new file mode 100644 index 0000000..d2fc2ea --- /dev/null +++ b/src/hooks/useCookie.ts @@ -0,0 +1,27 @@ +import { fetchCookie } from 'api/fetchCookie'; +import { useCallback, useEffect, useState } from 'react'; + +/** + * Custom hook that return csrf cookie fetched from server. + * + * @return cookie + */ +export const useCookie = (): string => { + const [cookie, setCookie] = useState(''); + + const askCookie = useCallback(() => { + let isMounted = true; + if (isMounted) + fetchCookie().then((cookieResponse) => setCookie(cookieResponse)); + + return () => { + isMounted = false; + }; + }, []); + + useEffect(() => { + askCookie(); + }, [askCookie]); + + return cookie; +}; diff --git a/src/hooks/useRole.ts b/src/hooks/useRole.ts new file mode 100644 index 0000000..785a979 --- /dev/null +++ b/src/hooks/useRole.ts @@ -0,0 +1,24 @@ +import { getRole } from 'api/getRole'; +import { useEffect, useState } from 'react'; + +export const useRole = (): [ + string, + React.Dispatch<React.SetStateAction<string>>, +] => { + const [role, setRole] = useState(''); + + useEffect(() => { + let isMounted = true; + // Initialize asking the server if this session is already logged in. + + getRole().then((responseRole) => { + if (isMounted) { + setRole(responseRole); + } + }); + return () => { + isMounted = false; + }; + }, []); + return [role, setRole]; +}; -- GitLab