Code Monkey home page Code Monkey logo

Comments (9)

cgitosh avatar cgitosh commented on July 28, 2024 1

Thank you @Mukthayar1 and everyone else for the contribution to my question. I managed to adapt your code and it's working. The code is in two files. 1.) the Protected routes file (I'm calling it RequireAuth.js) and the mainRoutes.js file.
1.) Code for RequireAuth.js
`import { useLocation, Navigate, Outlet } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { selectCurrentToken } from './authSlice';

const RequireAuth = () => {
const token = useSelector(selectCurrentToken);
const location = useLocation();
return token ? : <Navigate to="/login" state={{ from: location }} replace />;
};
export default RequireAuth;`

2.) Code for MainRoute.js

`import { Children, lazy } from 'react';

// project import
import Loadable from 'components/Loadable';
import MainLayout from 'layout/MainLayout';
import RequireAuth from 'pages/authentication/RequireAuth';
import { element, elementType } from 'prop-types';

// render - dashboard
const DashboardDefault = Loadable(lazy(() => import('pages/dashboard')));

// render - utilities
const Typography = Loadable(lazy(() => import('pages/components-overview/Typography')));
const Color = Loadable(lazy(() => import('pages/components-overview/Color')));
const Shadow = Loadable(lazy(() => import('pages/components-overview/Shadow')));
const AntIcons = Loadable(lazy(() => import('pages/components-overview/AntIcons')));

// ==============================|| MAIN ROUTING ||============================== //
/* protected routes */
const MainRoutes = {
path: '/',
element: ,
children: [
{
path: '/',
element: ,
children: [
{
path: '/dashboard/default',
element:
},
{
path: '/',
element:
},
{
path: 'color',
element:
},
{
path: 'typography'
element:
}
]
}
]
};
export default MainRoutes;
`

from berry-free-react-admin-template.

Mukthayar1 avatar Mukthayar1 commented on July 28, 2024

ProctedRoutes.js
import { useNavigate, useLocation, Navigate, Outlet } from 'react-router-dom';
import useAuth from "../hooks/useAuth";

const PrivateRoute = ({ children, allowedRoles }) => {

const { auth } = useAuth();
const location = useLocation();

console.log('auth===>',auth)

return (

    auth  ? <Outlet />
        :
        <Navigate to="/ECommerce/Login" state={{ from: location }} replace />
);

};

export default PrivateRoute;

New Routes

import React, { lazy } from 'react';
import MainLayout from 'layout/MainLayout';
import Loadable from 'ui-component/Loadable';
import { Routes, Route } from 'react-router-dom';
import MinimalLayout from 'layout/MinimalLayout';

import PrivateRoute from './ProvateRoute';

const DashboardDefault = Loadable(lazy(() => import('views/dashboard/Default')));
const AuthLogin3 = Loadable(lazy(() => import('views/pages/authentication/authentication3/Login3')));
const AuthRegister3 = Loadable(lazy(() => import('views/pages/authentication/authentication3/Register3')));
const AddProducts = Loadable(lazy(()=>import('views/utilities/AddProducts') ))

export default function RouteNew() {
return (
<>

                <Route path="/ECommerce" element={<MinimalLayout />}>
                    <Route path="/ECommerce" element={<AuthLogin3 />} />
                    <Route path="/ECommerce/Login" element={<AuthLogin3 />} />
                    <Route path="/ECommerce/Register" element={<AuthRegister3 />} />
                </Route>


                <Route element={<PrivateRoute />}>
                    <Route path="/" element={<MainLayout />}>
                        <Route path="/" element={<DashboardDefault />} />
                        <Route path="/dashboard/default" element={<DashboardDefault />} />
                    </Route>
                </Route>

                <Route element={<PrivateRoute />}>
                    <Route path="/Store" element={<MainLayout />}>
                        <Route path="/Store/AddProducts" element={<AddProducts />} />
                    </Route>
                </Route>

            </Route>
        </Routes>

    </>
);

}

where useAuth is my contex api when ever your login i save data in useAuth

from berry-free-react-admin-template.

shaheer904 avatar shaheer904 commented on July 28, 2024

I have check that if the redux state had the jwt token, then I have tried to access the login route but it shows black screen,
can u please share the code if the user is loggedin then it will only redirect to dashboard, if user access the route which does not exist.

from berry-free-react-admin-template.

Mukthayar1 avatar Mukthayar1 commented on July 28, 2024

I have check that if the redux state had the jwt token, then I have tried to access the login route but it shows black screen, can u please share the code if the user is loggedin then it will only redirect to dashboard, if user access the route which does not exist.

i have to code this . you can email me [email protected] so i can do work for you

from berry-free-react-admin-template.

shaheer904 avatar shaheer904 commented on July 28, 2024

in config.js
set basename='/'
Apply a condition in the login and register page just before the return

if(user){
navigate('/dashboard/default')
}

change the NewRoutes File

import { lazy } from 'react';
import MainLayout from 'layout/MainLayout';
import Loadable from 'ui-component/Loadable';
import { Routes, Route } from 'react-router-dom';
import MinimalLayout from 'layout/MinimalLayout';
import PrivateRoute from 'Potected';
import Typography from './views/utilities/Typography';
import NoFound from 'NoFound';

const DashboardDefault = Loadable(lazy(() => import('./views/dashboard/Default')));
const AuthLogin3 = Loadable(lazy(() => import('./views/pages/authentication/authentication3/Login3')));
const AuthRegister3 = Loadable(lazy(() => import('./views/pages/authentication/authentication3/Register3')));
const AddProduct = Loadable(lazy(() => import('./views/utilities/Typography')));

const NewRoutes = () => {
    return (
        <>
            <Routes>
                <MinimalLayout>
                    <Route path="/" element={<AuthLogin3 />} />
                    <Route path="/Register" element={<AuthRegister3 />} />
                    <Route path="*" true element={<NoFound />} />
                </MinimalLayout>

                <MainLayout>
                    <Route element={<PrivateRoute />}>
                        {/* <Route path="/" element={<DashboardDefault />} /> */}
                        <Route path="/dashboard/default" element={<DashboardDefault />} />
                        <Route path="*" true element={<NoFound />} />
                    </Route>

                    <Route path="/utils" element={<PrivateRoute />}>
                        <Route path="/util-typography" element={<Typography />} />
                        <Route path="*" true element={<NoFound />} />
                    </Route>
                </MainLayout>
            </Routes>
        </>
    );
};

export default NewRoutes;

In PrivateRoute.js file change this
return auth === 'user' ? <Outlet /> : <Navigate to="/" state={{ from: location }} replace />;

Now Add a new page NotFound.js

import React from 'react';
import { useNavigate } from 'react-router';

const NoFound = () => {
//user your own redux or contextAPI state or LocalStorage
    const a = localStorage.getItem('user');
    const navigate = useNavigate();

    return (
        <div>
            <h1>No Found</h1>
            {a === 'user' ? (
                <button onClick={() => navigate('/dashboard/default')}>go to dashboard</button>
            ) : (
                <button onClick={() => navigate('/')}>Go to login</button>
            )}
        </div>
    );
};

export default NoFound;

from berry-free-react-admin-template.

 avatar commented on July 28, 2024

Anything needed here, i can close issue if no response.

from berry-free-react-admin-template.

shaheer904 avatar shaheer904 commented on July 28, 2024

Please provide the code for protecting routes

from berry-free-react-admin-template.

pvimalmec avatar pvimalmec commented on July 28, 2024

@cgitosh Could you please share code snippet, when i made changes in above two files, it didnt work for me. I can see you never use RequireAuth in Maniroutes. Am i missing something? please help:-)

from berry-free-react-admin-template.

cgitosh avatar cgitosh commented on July 28, 2024

I'm using RequireAuth in mainRoutes to wrap around the other routes that require a user to be authenticated (All routes in MainRoutes require authentication in my case. I will share my RequireAuth code and the authSlice code plus section of the Mainroutes where I'm wrapping the routes using RequireAuth.
1.) authSlice.js (I'm using Redux Tool Kit (RTK), in my journey I discovered that redux is really unavoidable so I invested time learning it then I found the RTK gem at the end which has really made things simpler..)
import { createSlice } from '@reduxjs/toolkit'; import { loadState } from 'localStorage'; const persistedState = loadState(); const initialState = { user: '', token: '', refreshToken: '' }; const authSlice = createSlice({ name: 'auth', initialState: { ...persistedState.auth }, reducers: { setCredentials: (state, action) => { const { user, access, refresh } = action.payload; state.user = user; state.token = access; state.refreshToken = refresh; }, logOut: (state, action) => { state.user = null; state.token = null; } } }); export const { setCredentials, logOut } = authSlice.actions; export default authSlice.reducer; export const selectCurrentUser = (state) => state.auth.user; export const selectCurrentToken = (state) => state.auth.token;

2.) RequireAuth.js - Uses authSlice above to check if the user is authenticated and token is valid/not expired, if invalid/expired, user is redirected to login page. (Side note: Been trying to implement the refresh token for expired tokens but so far I have not been successful. Problem is on the Django side)

import { useLocation, Navigate, Outlet } from 'react-router-dom'; import { useSelector } from 'react-redux';
import { selectCurrentToken } from './authSlice';const RequireAuth = () => {
const token = useSelector(selectCurrentToken); const location = useLocation();
return token ? <Outlet /> : <Navigate to="login" state={{ from: location }} replace />; };
`export default RequireAuth;

3.) MainRoutes.js.. This file you have it so I will share snippets.

  •   `import` RequireAuth from 'WhereverYouHaveIt/RequireAuth';
    
  • Use RequireAuth in the routing like in the below snippet
    // ==============================|| MAIN ROUTING ||============================== // const MainRoutes = { path: '/', element: <RequireAuth />, children: [ { path: '/', element: <MainLayout />, children: [ { path: '/dashboard/default', element: <DashboardDefault /> }, { path: '/', element: <DashboardDefault /> }, ........... ...........

Hope that helps.. let me know if you need any more clarification

from berry-free-react-admin-template.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.