Skip to main content

Overview

AuthGuard

The authGuard function is employed to regulate access to specific routes based on user authentication status. For instance, the loginGuard function, redirects authenticated users from certain pages such as 'login' and 'register', while the 'isLoggedIn' function restricts access to the 'PageWithLoginCheck' page solely to authenticated users. Below are examples showcasing their utilization:

  1. loginGuard Implementation:
import React from 'react';

import PageWithAuthGuard from '../page-layouts/PageWithAuthGuard';

const loginGuard= ({ fpi, store, redirectUrl }) => {
try {

const loggedIn = await isLoggedIn({ fpi, store });
if (loggedIn) {
if (isRunningOnClient()) {
window.location.navigate(redirectUrl ?? "/");
}
return;
}
} catch (error) {
return true;
}
}

function PageWithAuthGuard({ fpi }) {
return (
<>
<PageWithAuthGuard fpi={fpi}>
</PageWithAuthGuard>
</>
);
}
PageWithAuthGuard.authGuard = loginGuard;

export default RegisterPage;
  1. isLoggedIn Implementation:
import React from 'react';
import { isLoggedIn } from '../helper/auth-guard';
import Cart from '../page-layouts/cart/cart';

const isLoggedIn = ({ fpi, store }) => {
const userFetched = store?.auth?.user_fetched ?? false;
if (userFetched) {
const loggedIn = store?.auth?.logged_in;
return loggedIn;
}

const { payload } = await fpi.auth.fetchUserData();

return !!(payload?.user ?? false);
}

function PageWithLoginCheck({ fpi }) {
return (
<>
<PageWithLoginCheck fpi={fpi} />
</>
);
}

PageWithLoginCheck.serverFetch = () => { };

PageWithLoginCheck.authGuard = isLoggedIn;

export default PageWithLoginCheck;

These examples demonstrate how authGuard functions like loginGuard and isLoggedIn are utilized to control access to routes based on user authentication status.