mirats_auth_cdn
v1.1.3
Published
This project integrates Single Sign-On (SSO) functionality using the `@mirats/mirats-auth` package. Follow the steps below to set up the SSO in your application.
Downloads
780
Readme
Mirats Auth
This project integrates Single Sign-On (SSO) functionality using the @mirats/mirats-auth
package. Follow the steps below to set up the SSO in your application.
Installation
First, install the SSO package:
npm i @mirats/mirats-auth
1. Create GlobalContext.js
Create a file called GlobalContext.js inside the root of your app directory with the following content:
"use client";
import ProtectRoute from "../components/ProtectRoute";
import { getAuth } from "@mirats/mirats-auth";
import { createContext, useContext, useEffect, useState } from "react";
const AppContext = createContext(null);
export const useGlobalContext = () => {
return useContext(AppContext);
};
const GlobalContext = ({ children }) => {
const [userData, setUserData] = useState({});
const getUserData = async () => {
try {
const user = await getAuth();
if (user && user?.currentUser?._id) {
setUserData(user?.currentUser);
return;
}
} catch (error) {
console.log(error);
}
};
useEffect(() => {
if (!Object.keys(userData || {})?.length) {
getUserData();
}
}, [userData?._id]);
return (
<AppContext.Provider value={{ userData }}>
<ProtectRoute>
{children}
</ProtectRoute>
</AppContext.Provider>
);
};
export default GlobalContext;
2. Create ProtectRoute.js
Create a file outside the app directory called ProtectRoute.js with the following content:
"use client";
import { isLoggedIn, signIn } from "@mirats/mirats-auth";
const ProtectRoute = ({ children }) => {
const { user, loading } = isLoggedIn();
if (user && !loading) {
console.log("user & loading", { user, loading });
return children;
} else {
signIn();
console.log("no user found");
return null;
}
};
export default ProtectRoute;
3. Import GlobalContext in layout.js
Import the GlobalContext file inside your layout.js file as shown below:
import dynamic from "next/dynamic";
const GlobalContext = dynamic(() => import("@/context/index"), { ssr: false });
const inter = Inter({ subsets: ["latin"] });
export default function RootLayout({ children }) {
return (
<html lang="en">
<body className={inter.className}>
<GlobalContext>
{children}
</GlobalContext>
</body>
</html>
);
}