protected-route.tsx 2.2 KB

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