Skip to content

Commit

Permalink
added route gaurd for frontend access control
Browse files Browse the repository at this point in the history
  • Loading branch information
linxiaoxin committed Aug 19, 2024
1 parent 4312f7d commit 6c58a0e
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
7 changes: 7 additions & 0 deletions app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,19 @@ import 'primeicons/primeicons.css';
import '../styles/layout/layout.scss';
import '../styles/demo/Demos.scss';
import { Suspense } from 'react';
import { usePathname } from 'next/navigation';
import { RouteGuard } from '@/lib/RouteGuard';
import { redirect } from 'next/navigation'

interface RootLayoutProps {
children: React.ReactNode;
}

export default function RootLayout({ children }: RootLayoutProps) {
const pathname = usePathname();
if(!RouteGuard.apply(pathname)){
redirect('/');
}
return (
<html lang="en" suppressHydrationWarning>
<head>
Expand Down
51 changes: 51 additions & 0 deletions lib/RouteGuard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
'use client';
import { USER, IS_LOGIN } from '../lib/constants'

export const RouteGuard = {

isLogin(){
if(typeof sessionStorage !== "undefined"){
return sessionStorage?.getItem(IS_LOGIN) == "true" || false;
}
else{
return false;
}
},
loginUser(){
if(this.isLogin()){
return JSON.parse(sessionStorage.getItem(USER) || '') as UserProfile;
}
else{
return null;
}
},
apply(path: string):boolean{
if(process.env.NODE_ENV === 'development') return true;
switch(path){
case '/':
return true;
case '/auth/google':
return true;
case '/auth/access':
return true;
case '/auth/error':
return true;
case '/dashboard':
return true;
case '/quiz':
return this.accessibleBy(['student']);
case '/questions/searchlist':
return this.accessibleBy(['admin', 'tutor']);
case '/questions/topics':
return this.accessibleBy(['admin', 'tutor']);
case '/classes':
return this.accessibleBy(['admin', 'tutor']);
default:
return false;
}
},
accessibleBy (roles: string[]) {
return this.isLogin() && this.loginUser()?.roles.some(role => roles.includes(role)) || false;
},

}

0 comments on commit 6c58a0e

Please sign in to comment.