Skip to content

Commit

Permalink
watch for window activation and check auth
Browse files Browse the repository at this point in the history
  • Loading branch information
suddjian committed Feb 17, 2022
1 parent 0ff9e56 commit d99a5c0
Show file tree
Hide file tree
Showing 4 changed files with 143 additions and 1 deletion.
78 changes: 78 additions & 0 deletions superset-frontend/src/hooks/useWindowActivatedAuthCheck.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import { fireEvent, waitFor } from '@testing-library/dom';
import { render } from '@testing-library/react';
import fetchMock from 'fetch-mock';

jest.useFakeTimers();

import { useWindowActivatedAuthCheck } from './useWindowActivatedAuthCheck';

const HookTester = () => {
useWindowActivatedAuthCheck();
return <>hook tester</>;
};

describe('useWindowActivatedAuthCheck', () => {
beforeEach(() => {
// jsdom doesn't support window location, so just gonna fake it here real simple-like
Object.defineProperty(window, 'location', {
value: {
href: 'http://example.com/fake-test-page',
pathname: '/fake-test-page',
search: '?foo=bar',
},
writable: true,
});
});

afterEach(() => {
fetchMock.restore();
});

it('redirects when the user tabs back after logging out elsewhere', async () => {
fetchMock.get('glob:*/api/v1/me/', { status: 401 });

render(<HookTester />);

fireEvent(document, new Event('visibilitychange'));

await waitFor(() => {
expect(window.location.href).toEqual(
'/login?next=/fake-test-page?foo=bar',
);
});
});

it('does not redirect if the user is still logged in', async () => {
fetchMock.get('glob:*/api/v1/me/', {
status: 200,
json: { username: 'test_user' },
});

render(<HookTester />);

fireEvent(document, new Event('visibilitychange'));

await jest.runAllTimers();

expect(window.location.href).toEqual('http://example.com/fake-test-page');
});
});
52 changes: 52 additions & 0 deletions superset-frontend/src/hooks/useWindowActivatedAuthCheck.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { useEffect } from 'react';
import { makeApi } from '@superset-ui/core';
import { User } from 'src/types/bootstrapTypes';

const getMe = makeApi<void, User>({
method: 'GET',
endpoint: '/api/v1/me/',
});

/**
* When the window becomes visible, checks for the current auth state.
* If we get a 401, we are no longer logged in and the SupersetClient will redirect us.
* This ensures that if you log out in browser tab A, and click to tab B,
* tab B will also display as logged out.
*/
export function useWindowActivatedAuthCheck() {
useEffect(() => {
const listener = () => {
// we only care about the tab becoming visible, not vice versa
if (document.visibilityState !== 'visible') return;

getMe().catch(() => {
// ignore error, SupersetClient will redirect to login on a 401
});
};

document.addEventListener('visibilitychange', listener);

return () => {
document.removeEventListener('visibilitychange', listener);
};
}, []);
}
3 changes: 2 additions & 1 deletion superset-frontend/src/preamble.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,14 @@ import setupClient from './setup/setupClient';
import setupColors from './setup/setupColors';
import setupFormatters from './setup/setupFormatters';
import setupDashboardComponents from './setup/setupDasboardComponents';
import { User } from './types/bootstrapTypes';

if (process.env.WEBPACK_MODE === 'development') {
setHotLoaderConfig({ logLevel: 'debug', trackTailUpdates: false });
}

// eslint-disable-next-line import/no-mutable-exports
export let bootstrapData: any;
export let bootstrapData: { user?: User | undefined; common?: any } = {};
// Configure translation
if (typeof window !== 'undefined') {
const root = document.getElementById('app');
Expand Down
11 changes: 11 additions & 0 deletions superset-frontend/src/views/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import setupApp from 'src/setup/setupApp';
import { routes, isFrontendRoute } from 'src/views/routes';
import { Logger } from 'src/logger/LogUtils';
import { RootContextProviders } from './RootContextProviders';
import { useWindowActivatedAuthCheck } from 'src/hooks/useWindowActivatedAuthCheck';

setupApp();

Expand All @@ -55,8 +56,18 @@ const LocationPathnameLogger = () => {
return <></>;
};

/** This component is just here so we can conditionally call this hook */
const AuthVigilance = () => {
useWindowActivatedAuthCheck();
return <></>;
};

const App = () => (
<Router>
{
// only check auth on window visibility change if the user is actually logged in in the first place
user?.isActive && <AuthVigilance />
}
<LocationPathnameLogger />
<RootContextProviders>
<Menu data={menu} isFrontendRoute={isFrontendRoute} />
Expand Down

0 comments on commit d99a5c0

Please sign in to comment.