From 0c6ec386c21e6a9316c0b64ca67d1668e03fbc7e Mon Sep 17 00:00:00 2001 From: swve Date: Sat, 24 Sep 2022 20:34:11 +0200 Subject: [PATCH] feat: add authentication only component --- .../components/security/AuthenticatedOnly.tsx | 42 +++++++++++++++++++ front/pages/organizations/index.tsx | 3 ++ 2 files changed, 45 insertions(+) create mode 100644 front/components/security/AuthenticatedOnly.tsx diff --git a/front/components/security/AuthenticatedOnly.tsx b/front/components/security/AuthenticatedOnly.tsx new file mode 100644 index 00000000..8612b387 --- /dev/null +++ b/front/components/security/AuthenticatedOnly.tsx @@ -0,0 +1,42 @@ +import React from "react"; +import { getRefreshToken, getUserInfo } from "../../services/auth/auth"; +import { Auth, AuthContext } from "./AuthProvider"; + +const AuthenticatedOnly = (props: any) => { + const [auth, setAuth] = React.useState({ access_token: "", isAuthenticated: false, userInfo: {}, isLoading: true }); + + async function checkRefreshToken() { + let data = await getRefreshToken(); + return data.access_token; + } + + async function checkAuth() { + let access_token = await checkRefreshToken(); + let isAuthenticated = false; + let userInfo = {}; + let isLoading = false; + + if (access_token) { + userInfo = await getUserInfo(access_token); + isAuthenticated = true; + setAuth({ access_token, isAuthenticated, userInfo, isLoading }); + } else { + isAuthenticated = false; + setAuth({ access_token, isAuthenticated, userInfo, isLoading }); + } + } + + React.useEffect(() => { + checkAuth(); + }, []); + + return ( +
+ {auth.isLoading &&
Loading...
} + {!auth.isLoading && auth.isAuthenticated &&
{props.children}
} + {!auth.isLoading && !auth.isAuthenticated &&
Not Authenticated
} +
+ ); +}; + +export default AuthenticatedOnly; diff --git a/front/pages/organizations/index.tsx b/front/pages/organizations/index.tsx index 0a21a2ff..7967625d 100644 --- a/front/pages/organizations/index.tsx +++ b/front/pages/organizations/index.tsx @@ -1,5 +1,6 @@ import Link from "next/link"; import React from "react"; +import AuthenticatedOnly from "../../components/security/AuthenticatedOnly"; import Layout from "../../components/ui/layout"; import { Title } from "../../components/ui/styles/title"; import { deleteOrganizationFromBackend, getUserOrganizations } from "../../services/orgs"; @@ -32,6 +33,7 @@ const Organizations = () => { return ( + Your Organizations{" "} <Link href={"/organizations/new"}> @@ -59,6 +61,7 @@ const Organizations = () => { ))} </div> )} + </AuthenticatedOnly> </Layout> );