Skip to content

Commit

Permalink
save
Browse files Browse the repository at this point in the history
  • Loading branch information
AntoLC committed Sep 27, 2024
1 parent 827d8cc commit 2193d00
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 23 deletions.
6 changes: 1 addition & 5 deletions src/frontend/apps/e2e/__tests__/app-impress/common.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
import { Page, expect } from '@playwright/test';

export const keyCloakSignIn = async (page: Page, browserName: string) => {
const title = await page.locator('h1').first().textContent({
timeout: 5000,
});

const login = `user-e2e-${browserName}`;
const password = `password-e2e-${browserName}`;

if (await page.getByLabel('Restart login').isVisible()) {
await page.getByRole('textbox', { name: 'password' }).fill(password);

await page.click('input[type="submit"]', { force: true });
} else if (title?.includes('Sign in to your account')) {
} else {
await page.getByRole('textbox', { name: 'username' }).fill(login);

await page.getByRole('textbox', { name: 'password' }).fill(password);
Expand Down
12 changes: 9 additions & 3 deletions src/frontend/apps/e2e/__tests__/app-impress/doc-routing.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { expect, test } from '@playwright/test';

import { keyCloakSignIn } from './common';
import { goToGridDoc, keyCloakSignIn, mockedDocument } from './common';

test.describe('Doc Routing', () => {
test.beforeEach(async ({ page }) => {
Expand Down Expand Up @@ -43,9 +43,15 @@ test.describe('Doc Routing: Not loggued', () => {
page,
browserName,
}) => {
await page.goto('/docs/mocked-document-id/');
test.slow();
await mockedDocument(page, { link_reach: 'public' });
await goToGridDoc(page);

await expect(page.locator('h2').getByText('Mocked document')).toBeVisible();
//await page.goto('/docs/mocked-document-id/');
await page.getByRole('button', { name: 'Login' }).click();
await keyCloakSignIn(page, browserName);
await expect(page).toHaveURL(/\/docs\/mocked-document-id\/$/);
await expect(page.locator('h2').getByText('Mocked document')).toBeVisible();
});

test('The homepage redirects to login.', async ({ page }) => {
Expand Down
20 changes: 18 additions & 2 deletions src/frontend/apps/impress/src/core/auth/Auth.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Loader } from '@openfun/cunningham-react';
import { useRouter as useNavigate } from 'next/navigation';
import { useRouter } from 'next/router';
import { PropsWithChildren, useEffect, useState } from 'react';

Expand All @@ -17,8 +18,11 @@ import { useAuthStore } from './useAuthStore';
const regexpUrlsAuth = [/\/docs\/$/g, /^\/$/g];

export const Auth = ({ children }: PropsWithChildren) => {
const { initAuth, initiated, authenticated, login } = useAuthStore();
const { asPath } = useRouter();
const navigate = useNavigate();
//const replace = navigate.replace;
const { initAuth, initiated, authenticated, login, getAuthUrl } =
useAuthStore();
const { asPath, replace } = useRouter();

const [pathAllowed, setPathAllowed] = useState<boolean>(
!regexpUrlsAuth.some((regexp) => !!asPath.match(regexp)),
Expand All @@ -41,6 +45,18 @@ export const Auth = ({ children }: PropsWithChildren) => {
login();
}, [authenticated, pathAllowed, login, initiated]);

useEffect(() => {
if (!authenticated) {
return;
}

const authUrl = getAuthUrl();
if (authUrl) {
console.log('authUrl', authUrl);
void replace(authUrl);
}
}, [authenticated, getAuthUrl, replace]);

if ((!initiated && pathAllowed) || (!authenticated && !pathAllowed)) {
return (
<Box $height="100vh" $width="100vw" $align="center" $justify="center">
Expand Down
36 changes: 23 additions & 13 deletions src/frontend/apps/impress/src/core/auth/useAuthStore.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ interface AuthStore {
initAuth: () => void;
logout: () => void;
login: () => void;
setAuthUrl: (url: string) => void;
getAuthUrl: () => string | undefined;
userData?: User;
}

Expand All @@ -20,22 +22,13 @@ const initialState = {
userData: undefined,
};

export const useAuthStore = create<AuthStore>((set) => ({
export const useAuthStore = create<AuthStore>((set, get) => ({
initiated: initialState.initiated,
authenticated: initialState.authenticated,
userData: initialState.userData,

initAuth: () => {
getMe()
.then((data: User) => {
// If a path is stored in the local storage, we redirect to it
const path_auth = localStorage.getItem(PATH_AUTH_LOCAL_STORAGE);
if (path_auth) {
localStorage.removeItem(PATH_AUTH_LOCAL_STORAGE);
window.location.replace(path_auth);
return;
}

set({ authenticated: true, userData: data });
})
.catch(() => {})
Expand All @@ -46,13 +39,30 @@ export const useAuthStore = create<AuthStore>((set) => ({
login: () => {
// If we try to access a specific page and we are not authenticated
// we store the path in the local storage to redirect to it after login
if (window.location.pathname !== '/') {
localStorage.setItem(PATH_AUTH_LOCAL_STORAGE, window.location.pathname);
}

console.log('data3', window.location);
console.log('data3pathname', window.location.pathname);
get().setAuthUrl(window.location.pathname);

window.location.replace(`${baseApiUrl()}authenticate/`);
},
logout: () => {
window.location.replace(`${baseApiUrl()}logout/`);
},
setAuthUrl() {
if (window.location.pathname !== '/') {
localStorage.setItem(PATH_AUTH_LOCAL_STORAGE, window.location.pathname);
}
},
getAuthUrl() {
// If a path is stored in the local storage, we redirect to it
const path_auth = localStorage.getItem(PATH_AUTH_LOCAL_STORAGE);
console.log('data', path_auth);
if (path_auth) {
localStorage.removeItem(PATH_AUTH_LOCAL_STORAGE);
console.log('data2', path_auth);
//window.location.assign(path_auth);
return path_auth;
}
},
}));
7 changes: 7 additions & 0 deletions src/frontend/apps/impress/src/pages/docs/[id]/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useEffect, useState } from 'react';

import { Box, Text } from '@/components';
import { TextErrors } from '@/components/TextErrors';
import { useAuthStore } from '@/core/auth';
import { DocEditor } from '@/features/docs';
import { useDoc } from '@/features/docs/doc-management';
import { MainLayout } from '@/layouts';
Expand All @@ -31,6 +32,7 @@ interface DocProps {
}

const DocPage = ({ id }: DocProps) => {
const { authenticated, login } = useAuthStore();
const { data: docQuery, isError, error } = useDoc({ id });
const [doc, setDoc] = useState(docQuery);

Expand Down Expand Up @@ -58,6 +60,11 @@ const DocPage = ({ id }: DocProps) => {
return null;
}

if (error.status === 401 && !authenticated) {
login();
return null;
}

return (
<Box $margin="large">
<TextErrors
Expand Down

0 comments on commit 2193d00

Please sign in to comment.