protected-route.tsx 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. "use client"
  2. import React, { useEffect } from 'react'
  3. import { useAuth } from '@/lib/auth-context'
  4. import { LoginForm } from './login-form'
  5. interface ProtectedRouteProps {
  6. children: React.ReactNode
  7. requiredRole?: 'admin' | 'user'
  8. fallback?: React.ReactNode
  9. }
  10. export function ProtectedRoute({ children, requiredRole, fallback }: ProtectedRouteProps) {
  11. const { isAuthenticated, isLoading, user, error } = useAuth()
  12. if (isLoading) {
  13. return (
  14. <div className="flex items-center justify-center min-h-screen">
  15. <div className="text-center">
  16. <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
  17. <p className="text-muted-foreground">Loading...</p>
  18. </div>
  19. </div>
  20. )
  21. }
  22. if (!isAuthenticated) {
  23. if (fallback) {
  24. return <>{fallback}</>
  25. }
  26. return (
  27. <div className="flex items-center justify-center min-h-screen bg-background">
  28. <div className="w-full max-w-md p-6">
  29. <div className="text-center mb-8">
  30. <h1 className="text-3xl font-bold">Stable Diffusion</h1>
  31. <p className="text-muted-foreground mt-2">Please sign in to continue</p>
  32. </div>
  33. <LoginForm />
  34. </div>
  35. </div>
  36. )
  37. }
  38. // Check role requirements
  39. if (requiredRole && user?.role !== requiredRole) {
  40. return (
  41. <div className="flex items-center justify-center min-h-screen">
  42. <div className="text-center">
  43. <h1 className="text-2xl font-bold text-destructive mb-4">Access Denied</h1>
  44. <p className="text-muted-foreground">
  45. You don't have permission to access this page.
  46. </p>
  47. </div>
  48. </div>
  49. )
  50. }
  51. return <>{children}</>
  52. }
  53. // Higher-order component for protecting routes
  54. export function withAuth<P extends object>(
  55. Component: React.ComponentType<P>,
  56. options?: { requiredRole?: 'admin' | 'user' }
  57. ) {
  58. return function AuthenticatedComponent(props: P) {
  59. return (
  60. <ProtectedRoute requiredRole={options?.requiredRole}>
  61. <Component {...props} />
  62. </ProtectedRoute>
  63. )
  64. }
  65. }