Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions src/components/auth/RouteGuard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { useEffect, useState } from 'react'
import { Navigate } from 'react-router-dom'
import { useWallet } from '../../hooks/useWallet'
import { useAuth } from '../../hooks/useAuth'
import { useRoleStore, type UserRole } from '../../stores/role.store'
import type { ReactNode } from 'react'

interface RouteGuardProps {
children: ReactNode
allowedRole?: UserRole
requireAuth?: boolean
}

export function RouteGuard({
children,
allowedRole,
requireAuth = true,
}: RouteGuardProps) {
const { isConnected } = useWallet()
const { checkAuth, logout } = useAuth()
const { role, roleSelected } = useRoleStore()
const [isChecking, setIsChecking] = useState(true)
const [isAuthenticated, setIsAuthenticated] = useState(false)

useEffect(() => {
const validateAuth = () => {
setIsChecking(true)

if (!requireAuth) {
setIsAuthenticated(true)
setIsChecking(false)
return
}

// Check wallet connection
if (!isConnected) {
setIsAuthenticated(false)
setIsChecking(false)
return
}

// Check JWT token validity
const isValid = checkAuth()
if (!isValid) {
logout()
setIsAuthenticated(false)
setIsChecking(false)
return
}

setIsAuthenticated(true)
setIsChecking(false)
}

validateAuth()
}, [isConnected, checkAuth, logout, requireAuth])

if (isChecking) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900"></div>
</div>
)
}

// Redirect unauthenticated users
if (requireAuth && !isAuthenticated) {
return <Navigate to="/" replace />
}

// Redirect if wallet not connected
if (requireAuth && !isConnected) {
return <Navigate to="/" replace />
}

// Redirect if role not selected
if (requireAuth && !roleSelected) {
return <Navigate to="/role-select" replace />
}

// Redirect if role doesn't match requirement
if (requireAuth && allowedRole && role !== allowedRole) {
return <Navigate to="/dashboard" replace />
}

return <>{children}</>
}
24 changes: 24 additions & 0 deletions src/hooks/useAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,17 @@ function bytesToBase64(bytes: Uint8Array): string {
return btoa(binary)
}

function isTokenExpired(token: string): boolean {
try {
const payload = JSON.parse(atob(token.split('.')[1]))
const exp = payload.exp
if (!exp) return false
return Date.now() >= exp * 1000
} catch {
return true
}
}

export const useAuth = () => {
const [isAuthLoading, setIsAuthLoading] = useState(false)
const [authError, setAuthError] = useState<string | null>(null)
Expand Down Expand Up @@ -49,9 +60,22 @@ export const useAuth = () => {
clearTokens()
}

const checkAuth = () => {
const token = localStorage.getItem('accessToken')
if (!token) {
return false
}
if (isTokenExpired(token)) {
clearTokens()
return false
}
return true
}

return {
authenticate,
logout,
checkAuth,
isAuthLoading,
authError,
isAuthenticated,
Expand Down
46 changes: 11 additions & 35 deletions src/router/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createBrowserRouter, RouterProvider, Navigate } from 'react-router-dom'
import { createBrowserRouter, RouterProvider } from 'react-router-dom'
import { Layout } from '../components/layout/Layout'
import { Home } from '../pages/Home'
import { Docs } from '../pages/Docs'
Expand All @@ -16,32 +16,8 @@ import { LearnerProfile } from '../pages/LearnerProfile'
import { NotFound } from '../pages/NotFound'
import { History } from '../pages/History'
import { RoleSelect } from '../pages/RoleSelect'
import { useRoleStore } from '../stores/role.store'
import { RouteGuard } from '../components/auth/RouteGuard'
import type { UserRole } from '../stores/role.store'
import { useWallet } from '../hooks/useWallet'
import type { ReactNode } from 'react'

function RoleGuard({
allowedRole,
children,
}: {
allowedRole: UserRole
children: ReactNode
}) {
const { isConnected } = useWallet()
const { role, roleSelected } = useRoleStore()

if (!isConnected) {
return <Navigate to="/" replace />
}
if (!roleSelected) {
return <Navigate to="/role-select" replace />
}
if (role !== allowedRole) {
return <Navigate to="/dashboard" replace />
}
return <>{children}</>
}

const router = createBrowserRouter([
{
Expand All @@ -58,51 +34,51 @@ const router = createBrowserRouter([
},
{
path: '/role-select',
element: <Layout><RoleSelect /></Layout>,
element: <Layout><RouteGuard requireAuth><RoleSelect /></RouteGuard></Layout>,
},
{
path: '/dashboard',
element: <Layout><Dashboard /></Layout>,
element: <Layout><RouteGuard requireAuth><Dashboard /></RouteGuard></Layout>,
},
{
path: '/vendors',
element: <Layout><Vendors /></Layout>,
},
{
path: '/vendors/dashboard',
element: <Layout><RoleGuard allowedRole="vendor"><VendorDashboard /></RoleGuard></Layout>,
element: <Layout><RouteGuard requireAuth allowedRole="vendor"><VendorDashboard /></RouteGuard></Layout>,
},
{
path: '/vendors/register',
element: <Layout><RoleGuard allowedRole="vendor"><VendorRegister /></RoleGuard></Layout>,
element: <Layout><RouteGuard requireAuth allowedRole="vendor"><VendorRegister /></RouteGuard></Layout>,
},
{
path: '/vendors/:id',
element: <Layout><VendorDetail /></Layout>,
},
{
path: '/sponsors',
element: <Layout><RoleGuard allowedRole="sponsor"><Sponsors /></RoleGuard></Layout>,
element: <Layout><RouteGuard requireAuth allowedRole="sponsor"><Sponsors /></RouteGuard></Layout>,
},
{
path: '/sponsors/onboarding',
element: <Layout><RoleGuard allowedRole="sponsor"><SponsorOnboarding /></RoleGuard></Layout>,
element: <Layout><RouteGuard requireAuth allowedRole="sponsor"><SponsorOnboarding /></RouteGuard></Layout>,
},
{
path: '/mentor',
element: <Layout><RoleGuard allowedRole="mentor"><MentorDashboard /></RoleGuard></Layout>,
element: <Layout><RouteGuard requireAuth allowedRole="mentor"><MentorDashboard /></RouteGuard></Layout>,
},
{
path: '/vouch',
element: <Layout><RoleGuard allowedRole="mentor"><Vouch /></RoleGuard></Layout>,
element: <Layout><RouteGuard requireAuth allowedRole="mentor"><Vouch /></RouteGuard></Layout>,
},
{
path: '/learner/:walletAddress',
element: <Layout><LearnerProfile /></Layout>,
},
{
path: '/history',
element: <Layout><History /></Layout>,
element: <Layout><RouteGuard requireAuth><History /></RouteGuard></Layout>,
},
{
path: '*',
Expand Down