Spaces:
Running

File size: 3,808 Bytes
224f821
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
'use client'

import { useEffect } from 'react'
import { useRouter, usePathname } from 'next/navigation'
import { useAuth } from '@/contexts/AuthContext'
import { hasAccess } from '@/lib/permissions'
import { AlertCircle, Lock } from 'lucide-react'

interface ProtectedRouteProps {
  children: React.ReactNode
  requiredRole?: 'OWNER' | 'MANAGER'
  fallbackPath?: string
}

/**
 * Компонент для защиты маршрутов по ролям
 * 
 * Использование:
 * <ProtectedRoute requiredRole="OWNER">
 *   <AdminContent />
 * </ProtectedRoute>
 */
export function ProtectedRoute({ 
  children, 
  requiredRole = 'OWNER',
  fallbackPath = '/chats'
}: ProtectedRouteProps) {
  const { user, isLoading } = useAuth()
  const router = useRouter()
  const pathname = usePathname()

  useEffect(() => {
    if (isLoading) return

    // Если пользователь не авторизован
    if (!user) {
      router.push('/login')
      return
    }

    // Если требуется роль OWNER, а у пользователя MANAGER
    if (requiredRole === 'OWNER' && user.role !== 'OWNER') {
      router.push(fallbackPath)
      return
    }

    // Проверка доступа к текущему пути
    if (!hasAccess(user.role as any, pathname)) {
      router.push(fallbackPath)
    }
  }, [user, isLoading, pathname, requiredRole, fallbackPath, router])

  // Показываем загрузку
  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-indigo-50/30 to-purple-50/20 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-16 w-16 border-b-4 border-indigo-600 mx-auto mb-4"></div>
          <p className="text-lg font-semibold text-slate-700">Проверка доступа...</p>
        </div>
      </div>
    )
  }

  // Если нет пользователя или нет доступа
  if (!user || (requiredRole === 'OWNER' && user.role !== 'OWNER')) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-indigo-50/30 to-purple-50/20 flex items-center justify-center p-4">
        <div className="bg-white rounded-2xl shadow-2xl border-2 border-red-200 p-8 max-w-md w-full text-center">
          <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <Lock className="w-8 h-8 text-red-600" />
          </div>
          <h2 className="text-2xl font-bold text-slate-900 mb-2">Доступ запрещён</h2>
          <p className="text-slate-600 mb-6">
            У вас нет прав для просмотра этой страницы. Требуется роль: <strong>{requiredRole === 'OWNER' ? 'Владелец' : 'Менеджер'}</strong>
          </p>
          <div className="flex items-start gap-3 p-4 bg-amber-50 border-2 border-amber-200 rounded-xl mb-6">
            <AlertCircle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
            <p className="text-sm text-amber-800 text-left">
              Обратитесь к владельцу аккаунта для получения необходимых прав доступа.
            </p>
          </div>
          <button
            onClick={() => router.push(fallbackPath)}
            className="w-full px-6 py-3 bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-500 hover:to-purple-500 text-white font-bold rounded-xl transition-all shadow-lg hover:shadow-xl"
          >
            Вернуться к чатам
          </button>
        </div>
      </div>
    )
  }

  // Пользователь авторизован и имеет доступ
  return <>{children}</>
}