32 lines
1.1 KiB
JavaScript
32 lines
1.1 KiB
JavaScript
import { Navigate } from 'react-router-dom'
|
|
import { useAuth } from '../app/providers/AuthProvider'
|
|
|
|
// Gate: requires an authenticated user.
|
|
export function RequireAuth({ children }) {
|
|
const { user, loading } = useAuth()
|
|
|
|
if (loading) return <div>Loading...</div>
|
|
if (!user) return <Navigate to="/login" replace />
|
|
|
|
return children
|
|
}
|
|
|
|
// Gate: requires an authenticated user whose role is allowed.
|
|
// <RequireRole role="admin">...</RequireRole> // single role
|
|
// <RequireRole role={['admin', 'manager']}>...</RequireRole> // any of several
|
|
//
|
|
// IMPORTANT: this is a UX guard only. The client can be tampered with, so the
|
|
// REAL enforcement must live on the backend (e.g. Spring Security
|
|
// @PreAuthorize("hasRole('ADMIN')")). Never trust the front end for access control.
|
|
export function RequireRole({ role, children, fallback = '/' }) {
|
|
const { user, loading } = useAuth()
|
|
|
|
if (loading) return <div>Loading...</div>
|
|
if (!user) return <Navigate to="/login" replace />
|
|
|
|
const allowed = Array.isArray(role) ? role : [role]
|
|
if (!allowed.includes(user.role)) return <Navigate to={fallback} replace />
|
|
|
|
return children
|
|
}
|