From 54e4bbcd0681b28db8e87ba967624d61c4ec3280 Mon Sep 17 00:00:00 2001 From: lebaudantoine Date: Mon, 24 Jun 2024 16:33:09 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8(frontend)=20add=20login/logout=20Auth?= =?UTF-8?q?orization=20Code=20flow?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Quick and dirty code to initiate a login or logout flow based on user's click. The code is copied/pasted from several sources of Impress. It's dirty, and meant to be refactored. It asserts the login and logout are still functional while introducing new features in the project. --- src/frontend/visio/src/App.tsx | 90 ++++++++++++++++++++++++---------- 1 file changed, 64 insertions(+), 26 deletions(-) diff --git a/src/frontend/visio/src/App.tsx b/src/frontend/visio/src/App.tsx index afe48ac7..45793fea 100644 --- a/src/frontend/visio/src/App.tsx +++ b/src/frontend/visio/src/App.tsx @@ -1,34 +1,72 @@ -import { useState } from 'react' -import reactLogo from './assets/react.svg' -import viteLogo from '/vite.svg' +import {useEffect, useState} from 'react' import './App.css' +const API_BASE_URL = 'http://localhost:8071/api/v1.0/' + +export interface User { + id: string; + email: string; +} + +function getCSRFToken() { + return document.cookie + .split(';') + .filter((cookie) => cookie.trim().startsWith('csrftoken=')) + .map((cookie) => cookie.split('=')[1]) + .pop(); +} + +async function getMe() { + const csrfToken = getCSRFToken(); + const response = await fetch( + `${API_BASE_URL}users/me/`, + { + credentials: 'include', + headers: { + 'Content-Type': 'application/json', + ...(csrfToken && {'X-CSRFToken': csrfToken}), + }, + } + ) + if (!response.ok) { + throw new Error(`Couldn't fetch user data: ${response.statusText}`); + } + return response.json() as Promise; +} + + function App() { - const [count, setCount] = useState(0) + const [authenticatedUser, setAuthenticatedUser] = useState(null) + const [isLoading, setIsLoading] = useState(true) + + useEffect(() => { + getMe() + .then((data) => setAuthenticatedUser(data)) + .catch(() => { + console.log('user not logged-in.') + }) + .finally(() => setIsLoading(false)) + }, []) + + if (isLoading) { + return ( +
+ loading ... +
+ ) + } + + if (authenticatedUser) { + return ( +
+

You are connected as: {authenticatedUser.email}

+ +
+ ) + } return ( - <> -
- - Vite logo - - - React logo - -
-

Vite + React

-
- -

- Edit src/App.tsx and save to test HMR -

-
-

- Click on the Vite and React logos to learn more -

- + ) }