Skip to content
This repository has been archived by the owner on Oct 24, 2024. It is now read-only.

[okta-react] fixes SecureRoute to only run logic if route matches #903

Merged
merged 2 commits into from
Sep 10, 2020
Merged
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
9 changes: 7 additions & 2 deletions packages/okta-react/src/SecureRoute.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,22 @@

import React, { useEffect } from 'react';
import { useOktaAuth } from './OktaContext';
import { Route } from 'react-router-dom';
import { Route, useRouteMatch } from 'react-router-dom';

const SecureRoute = ( props ) => {
const { authService, authState } = useOktaAuth();
const match = useRouteMatch(props);

useEffect(() => {
// Only process logic if the route matches
if (!match) {
return;
}
// Start login if and only if app has decided it is not logged inn
if(!authState.isAuthenticated && !authState.isPending) {
authService.login();
}
}, [authState.isPending, authState.isAuthenticated, authService]);
}, [authState.isPending, authState.isAuthenticated, authService, match]);

if (!authState.isAuthenticated) {
return null;
Expand Down
15 changes: 13 additions & 2 deletions packages/okta-react/test/jest/secureRoute.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,16 +132,27 @@ describe('<SecureRoute />', () => {
authState.isPending = false;
});

it('calls login()', () => {
it('calls login() if route matches', () => {
mount(
<MemoryRouter>
<Security {...mockProps}>
<SecureRoute />
<SecureRoute path="/" />
</Security>
</MemoryRouter>
);
expect(authService.login).toHaveBeenCalled();
});

it('does not call login() if route does not match', () => {
mount(
<MemoryRouter>
<Security {...mockProps}>
<SecureRoute path="/other" />
</Security>
</MemoryRouter>
);
expect(authService.login).not.toHaveBeenCalled();
});
});

describe('isPending: true', () => {
Expand Down