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

[RFR] Add auth hooks #3368

Merged
merged 18 commits into from
Jul 1, 2019
Merged
Show file tree
Hide file tree
Changes from 6 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
55 changes: 20 additions & 35 deletions examples/simple/src/customRouteLayout.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,23 @@
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { crudGetList as crudGetListAction, Title } from 'react-admin'; // eslint-disable-line import/no-unresolved
import React from 'react';
import { useGetList, useAuth, Title } from 'react-admin';

class CustomRouteLayout extends Component {
componentWillMount() {
this.props.crudGetList(
'posts',
{ page: 0, perPage: 10 },
{ field: 'id', order: 'ASC' }
);
}
const CustomRouteLayout = () => {
useAuth();
const { total, loaded } = useGetList(
'posts',
{ page: 1, perPage: 10 },
{ field: 'published_at', order: 'DESC' }
);

render() {
const { total } = this.props;
return loaded ? (
<div>
<Title title="Example Admin" />
<h1>Posts</h1>
<p>
Found <span className="total">{total}</span> posts !
</p>
</div>
) : null;
};

return (
<div>
<Title title="Example Admin" />
<h1>Posts</h1>
<p>
Found <span className="total">{total}</span> posts !
</p>
</div>
);
}
}

const mapStateToProps = state => ({
total: state.admin.resources.posts
? state.admin.resources.posts.list.total
: 0,
});

export default connect(
mapStateToProps,
{ crudGetList: crudGetListAction }
)(CustomRouteLayout);
export default CustomRouteLayout;
2 changes: 1 addition & 1 deletion packages/ra-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"@redux-saga/testing-utils": "^1.0.2",
"@types/history": "^4.7.2",
"@types/node-polyglot": "^0.4.31",
"@types/react-router": "^4.4.4",
"@types/react-router": "^5.0.1",
"@types/react-router-dom": "^4.3.1",
"@types/recompose": "^0.27.0",
"@types/redux-form": "^7.5.2",
Expand Down
48 changes: 21 additions & 27 deletions packages/ra-core/src/CoreAdmin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Switch, Route } from 'react-router-dom';
import { ConnectedRouter } from 'connected-react-router';
import withContext from 'recompose/withContext';

import AuthContext from './auth/AuthContext';
import createAdminStore from './createAdminStore';
import TranslationProvider from './i18n/TranslationProvider';
import CoreAdminRouter from './CoreAdminRouter';
Expand Down Expand Up @@ -55,11 +56,7 @@ interface AdminContext {
authProvider: AuthProvider;
}

class CoreAdminBase extends Component<AdminProps> {
static contextTypes = {
store: PropTypes.object,
};

class CoreAdmin extends Component<AdminProps> {
static defaultProps: Partial<AdminProps> = {
catchAll: () => null,
layout: DefaultLayout,
Expand Down Expand Up @@ -174,31 +171,28 @@ React-admin requires a valid dataProvider function to work.`);
} = this.props;

return this.reduxIsAlreadyInitialized ? (
this.renderCore()
) : (
<Provider
store={createAdminStore({
authProvider,
customReducers,
customSagas,
dataProvider,
i18nProvider,
initialState,
locale,
history: this.history,
})}
>
<AuthContext.Provider value={authProvider}>
{this.renderCore()}
</Provider>
</AuthContext.Provider>
) : (
<AuthContext.Provider value={authProvider}>
<Provider
store={createAdminStore({
authProvider,
customReducers,
customSagas,
dataProvider,
i18nProvider,
initialState,
locale,
history: this.history,
})}
>
{this.renderCore()}
</Provider>
</AuthContext.Provider>
);
}
}

const CoreAdmin = withContext<AdminContext, AdminProps>(
{
authProvider: PropTypes.func,
},
({ authProvider }) => ({ authProvider })
)(CoreAdminBase) as ComponentType<AdminProps>;

export default CoreAdmin;
157 changes: 89 additions & 68 deletions packages/ra-core/src/CoreAdminRouter.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,94 +1,115 @@
import React from 'react';
import { shallow } from 'enzyme';
import assert from 'assert';
import { Route } from 'react-router-dom';
import { cleanup, wait } from 'react-testing-library';
import expect from 'expect';
import { Router, Route } from 'react-router-dom';
import { createMemoryHistory } from 'history';

import renderWithRedux from './util/renderWithRedux';
import { CoreAdminRouter } from './CoreAdminRouter';
import AuthContext from './auth/AuthContext';
import Resource from './Resource';

const Layout = ({ children }) => <div>Layout {children}</div>;

describe('<AdminRouter>', () => {
afterEach(cleanup);

const defaultProps = {
authProvider: () => Promise.resolve(),
userLogout: () => <span />,
customRoutes: [],
};

describe('With resources as regular children', () => {
it('should render all resources with a registration intent', () => {
const wrapper = shallow(
<CoreAdminRouter {...defaultProps}>
<Resource name="posts" />
<Resource name="comments" />
</CoreAdminRouter>
);

const resources = wrapper.find('ConnectFunction');

assert.equal(resources.length, 2);
assert.deepEqual(
resources.map(resource => resource.prop('intent')),
['registration', 'registration']
it('should render all resources in routes', () => {
const history = createMemoryHistory();
const { getByText } = renderWithRedux(
<Router history={history}>
<CoreAdminRouter {...defaultProps} layout={Layout}>
<Resource
name="posts"
list={() => <span>PostList</span>}
/>
<Resource
name="comments"
list={() => <span>CommentList</span>}
/>
</CoreAdminRouter>
</Router>
);
expect(getByText('Layout')).toBeDefined();
history.push('/posts');
expect(getByText('PostList')).toBeDefined();
history.push('/comments');
expect(getByText('CommentList')).toBeDefined();
});
});

describe('With resources returned from a function as children', () => {
it('should render all resources with a registration intent', async () => {
const wrapper = shallow(
<CoreAdminRouter {...defaultProps}>
{() => [
<Resource key="posts" name="posts" />,
<Resource key="comments" name="comments" />,
null,
]}
</CoreAdminRouter>
const history = createMemoryHistory();
const { getByText } = renderWithRedux(
<AuthContext.Provider value={() => Promise.resolve()}>
<Router history={history}>
<CoreAdminRouter {...defaultProps} layout={Layout}>
{() => [
<Resource
key="posts"
name="posts"
list={() => <span>PostList</span>}
/>,
<Resource
key="comments"
name="comments"
list={() => <span>CommentList</span>}
/>,
null,
]}
</CoreAdminRouter>
</Router>
</AuthContext.Provider>
);

// Timeout needed because of the authProvider call
await new Promise(resolve => {
setTimeout(resolve, 10);
});

wrapper.update();
const resources = wrapper.find('ConnectFunction');
assert.equal(resources.length, 2);
assert.deepEqual(
resources.map(resource => resource.prop('intent')),
['registration', 'registration']
);
await wait();
expect(getByText('Layout')).toBeDefined();
history.push('/posts');
expect(getByText('PostList')).toBeDefined();
history.push('/comments');
expect(getByText('CommentList')).toBeDefined();
});
});

it('should render the custom routes which do not need a layout', () => {
const Bar = () => <div>Bar</div>;

const wrapper = shallow(
<CoreAdminRouter
customRoutes={[
<Route
key="custom"
noLayout
exact
path="/custom"
render={() => <div>Foo</div>}
/>,
<Route
key="custom2"
noLayout
exact
path="/custom2"
component={Bar}
/>,
]}
location={{ pathname: '/custom' }}
>
<Resource name="posts" />
<Resource name="comments" />
</CoreAdminRouter>
it('should render the custom routes with and withoutayout', () => {
const history = createMemoryHistory();
const { getByText, queryByText } = renderWithRedux(
<Router history={history}>
<CoreAdminRouter
layout={Layout}
customRoutes={[
<Route
key="foo"
noLayout
exact
path="/foo"
render={() => <div>Foo</div>}
/>,
<Route
key="bar"
exact
path="/bar"
component={() => <div>Bar</div>}
/>,
]}
location={{ pathname: '/custom' }}
>
<Resource name="posts" />
</CoreAdminRouter>
</Router>
);

const routes = wrapper.find('Route');
assert.equal(routes.at(0).prop('path'), '/custom');
assert.equal(routes.at(1).prop('path'), '/custom2');
history.push('/foo');
expect(queryByText('Layout')).toBeNull();
expect(getByText('Foo')).toBeDefined();
history.push('/bar');
expect(getByText('Layout')).toBeDefined();
expect(getByText('Bar')).toBeDefined();
});
});
21 changes: 6 additions & 15 deletions packages/ra-core/src/CoreAdminRouter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,16 @@ import React, {
CSSProperties,
ReactElement,
} from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Route, Switch } from 'react-router-dom';
import compose from 'recompose/compose';
import getContext from 'recompose/getContext';

import { AUTH_GET_PERMISSIONS } from './auth/types';
import { isLoggedIn } from './reducer';
import { userLogout as userLogoutAction } from './actions/authActions';
import RoutesWithLayout from './RoutesWithLayout';
import AuthContext from './auth/AuthContext';
import {
Dispatch,
AuthProvider,
AdminChildren,
CustomRoutes,
CatchAllComponent,
Expand All @@ -45,7 +42,6 @@ export interface AdminRouterProps extends LayoutProps {
}

interface EnhancedProps {
authProvider?: AuthProvider;
isLoggedIn?: boolean;
userLogout: Dispatch<typeof userLogoutAction>;
}
Expand All @@ -61,7 +57,7 @@ export class CoreAdminRouter extends Component<
static defaultProps: Partial<AdminRouterProps> = {
customRoutes: [],
};

static contextType = AuthContext;
state: State = { children: [] };

componentWillMount() {
Expand All @@ -77,7 +73,7 @@ export class CoreAdminRouter extends Component<
initializeResourcesAsync = async (
props: AdminRouterProps & EnhancedProps
) => {
const { authProvider } = props;
const authProvider = this.context;
try {
const permissions = await authProvider(AUTH_GET_PERMISSIONS);
const resolveChildren = props.children as RenderResourcesFunction;
Expand Down Expand Up @@ -250,12 +246,7 @@ const mapStateToProps = state => ({
isLoggedIn: isLoggedIn(state),
});

export default compose(
getContext({
authProvider: PropTypes.func,
}),
connect(
mapStateToProps,
{ userLogout: userLogoutAction }
)
export default connect(
mapStateToProps,
{ userLogout: userLogoutAction }
)(CoreAdminRouter) as ComponentType<AdminRouterProps>;
2 changes: 1 addition & 1 deletion packages/ra-core/src/actions/authActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export interface UserCheckAction {
export const userCheck = (
payload: object,
pathName: string,
routeParams
routeParams: object = {}
): UserCheckAction => ({
type: USER_CHECK,
payload: {
Expand Down
Loading