Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Login design #412

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ type Props = {

export const AuthWrapper: React.FC<Props> = ({ onTokenChange, children }) => {
const [loggedIn, setLoggedIn] = React.useState(false);
const [discoveryLoading, setDiscoveryLoading] = React.useState(true);

const [tokenResponse, login] = useTokenResponse();
const [tokenResponse, login] = useTokenResponse(setDiscoveryLoading);

React.useEffect(() => {
if (tokenResponse) {
Expand All @@ -29,7 +30,7 @@ export const AuthWrapper: React.FC<Props> = ({ onTokenChange, children }) => {
}, [tokenResponse?.accessToken]);

if (!loggedIn) {
return <LoginScreen onLogin={login} />;
return <LoginScreen onLogin={login} isLoading={discoveryLoading} />;
}

return <>{children}</>;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Text } from 'react-native';
import { fireEvent } from '@testing-library/react-native';
import { TokenResponse } from 'expo-auth-session';
import React, { useState } from 'react';

import { render } from '../../testUtils/render';

import * as hooks from './useTokenResponse';
import { AuthWrapper } from './AuthWrapper';
import { render } from '../../../testUtils/render';
import * as hooks from '../useTokenResponse';
import { AuthWrapper } from '../AuthWrapper';

describe('Unauthenticated', () => {
it('should render the login button', () => {
Expand All @@ -16,35 +16,16 @@ describe('Unauthenticated', () => {
.spyOn(hooks, 'useTokenResponse')
.mockImplementationOnce(() => [undefined, loginSpy]);

const { getByText } = render(
const { getByTestId } = render(
<AuthWrapper onTokenChange={onTokenChangeMock}>
<Text>Success</Text>
</AuthWrapper>,
);

const button = getByText('Login');
const button = getByTestId('login-button');
expect(button).toBeTruthy();
fireEvent.press(button);
});

it('should call "login" when the button is clicked', () => {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is also being tested in the LoginScreenComponent tests

const onTokenChangeMock = jest.fn();
const loginSpy = jest.fn();

jest
.spyOn(hooks, 'useTokenResponse')
.mockImplementationOnce(() => [undefined, loginSpy]);

const { getByText } = render(
<AuthWrapper onTokenChange={onTokenChangeMock}>
<Text>Success</Text>
</AuthWrapper>,
);

const button = getByText('Login');
fireEvent.press(button);
expect(loginSpy).toHaveBeenCalled();
});
});

describe('Authenticated', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { renderHook } from '@testing-library/react-hooks';
import { waitFor } from '@testing-library/react-native';
import * as expoAuthSession from 'expo-auth-session';

import { useTokenResponse } from './useTokenResponse';
import { useTokenResponse } from '../useTokenResponse';

jest.useFakeTimers();
jest.spyOn(window, 'setInterval');
Expand Down Expand Up @@ -53,7 +53,7 @@ describe('Success', () => {
.mockResolvedValue(fakeTokenResponse);
exchangeCodeAsyncSpy.mockClear();

const { waitForNextUpdate } = renderHook(() => useTokenResponse());
const { waitForNextUpdate } = renderHook(() => useTokenResponse(jest.fn()));

expect(useAutoDiscoverySpy).toHaveBeenCalledTimes(1);
// issuer defined in core/frontend/app.json
Expand Down Expand Up @@ -124,7 +124,7 @@ describe('Success', () => {
.mockResolvedValue(fakeTokenResponse);
exchangeCodeAsyncSpy.mockClear();

const { result } = renderHook(() => useTokenResponse());
const { result } = renderHook(() => useTokenResponse(jest.fn()));
await waitFor(() => expect(result.current[0]).toEqual(fakeTokenResponse));
});

Expand Down Expand Up @@ -164,7 +164,9 @@ describe('Success', () => {
.mockResolvedValue(fakeTokenResponse);
exchangeCodeAsyncSpy.mockClear();

const { result, waitForNextUpdate } = renderHook(() => useTokenResponse());
const { result, waitForNextUpdate } = renderHook(() =>
useTokenResponse(jest.fn()),
);

result.current[1]();
expect(promptAsyncMock).toHaveBeenCalledTimes(1);
Expand Down Expand Up @@ -222,7 +224,9 @@ describe('Success', () => {
.mockResolvedValue(fakeTokenResponse);
exchangeCodeAsyncSpy.mockClear();

const { result, waitForNextUpdate } = renderHook(() => useTokenResponse());
const { result, waitForNextUpdate } = renderHook(() =>
useTokenResponse(jest.fn()),
);

expect(useAutoDiscoverySpy).toHaveBeenCalledTimes(1);
// issuer defined in core/frontend/app.json
Expand Down Expand Up @@ -318,7 +322,7 @@ describe('Failure', () => {
.mockResolvedValue(fakeTokenResponse);
exchangeCodeAsyncSpy.mockClear();

const { result } = renderHook(() => useTokenResponse());
const { result } = renderHook(() => useTokenResponse(jest.fn()));

expect(useAutoDiscoverySpy).toHaveBeenCalledTimes(1);
// issuer defined in core/frontend/app.json
Expand Down Expand Up @@ -376,7 +380,7 @@ describe('Failure', () => {
.mockResolvedValue(fakeTokenResponse);
exchangeCodeAsyncSpy.mockClear();

const { result } = renderHook(() => useTokenResponse());
const { result } = renderHook(() => useTokenResponse(jest.fn()));

expect(useAutoDiscoverySpy).toHaveBeenCalledTimes(1);
// issuer defined in core/frontend/app.json
Expand All @@ -400,7 +404,7 @@ describe('Failure', () => {
expect(result.current[0]).toBe(undefined);
});

it('should not set the token respone if exchange codes fails', () => {
it('should not set the token response if exchange codes fails', () => {
const fakeTokenResponse = new expoAuthSession.TokenResponse({
accessToken: 'fakeToken',
});
Expand Down Expand Up @@ -438,7 +442,7 @@ describe('Failure', () => {
});
exchangeCodeAsyncSpy.mockClear();

const { result } = renderHook(() => useTokenResponse());
const { result } = renderHook(() => useTokenResponse(jest.fn()));

expect(useAutoDiscoverySpy).toHaveBeenCalledTimes(1);
// issuer defined in core/frontend/app.json
Expand Down Expand Up @@ -523,7 +527,9 @@ describe('Failure', () => {
.mockResolvedValue(fakeTokenResponse);
exchangeCodeAsyncSpy.mockClear();

const { result, waitForNextUpdate } = renderHook(() => useTokenResponse());
const { result, waitForNextUpdate } = renderHook(() =>
useTokenResponse(jest.fn()),
);

expect(useAutoDiscoverySpy).toHaveBeenCalledTimes(1);
// issuer defined in core/frontend/app.json
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
useAutoDiscovery,
} from 'expo-auth-session';
import Constants from 'expo-constants';
import { useEffect } from 'react';

const getStoredTokenResponse = (): TokenResponse | undefined => {
try {
Expand Down Expand Up @@ -37,10 +38,9 @@ const storeTokenResponse = (tokenResponse: TokenResponse) => {
}
};

export const useTokenResponse = (): [
TokenResponse | undefined,
() => Promise<void>,
] => {
export const useTokenResponse = (
setDiscoveryLoading: React.Dispatch<React.SetStateAction<boolean>>,
): [TokenResponse | undefined, () => Promise<void>] => {
const [tokenResponse, setTokenResponse] = React.useState<
TokenResponse | undefined
>(getStoredTokenResponse());
Expand All @@ -58,6 +58,12 @@ export const useTokenResponse = (): [
const discovery = useAutoDiscovery(Constants.manifest?.extra?.issuer);
const clientId = Constants.manifest?.extra?.client_id;

useEffect(() => {
if (discovery) {
setDiscoveryLoading(false);
}
}, [JSON.stringify(discovery)]);

const [request, response, promptAsync] = useAuthRequest(
{
clientId,
Expand Down
8 changes: 6 additions & 2 deletions frontend/apps/core-app/src/components/NavHeader/logout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import * as AuthSession from 'expo-auth-session';
import { openAuthSessionAsync } from 'expo-web-browser';
import Constants from 'expo-constants';

import { formsClient } from '../../clients/formsClient';

const authorizationEndpoint = `${Constants.manifest?.extra?.issuer}/oauth2/sessions/logout`;
const redirectUri = AuthSession.makeRedirectUri({ useProxy: false });

Expand All @@ -12,10 +14,12 @@ export const logout = async () => {
`${authorizationEndpoint}?post_logout_redirect=${redirectUri}`,
'redirectUrl',
);
} catch (err) {
console.error(err);
} finally {
if (Platform.OS === 'web') {
sessionStorage.removeItem('tokenResponse');
}
} catch (err) {
console.error(err);
formsClient.setToken('');
}
};
Original file line number Diff line number Diff line change
@@ -1,18 +1,49 @@
import * as React from 'react';
import { Button } from 'native-base';

import * as Styles from './LoginScreen.styles';
import { Box, Button, Text } from 'native-base';
import { Logo } from 'core-design-system';

type Props = {
onLogin: () => any;
isLoading: boolean;
};

export const LoginScreenComponent: React.FC<Props> = ({ onLogin }) => {
export const LoginScreenComponent: React.FC<Props> = ({
onLogin,
isLoading,
}) => {
return (
<Styles.Container>
<Button onPress={onLogin} color="primary" variant="major">
Login
</Button>
</Styles.Container>
<Box height="100%" flexDirection="row">
<Box
pl="130px"
pt="40px"
justifyContent="flex-start"
alignItems="flex-start"
width="700px"
maxWidth="700px"
height="100%"
bg="red"
zIndex={1}
>
<Logo size="65px" pb="55px" />
<Text variant="heading" level="1" mb="40px">
Login
</Text>
<Text variant="body" level="1" mb="35px">
Access to your personal account
</Text>
<Button
onPress={onLogin}
color="primary"
variant="major"
w="440px"
isLoading={isLoading}
testID="login-button"
>
Login
</Button>
</Box>

<Box flexGrow="1" bg="neutral.200" />
</Box>
);
};

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,26 @@ import { LoginScreenComponent } from '../LoginScreen.component';

it('should match the snapshot', () => {
const login = jest.fn();
const { toJSON } = render(<LoginScreenComponent onLogin={login} />);
const { toJSON } = render(
<LoginScreenComponent onLogin={login} isLoading={false} />,
);
expect(toJSON()).toMatchSnapshot();
});

it('should call login on click', () => {
const login = jest.fn();
const { getByText } = render(<LoginScreenComponent onLogin={login} />);
fireEvent.press(getByText('Login'));
const { getByTestId } = render(
<LoginScreenComponent onLogin={login} isLoading={false} />,
);
fireEvent.press(getByTestId('login-button'));
expect(login).toHaveBeenCalled();
});

it('should not call login on click when loading', () => {
const login = jest.fn();
const { getByTestId } = render(
<LoginScreenComponent onLogin={login} isLoading />,
);
fireEvent.press(getByTestId('login-button'));
expect(login).not.toHaveBeenCalled();
});
Loading