Skip to content

Commit

Permalink
feat(boilerplate): add auth guard in webapp
Browse files Browse the repository at this point in the history
  • Loading branch information
k1eu committed Jul 5, 2024
1 parent d1574d6 commit 976b8aa
Show file tree
Hide file tree
Showing 6 changed files with 199 additions and 81 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useEffect } from "react";
import { useAuthStore } from "./authStore";
import { useNavigate } from "@remix-run/react";

/**
* @returns void
* @description This hook is used to rediect the user to the login page if they are not logged in.
*/
export function useAuthEffect() {
const loggedIn = useAuthStore((state) => state.isLoggedIn);
const navigate = useNavigate();

useEffect(() => {
if (!loggedIn) {
navigate("/login");
}
}, [loggedIn, navigate]);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { redirect } from "@remix-run/react";
import { useAuthStore } from "./authStore";

/**
* @returns void
* @description This function is used to rediect the user to the login page if they are not logged in.
* @description Should be moved to middlewares once they are supported in Remix/ReactRouter7
*/
export function authGuard() {
const authStore = useAuthStore.getState();

if (!authStore.isLoggedIn) {
return redirect("/login");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { create } from "zustand";

type AuthStore = {
isLoggedIn: boolean;
setAuthState: (isLoggedIn: boolean) => void;
};

export const useAuthStore = create<AuthStore>((set) => ({
isLoggedIn: false,
setAuthState: (isLoggedIn) => set({ isLoggedIn }),
}));
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { Outlet } from "@remix-run/react";
import { useAuthEffect } from "../Auth/authEffect";
import { authGuard } from "../Auth/authGuard";

export function clientLoader() {
authGuard();
}

export default function DashboardLayout() {
useAuthEffect();

return (
<div>
<h1>Dashboard Layout</h1>
Expand Down
3 changes: 2 additions & 1 deletion examples/common_nestjs_remix/apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
"isbot": "^4.1.0",
"morgan": "^1.10.0",
"react": "^18.3.1",
"react-dom": "^18.3.1"
"react-dom": "^18.3.1",
"zustand": "^4.5.4"
},
"devDependencies": {
"@remix-run/dev": "^2.9.2",
Expand Down
Loading

0 comments on commit 976b8aa

Please sign in to comment.