Skip to content
This repository has been archived by the owner on Jul 26, 2022. It is now read-only.

Commit

Permalink
[okta-react] fixes SecureRoute to only run logic if route matches
Browse files Browse the repository at this point in the history
  • Loading branch information
aarongranick-okta committed Sep 9, 2020
1 parent 4751348 commit 7ee4660
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
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

0 comments on commit 7ee4660

Please sign in to comment.