Spaces:
Running

MicroFunnel commited on
Commit
224f821
·
1 Parent(s): ba31b41

feat: Система ограничения доступа для менеджеров

Browse files

SIDEBAR:
- Dashboard - только OWNER
- Чаты - все роли
- База Знаний, AI Brain, Воронка - только OWNER
- Каналы, CRM, Партнёры - только OWNER
- Добавлен бейдж с ролью пользователя

ФАЙЛЫ:
- lib/permissions.ts - проверка прав доступа
- ProtectedRoute.tsx - защита страниц от неавторизованного доступа
- Обновлён Sidebar.tsx

OWNER: полный доступ
MANAGER: только чаты

frontend/components/ProtectedRoute.tsx ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use client'
2
+
3
+ import { useEffect } from 'react'
4
+ import { useRouter, usePathname } from 'next/navigation'
5
+ import { useAuth } from '@/contexts/AuthContext'
6
+ import { hasAccess } from '@/lib/permissions'
7
+ import { AlertCircle, Lock } from 'lucide-react'
8
+
9
+ interface ProtectedRouteProps {
10
+ children: React.ReactNode
11
+ requiredRole?: 'OWNER' | 'MANAGER'
12
+ fallbackPath?: string
13
+ }
14
+
15
+ /**
16
+ * Компонент для защиты маршрутов по ролям
17
+ *
18
+ * Использование:
19
+ * <ProtectedRoute requiredRole="OWNER">
20
+ * <AdminContent />
21
+ * </ProtectedRoute>
22
+ */
23
+ export function ProtectedRoute({
24
+ children,
25
+ requiredRole = 'OWNER',
26
+ fallbackPath = '/chats'
27
+ }: ProtectedRouteProps) {
28
+ const { user, isLoading } = useAuth()
29
+ const router = useRouter()
30
+ const pathname = usePathname()
31
+
32
+ useEffect(() => {
33
+ if (isLoading) return
34
+
35
+ // Если пользователь не авторизован
36
+ if (!user) {
37
+ router.push('/login')
38
+ return
39
+ }
40
+
41
+ // Если требуется роль OWNER, а у пользователя MANAGER
42
+ if (requiredRole === 'OWNER' && user.role !== 'OWNER') {
43
+ router.push(fallbackPath)
44
+ return
45
+ }
46
+
47
+ // Проверка доступа к текущему пути
48
+ if (!hasAccess(user.role as any, pathname)) {
49
+ router.push(fallbackPath)
50
+ }
51
+ }, [user, isLoading, pathname, requiredRole, fallbackPath, router])
52
+
53
+ // Показываем загрузку
54
+ if (isLoading) {
55
+ return (
56
+ <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">
57
+ <div className="text-center">
58
+ <div className="animate-spin rounded-full h-16 w-16 border-b-4 border-indigo-600 mx-auto mb-4"></div>
59
+ <p className="text-lg font-semibold text-slate-700">Проверка доступа...</p>
60
+ </div>
61
+ </div>
62
+ )
63
+ }
64
+
65
+ // Если нет пользователя или нет доступа
66
+ if (!user || (requiredRole === 'OWNER' && user.role !== 'OWNER')) {
67
+ return (
68
+ <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">
69
+ <div className="bg-white rounded-2xl shadow-2xl border-2 border-red-200 p-8 max-w-md w-full text-center">
70
+ <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
71
+ <Lock className="w-8 h-8 text-red-600" />
72
+ </div>
73
+ <h2 className="text-2xl font-bold text-slate-900 mb-2">Доступ запрещён</h2>
74
+ <p className="text-slate-600 mb-6">
75
+ У вас нет прав для просмотра этой страницы. Требуется роль: <strong>{requiredRole === 'OWNER' ? 'Владелец' : 'Менеджер'}</strong>
76
+ </p>
77
+ <div className="flex items-start gap-3 p-4 bg-amber-50 border-2 border-amber-200 rounded-xl mb-6">
78
+ <AlertCircle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
79
+ <p className="text-sm text-amber-800 text-left">
80
+ Обратитесь к владельцу аккаунта для получения необходимых прав доступа.
81
+ </p>
82
+ </div>
83
+ <button
84
+ onClick={() => router.push(fallbackPath)}
85
+ 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"
86
+ >
87
+ Вернуться к чатам
88
+ </button>
89
+ </div>
90
+ </div>
91
+ )
92
+ }
93
+
94
+ // Пользователь авторизован и имеет доступ
95
+ return <>{children}</>
96
+ }
frontend/components/Sidebar.tsx CHANGED
@@ -87,17 +87,19 @@ export function Sidebar() {
87
  Рабочее пространство
88
  </div>
89
  <div className="space-y-1">
90
- <Link
91
- href="/dashboard"
92
- className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 font-medium text-sm ${
93
- isActive('/dashboard')
94
- ? 'bg-indigo-600 text-white'
95
- : 'text-slate-400 hover:text-white hover:bg-white/10'
96
- }`}
97
- >
98
- <LayoutDashboard className="w-4 h-4" />
99
- Дашборд
100
- </Link>
 
 
101
  <Link
102
  href="/chats"
103
  className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 font-medium text-sm ${
@@ -112,51 +114,49 @@ export function Sidebar() {
112
  </div>
113
  </div>
114
 
115
- {/* INTELLIGENCE Group */}
116
- <div>
117
- <div className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2 px-3">
118
- Интеллект
119
- </div>
120
- <div className="space-y-1">
121
- <Link
122
- href="/knowledge"
123
- className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 font-medium text-sm ${
124
- isActive('/knowledge')
125
- ? 'bg-indigo-600 text-white'
126
- : 'text-slate-400 hover:text-white hover:bg-white/10'
127
- }`}
128
- >
129
- <Database className="w-4 h-4" />
130
- База Знаний
131
- </Link>
132
- {user?.role === 'OWNER' && (
133
- <>
134
- <Link
135
- href="/settings/brain"
136
- className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 font-medium text-sm ${
137
- isActive('/settings/brain')
138
- ? 'bg-indigo-600 text-white'
139
- : 'text-slate-400 hover:text-white hover:bg-white/10'
140
- }`}
141
- >
142
- <Brain className="w-4 h-4" />
143
- AI Brain
144
- </Link>
145
- <Link
146
- href="/settings/playbook"
147
- className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 font-medium text-sm ${
148
- isActive('/settings/playbook')
149
- ? 'bg-indigo-600 text-white'
150
- : 'text-slate-400 hover:text-white hover:bg-white/10'
151
- }`}
152
- >
153
- <Zap className="w-4 h-4" />
154
- Воронка
155
- </Link>
156
- </>
157
- )}
158
  </div>
159
- </div>
160
 
161
  {/* CONNECTIONS Group */}
162
  {user?.role === 'OWNER' && (
@@ -224,9 +224,16 @@ export function Sidebar() {
224
  <p className="text-sm font-medium text-white truncate">
225
  {user.full_name || user.email}
226
  </p>
227
- <p className="text-xs text-slate-500 truncate">
228
- {user.tenant_name}
229
- </p>
 
 
 
 
 
 
 
230
  </div>
231
 
232
  {/* Logout Button */}
 
87
  Рабочее пространство
88
  </div>
89
  <div className="space-y-1">
90
+ {user?.role === 'OWNER' && (
91
+ <Link
92
+ href="/dashboard"
93
+ className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 font-medium text-sm ${
94
+ isActive('/dashboard')
95
+ ? 'bg-indigo-600 text-white'
96
+ : 'text-slate-400 hover:text-white hover:bg-white/10'
97
+ }`}
98
+ >
99
+ <LayoutDashboard className="w-4 h-4" />
100
+ Дашборд
101
+ </Link>
102
+ )}
103
  <Link
104
  href="/chats"
105
  className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 font-medium text-sm ${
 
114
  </div>
115
  </div>
116
 
117
+ {/* INTELLIGENCE Group - ТОЛЬКО ДЛЯ OWNER */}
118
+ {user?.role === 'OWNER' && (
119
+ <div>
120
+ <div className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2 px-3">
121
+ Интеллект
122
+ </div>
123
+ <div className="space-y-1">
124
+ <Link
125
+ href="/knowledge"
126
+ className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 font-medium text-sm ${
127
+ isActive('/knowledge')
128
+ ? 'bg-indigo-600 text-white'
129
+ : 'text-slate-400 hover:text-white hover:bg-white/10'
130
+ }`}
131
+ >
132
+ <Database className="w-4 h-4" />
133
+ База Знаний
134
+ </Link>
135
+ <Link
136
+ href="/settings/brain"
137
+ className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 font-medium text-sm ${
138
+ isActive('/settings/brain')
139
+ ? 'bg-indigo-600 text-white'
140
+ : 'text-slate-400 hover:text-white hover:bg-white/10'
141
+ }`}
142
+ >
143
+ <Brain className="w-4 h-4" />
144
+ AI Brain
145
+ </Link>
146
+ <Link
147
+ href="/settings/playbook"
148
+ className={`group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 font-medium text-sm ${
149
+ isActive('/settings/playbook')
150
+ ? 'bg-indigo-600 text-white'
151
+ : 'text-slate-400 hover:text-white hover:bg-white/10'
152
+ }`}
153
+ >
154
+ <Zap className="w-4 h-4" />
155
+ Воронка
156
+ </Link>
157
+ </div>
 
 
158
  </div>
159
+ )}
160
 
161
  {/* CONNECTIONS Group */}
162
  {user?.role === 'OWNER' && (
 
224
  <p className="text-sm font-medium text-white truncate">
225
  {user.full_name || user.email}
226
  </p>
227
+ <div className="flex items-center gap-1.5">
228
+ <span className={`px-1.5 py-0.5 rounded text-[10px] font-bold uppercase ${
229
+ user.role === 'OWNER'
230
+ ? 'bg-indigo-600 text-white'
231
+ : 'bg-slate-600 text-slate-200'
232
+ }`}>
233
+ {user.role === 'OWNER' ? 'Владелец' : 'Менеджер'}
234
+ </span>
235
+ <span className="text-xs text-slate-500 truncate">• {user.tenant_name}</span>
236
+ </div>
237
  </div>
238
 
239
  {/* Logout Button */}
frontend/lib/permissions.ts ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Permissions Helper
3
+ *
4
+ * Проверка прав доступа для разных ролей
5
+ */
6
+
7
+ export type UserRole = 'OWNER' | 'MANAGER'
8
+
9
+ /**
10
+ * Проверяет, имеет ли пользователь доступ к определённому разделу
11
+ */
12
+ export function hasAccess(userRole: UserRole | undefined, section: string): boolean {
13
+ if (!userRole) return false
14
+
15
+ // OWNER имеет доступ ко всему
16
+ if (userRole === 'OWNER') return true
17
+
18
+ // MANAGER имеет доступ только к чатам
19
+ const managerAllowedSections = [
20
+ '/chats',
21
+ '/chat/', // для отдельных чатов
22
+ ]
23
+
24
+ return managerAllowedSections.some(allowed => section.startsWith(allowed))
25
+ }
26
+
27
+ /**
28
+ * Проверяет, является ли пользователь владельцем
29
+ */
30
+ export function isOwner(userRole: UserRole | undefined): boolean {
31
+ return userRole === 'OWNER'
32
+ }
33
+
34
+ /**
35
+ * Проверяет, является ли пользователь менеджером
36
+ */
37
+ export function isManager(userRole: UserRole | undefined): boolean {
38
+ return userRole === 'MANAGER'
39
+ }
40
+
41
+ /**
42
+ * Возвращает роль пользователя на русском
43
+ */
44
+ export function getRoleLabel(userRole: UserRole | undefined): string {
45
+ switch (userRole) {
46
+ case 'OWNER':
47
+ return 'Владелец'
48
+ case 'MANAGER':
49
+ return 'Менеджер'
50
+ default:
51
+ return 'Гость'
52
+ }
53
+ }