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

Enhance/4819 auth dependent components #5078

Merged
merged 7 commits into from
Apr 12, 2022
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
112 changes: 112 additions & 0 deletions assets/js/components/PermissionsModal/AuthenticatedPermissionsModal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/**
* AuthenticatedPermissionsModal component.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed 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
*
* https://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.
*/

/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { useEffect, useCallback } from '@wordpress/element';

/**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import { CORE_USER } from '../../googlesitekit/datastore/user/constants';
import { CORE_LOCATION } from '../../googlesitekit/datastore/location/constants';
import { snapshotAllStores } from '../../googlesitekit/data/create-snapshot-store';
import Dialog from '../Dialog';
import Portal from '../Portal';
const { useSelect, useDispatch, useRegistry } = Data;

const AuthenticatedPermissionsModal = () => {
const registry = useRegistry();
const permissionsError = useSelect( ( select ) =>
select( CORE_USER ).getPermissionScopeError()
);
const connectURL = useSelect( ( select ) =>
select( CORE_USER ).getConnectURL( {
additionalScopes: permissionsError?.data?.scopes,
redirectURL: global.location.href,
} )
);

const { clearPermissionScopeError } = useDispatch( CORE_USER );
const { navigateTo } = useDispatch( CORE_LOCATION );

const onCancel = useCallback( () => {
clearPermissionScopeError();
}, [ clearPermissionScopeError ] );

const onConfirm = useCallback( async () => {
// If we have a datastores to snapshot before navigating away to the
// authorization page, do that first.
await snapshotAllStores( registry );
navigateTo( connectURL );
}, [ registry, connectURL, navigateTo ] );

useEffect( () => {
// If error has flag to skip the modal, redirect to the authorization
// page immediately without prompting the user, essentially short-
// circuiting to the confirm step.
const confirmIfSkipModal = async () => {
if (
permissionsError?.data?.skipModal &&
permissionsError?.data?.scopes?.length
) {
await onConfirm();
}
};
confirmIfSkipModal();
}, [ onConfirm, permissionsError ] );

if ( ! permissionsError ) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

It looks like this can potentially return undefined, which I was assuming is from it resolving and returning undefined during that, but it appears that actually isn't the case… it's either null or an error.

But the docs say it can return undefined:

/**
* Gets the most recent permission error encountered by this user.
*
* @since 1.9.0
* @private
*
* @param {Object} state Data store's state.
* @return {(Object|undefined)} Permission scope errors. Returns `null` if no error exists.
*/
getPermissionScopeError( state ) {
const { permissionError } = state;
return permissionError;
},

This isn't related to your change, but we should update the JSDoc for getPermissionScopeError so it doesn't trip anyone else up. Looks like it should be @return {(Object|undefined)} not @return {(Object|null)}

Copy link
Collaborator

Choose a reason for hiding this comment

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

Worse: I think it was me who wrong that JSDoc. Shame! 😆

return null;
}

// If there aren't any scopes for us to request, there's no reason to show
// the modal. Log a console warning if this happens and return `null`.
if ( ! permissionsError?.data?.scopes?.length ) {
global.console.warn(
'permissionsError lacks scopes array to use for redirect, so not showing the PermissionsModal. permissionsError was:',
permissionsError
);
return null;
}

if ( permissionsError?.data?.skipModal ) {
return null;
}

return (
<Portal>
<Dialog
title={ __(
'Additional Permissions Required',
'google-site-kit'
) }
subtitle={ permissionsError.message }
confirmButton={ __( 'Proceed', 'google-site-kit' ) }
dialogActive={ true }
handleConfirm={ onConfirm }
handleDialog={ onCancel }
/>
</Portal>
);
};

export default AuthenticatedPermissionsModal;
87 changes: 7 additions & 80 deletions assets/js/components/PermissionsModal/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,97 +16,24 @@
* limitations under the License.
*/

/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { useEffect, useCallback } from '@wordpress/element';

/**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import AuthenticatedPermissionsModal from './AuthenticatedPermissionsModal';
import { CORE_USER } from '../../googlesitekit/datastore/user/constants';
import { CORE_LOCATION } from '../../googlesitekit/datastore/location/constants';
import { snapshotAllStores } from '../../googlesitekit/data/create-snapshot-store';
import Dialog from '../Dialog';
import Portal from '../Portal';
const { useSelect, useDispatch, useRegistry } = Data;
const { useSelect } = Data;

const PermissionsModal = () => {
const registry = useRegistry();
const permissionsError = useSelect( ( select ) =>
select( CORE_USER ).getPermissionScopeError()
);
const connectURL = useSelect( ( select ) =>
select( CORE_USER ).getConnectURL( {
additionalScopes: permissionsError?.data?.scopes,
redirectURL: global.location.href,
} )
const isAuthenticated = useSelect( ( select ) =>
select( CORE_USER ).isAuthenticated()
);

const { clearPermissionScopeError } = useDispatch( CORE_USER );
const { navigateTo } = useDispatch( CORE_LOCATION );

const onCancel = useCallback( () => {
clearPermissionScopeError();
}, [ clearPermissionScopeError ] );

const onConfirm = useCallback( async () => {
// If we have a datastores to snapshot before navigating away to the
// authorization page, do that first.
await snapshotAllStores( registry );
navigateTo( connectURL );
}, [ registry, connectURL, navigateTo ] );

useEffect( () => {
// If error has flag to skip the modal, redirect to the authorization
// page immediately without prompting the user, essentially short-
// circuiting to the confirm step.
const confirmIfSkipModal = async () => {
if (
permissionsError?.data?.skipModal &&
permissionsError?.data?.scopes?.length
) {
await onConfirm();
}
};
confirmIfSkipModal();
}, [ onConfirm, permissionsError ] );

if ( ! permissionsError ) {
return null;
}

// If there aren't any scopes for us to request, there's no reason to show
// the modal. Log a console warning if this happens and return `null`.
if ( ! permissionsError?.data?.scopes?.length ) {
global.console.warn(
'permissionsError lacks scopes array to use for redirect, so not showing the PermissionsModal. permissionsError was:',
permissionsError
);
return null;
if ( isAuthenticated ) {
return <AuthenticatedPermissionsModal />;
}

if ( permissionsError?.data?.skipModal ) {
return null;
}

return (
<Portal>
<Dialog
title={ __(
'Additional Permissions Required',
'google-site-kit'
) }
subtitle={ permissionsError.message }
confirmButton={ __( 'Proceed', 'google-site-kit' ) }
dialogActive={ true }
handleConfirm={ onConfirm }
handleDialog={ onCancel }
/>
</Portal>
);
return null;
};

export default PermissionsModal;
64 changes: 64 additions & 0 deletions assets/js/components/PermissionsModal/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* PermissionsModal component tests.
*
* Site Kit by Google, Copyright 2022 Google LLC
*
* Licensed 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
*
* https://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.
*/

/**
* Internal dependencies
*/
import PermissionsModal from './';
import {
render,
createTestRegistry,
provideUserAuthentication,
} from '../../../../tests/js/test-utils';
import { CORE_USER } from '../../googlesitekit/datastore/user/constants';

describe( 'PermissionsModal', () => {
let registry;

beforeEach( () => {
registry = createTestRegistry();
registry.dispatch( CORE_USER ).receiveConnectURL( 'test-url' );
registry.dispatch( CORE_USER ).setPermissionScopeError( {
status: 500,
message: 'Bad',
data: {
scopes: [
'https://www.googleapis.com/auth/analytics.readonly',
],
},
} );
} );

it( 'does not render AuthenticatedPermissionsModal when user is not authenticated', () => {
provideUserAuthentication( registry, { authenticated: false } );
const { baseElement } = render( <PermissionsModal />, { registry } );

expect( baseElement ).not.toHaveTextContent(
'Additional Permissions Required'
);
} );

it( 'renders AuthenticatedPermissionsModal when user is authenticated', () => {
provideUserAuthentication( registry );
const { baseElement } = render( <PermissionsModal />, { registry } );

expect( baseElement ).toHaveTextContent(
'Additional Permissions Required'
);
} );
} );
8 changes: 7 additions & 1 deletion assets/js/components/notifications/ErrorNotifications.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,22 @@ import { Fragment } from '@wordpress/element';
/**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import AuthError from './AuthError';
import UnsatisfiedScopesAlert from './UnsatisfiedScopesAlert';
import InternalServerError from './InternalServerError';
import { CORE_USER } from '../../googlesitekit/datastore/user/constants';
const { useSelect } = Data;

export default function ErrorNotifications() {
const isAuthenticated = useSelect( ( select ) =>
select( CORE_USER ).isAuthenticated()
);
return (
<Fragment>
<InternalServerError />
<AuthError />
<UnsatisfiedScopesAlert />
{ isAuthenticated && <UnsatisfiedScopesAlert /> }
</Fragment>
);
}
67 changes: 67 additions & 0 deletions assets/js/components/notifications/ErrorNotifications.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/**
* ErrorNotifications component tests.
*
* Site Kit by Google, Copyright 2022 Google LLC
*
* Licensed 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
*
* https://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.
*/

/**
* Internal dependencies
*/
import ErrorNotifications from './ErrorNotifications';
import {
render,
createTestRegistry,
provideUserAuthentication,
provideModules,
} from '../../../../tests/js/test-utils';
import { CORE_USER } from '../../googlesitekit/datastore/user/constants';

describe( 'ErrorNotifications', () => {
let registry;

beforeEach( () => {
registry = createTestRegistry();
provideModules( registry );
registry.dispatch( CORE_USER ).receiveConnectURL( 'test-url' );
} );

it( 'does not render UnsatisfiedScopesAlert when user is not authenticated', () => {
provideUserAuthentication( registry, {
authenticated: false,
unsatisfiedScopes: [
'https://www.googleapis.com/auth/analytics.readonly',
],
} );
const { container } = render( <ErrorNotifications />, {
registry,
} );
expect( container.childElementCount ).toBe( 0 );
} );

it( 'renders UnsatisfiedScopesAlert when user is authenticated', () => {
provideUserAuthentication( registry, {
unsatisfiedScopes: [
'https://www.googleapis.com/auth/analytics.readonly',
],
} );
const { container } = render( <ErrorNotifications />, {
registry,
} );

expect( container ).toHaveTextContent(
'Site Kit can’t access necessary data'
);
} );
} );
2 changes: 1 addition & 1 deletion assets/js/googlesitekit/datastore/user/permissions.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ export const selectors = {
* @private
*
* @param {Object} state Data store's state.
* @return {(Object|undefined)} Permission scope errors. Returns `null` if no error exists.
* @return {(Object|null)} Permission scope errors. Returns `null` if no error exists.
*/
getPermissionScopeError( state ) {
const { permissionError } = state;
Expand Down