I use React with Sanctum. I made atheAPI and I'm using middleware to protect that. Problem is that it only protects the API but it doesn't protect components. I want to implement a redirect. If a user visits a component which needs to log in - he will be redirected to the login route. My first idea was that I can fetch the user's data and if this data doesn't exist, the guest will be redirected.
{user.user.id ? '' : <Redirect to="/login" /> }
But it isn't a good method for me. In 1 component I have all routing - login, register, etc too. Component which don't require a user will be logged in. And if I try fetch user's data I have 401 error.Any other idea how can I solve my problem?
CodePudding user response:
You can create a Private route component.
PrivateRoute Component
const PrivateRoute = ({ children, ...rest }) => {
const { user } = useUser(); // Some hook or a way to get logged in user. You can get token from localStorage as well.
return (
<Route
{...rest}
render={({ location }) => {
if (user?.id) {
return children;
}
return (
<Redirect
to={{
pathname: '/login',
state: { from: location }, // This is added in case if you want to redirect user to login with existing query params
}}
/>
);
}}
/>
);
};
AppRouter Component
const AppRouter = () => {
return (
<Router>
<Switch>
<Route path="/login" exact component={Login} />
<PrivateRoute path="/">
<Route path="/" exact component={Dashboard} />
</PrivateRoute>
</Switch>
</Router>
);
};
CodePudding user response:
Pseudo-security. After a user logs in, set some flag in e.g. local, session... storage to indicate that a user is logged in. Create a dedicated component that checks whether a user is logged in, and use it as a wrapper for your "protected" components.
const Authenticated = ({children}) => {
const isLoggedIn = localStorage.getItem('loggedIn');
return isLoggedIn ? children : <Redirect to='/login' />
}
Use it:
<Authenticated>
<MyProtectedComponent />
</Authenticated>