React-Admin: How to redirect to <Dashboard> when authenticated through custom <Login> page

Viewed 2496

react-admin loads the <Dashboard> at the base "/". And for that reason, the custom page never opens by default because the <Admin> always routes to the dashboard.

I've implemented <PrivateRoutes> to handle authentication and it's a success.
The <Login> page is loaded by default, and upon authentication, it routes to dashboard.

Challenge: This process breaks the functionality of Sidebar <links>, like "Users".

// CustomRoutes.js
export default [
  <Route exact path="/login" component={LoginPage} noLayout />,
  <Route exact path="/forgot-password" component={ForgotPassword} noLayout />,
  <Route exact path="/confirm-password" component={ConfirmForgotPassword} noLayout />,
  <PrivateRoute path="/" loggedIn={localStorage.getItem("access_token")} component={dashboard} />
];

And then...

// PrivateRoute.js
import React from "react";
import { Redirect, Route } from "react-router-dom";

const PrivateRoute = ({ path, component: Component, ...rest }) => {
  const isLoggedIn = localStorage.getItem("access_token");

  return (
    <Route
      path={path}
      {...rest}
      render={props => isLoggedIn 
        ? <Component {...props} />
        : <Redirect to={{ pathname: "/login", state: { from: props.location } }} />
      }
    />
  );
};

export default PrivateRoute;

Here's how it looks within the main <App>

// App.js
const App = () => (
  <Admin
    theme={myTheme}
    dashboard={dashboard}
    authProvider={authProvider}
    dataProvider={dataProvider}
    customRoutes={customRoutes}
    loginPage={LoginPage}
    logoutButton={LogoutButton}
    forgotPassword={ForgotPassword}
  >
    <Resource name="users" list={UserList} create={UserCreate} show={UserShow} icon={UserIcon} />
  </Admin>
);

export default App;

Please note that the <resource> "users" is not working.
Do I need to add custom route for that too?

1 Answers

Alright, let's debug this step-by-step:

We can take advantage of react-admin directly to handle the authentication via the authProvider.

  • Once you include the authProvider, react-adminenables a new page on the /login route,
    which displays a <Login> form asking for username and password.

  • You can definitely customize that login page (as I assume you did), and I advise that you avoid using a <PrivateRoute> since the authProvider redirects all users who aren't yet authenticated to /login.

  • Kindly note that <Admin> creates an application with its own state, routing, and controller logic.
    In your code, you added forgotPassword which is not a prop accepted by <Admin.

<admin
   // remove this...
-  forgotPassword={ForgotPassword}
>

I wonder exactly what error you get in this case, but this is the main bug.

Related