File size: 3,766 Bytes
fc1eb7c | 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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | import React from "react";
import { useAuth } from "@/hooks/use-auth";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Shield, Lock } from "lucide-react";
interface RoleGuardProps {
allowedRoles: string[];
children: React.ReactNode;
fallback?: React.ReactNode;
showMessage?: boolean;
}
export function RoleGuard({ allowedRoles, children, fallback, showMessage = true }: RoleGuardProps) {
const { user } = useAuth();
if (!user) {
return fallback || (showMessage ? (
<Alert>
<Lock className="h-4 w-4" />
<AlertDescription>
Необходимо войти в систему для доступа к этому разделу.
</AlertDescription>
</Alert>
) : null);
}
if (!allowedRoles.includes(user.role)) {
return fallback || (showMessage ? (
<Alert>
<Shield className="h-4 w-4" />
<AlertDescription>
У вас недостаточно прав для доступа к этому разделу.
Текущая роль: {getRoleDisplayName(user.role)}.
Обратитесь к администратору для получения дополнительных прав.
</AlertDescription>
</Alert>
) : null);
}
return <>{children}</>;
}
// Компонент для скрытия элементов интерфейса на основе ролей
interface RoleBasedProps {
allowedRoles: string[];
children: React.ReactNode;
}
export function RoleBased({ allowedRoles, children }: RoleBasedProps) {
const { user } = useAuth();
if (!user || !allowedRoles.includes(user.role)) {
return null;
}
return <>{children}</>;
}
// Хук для проверки прав доступа
export function usePermissions() {
const { user } = useAuth();
const hasRole = (role: string) => {
return user?.role === role;
};
const hasAnyRole = (roles: string[]) => {
return user && roles.includes(user.role);
};
const canView = () => {
return hasAnyRole(['admin', 'operator', 'engineer', 'viewer']);
};
const canEdit = () => {
return hasAnyRole(['admin', 'operator', 'engineer']);
};
const canCreate = () => {
return hasAnyRole(['admin', 'operator', 'engineer']);
};
const canDelete = () => {
return hasAnyRole(['admin', 'operator']);
};
const canManageUsers = () => {
return hasRole('admin');
};
const canManageSystem = () => {
return hasRole('admin');
};
return {
hasRole,
hasAnyRole,
canView,
canEdit,
canCreate,
canDelete,
canManageUsers,
canManageSystem,
currentRole: user?.role || 'guest'
};
}
export function getRoleDisplayName(role: string): string {
switch (role) {
case 'admin':
return 'Администратор';
case 'operator':
return 'Оператор';
case 'engineer':
return 'Инженер';
case 'viewer':
return 'Просмотр';
default:
return 'Неизвестная роль';
}
}
export function getRoleDescription(role: string): string {
switch (role) {
case 'admin':
return 'Полный доступ ко всем функциям системы';
case 'operator':
return 'Может выполнять осмотры, создавать отчеты, управлять оборудованием';
case 'engineer':
return 'Может просматривать данные, выполнять ежедневные осмотры';
case 'viewer':
return 'Только просмотр данных без возможности изменений';
default:
return 'Описание роли недоступно';
}
} |