diff --git a/src/components/Layout/Header.tsx b/src/components/Layout/Header.tsx index 4d0aedd..467d563 100644 --- a/src/components/Layout/Header.tsx +++ b/src/components/Layout/Header.tsx @@ -7,6 +7,7 @@ import { IconLogout, IconSearch, IconSun, IconMoon, IconUser } from '@tabler/ico import { useLocation } from 'react-router-dom' import { useAuth } from '@/hooks/useAuth' import { findTrail } from './navigation' +import { ColorSchemeToggle } from '@/components/ui/ColorSchemeToggle' interface HeaderProps { toggleMobile: () => void @@ -15,20 +16,6 @@ interface HeaderProps { desktopOpened: boolean } -function ColorSchemeToggle() { - const { setColorScheme } = useMantineColorScheme() - const computed = useComputedColorScheme('light', { getInitialValueInEffect: true }) - return ( - setColorScheme(computed === 'light' ? 'dark' : 'light')} - > - {computed === 'dark' ? : } - - ) -} - export default function Header({ toggleMobile, toggleDesktop, mobileOpened, desktopOpened }: HeaderProps) { const { user, logout } = useAuth() const { pathname } = useLocation() diff --git a/src/components/ui/ColorSchemeToggle.tsx b/src/components/ui/ColorSchemeToggle.tsx new file mode 100644 index 0000000..a2c161a --- /dev/null +++ b/src/components/ui/ColorSchemeToggle.tsx @@ -0,0 +1,17 @@ +import { ActionIcon, useComputedColorScheme, useMantineColorScheme } from '@mantine/core' +import { IconMoon, IconSun } from '@tabler/icons-react' + +export function ColorSchemeToggle() { + const { setColorScheme } = useMantineColorScheme() + const computed = useComputedColorScheme('light', { getInitialValueInEffect: true }) + + return ( + setColorScheme(computed === 'light' ? 'dark' : 'light')} + > + {computed === 'dark' ? : } + + ) +} \ No newline at end of file diff --git a/src/pages/Login.tsx b/src/pages/Login.tsx index b161000..a2ee066 100644 --- a/src/pages/Login.tsx +++ b/src/pages/Login.tsx @@ -1,86 +1,102 @@ import { useState } from 'react' -import { - Container, - Paper, - Title, - Text, - TextInput, - PasswordInput, - Button, - Group, -} from '@mantine/core' +import { Alert, Box, Button, Paper, PasswordInput, Stack, Text, TextInput, Title } from '@mantine/core' import { useForm } from '@mantine/form' -import { notifications } from '@mantine/notifications' +import { IconAlertCircle } from '@tabler/icons-react' import { useAuth } from '@/hooks/useAuth' +import { ColorSchemeToggle } from '@/components/ui/ColorSchemeToggle' export default function Login() { const { login } = useAuth() const [loading, setLoading] = useState(false) + const [error, setError] = useState(null) + const [capsLock, setCapsLock] = useState(false) const form = useForm({ - initialValues: { - login: '', - password: '', - }, + initialValues: { login: '', password: '' }, validate: { - login: (value: string | any[]) => (value.length < 3 ? 'Логин должен содержать минимум 3 символа' : null), - password: (value: string | any[]) => (value.length < 4 ? 'Пароль должен содержать минимум 4 символа' : null), + login: (v) => (v.trim().length < 3 ? 'Минимум 3 символа' : null), + password: (v) => (v.length < 4 ? 'Минимум 4 символа' : null), }, }) const handleSubmit = async (values: typeof form.values) => { setLoading(true) + setError(null) try { - await login(values.login, values.password) - notifications.show({ - title: 'Успешный вход', - message: `Добро пожаловать, ${values.login}!`, - color: 'green', - }) - } catch (error: any) { - notifications.show({ - title: 'Ошибка входа', - message: error.response?.data?.error_description || 'Неверный логин или пароль', - color: 'red', - }) + await login(values.login.trim(), values.password) + } catch (e: any) { + setError(e.response?.data?.error_description || 'Неверный логин или пароль') } finally { setLoading(false) } } return ( - - - Корпоративная панель администратора - - - Введите свои данные для входа в систему - + + + + - -
- + + + + Р + + Вход в систему + Портал РусПЭТ · панель администратора + - + + + + {error && ( + } p="sm"> + {error} + + )} - - - - - -
+ + + setCapsLock(e.getModifierState('CapsLock'))} + onKeyUp={(e) => setCapsLock(e.getModifierState('CapsLock'))} + {...form.getInputProps('password')} + /> + + + + + + + ) } \ No newline at end of file diff --git a/src/pages/settings/SettingsPage.tsx b/src/pages/settings/SettingsPage.tsx index c74150c..3948587 100644 --- a/src/pages/settings/SettingsPage.tsx +++ b/src/pages/settings/SettingsPage.tsx @@ -1,180 +1,217 @@ import { useState } from 'react' import { - Paper, + Badge, + Box, + Button, + Center, + Divider, + Group, + PasswordInput, + SegmentedControl, Stack, Text, - PasswordInput, - Button, - Group, - Alert, - Box, - Title, - Divider, + useMantineColorScheme, } from '@mantine/core' import { useForm } from '@mantine/form' import { notifications } from '@mantine/notifications' -import { modals } from '@mantine/modals' -import { IconShield, IconAlertCircle, IconKey } from '@tabler/icons-react' +import { IconDeviceDesktop, IconMoon, IconSun } from '@tabler/icons-react' +import dayjs from 'dayjs' import { authApi } from '@/api/auth' import { useAuth } from '@/hooks/useAuth' +import { PageHeader } from '@/components/ui/PageHeader' +import { Panel } from '@/components/ui/Panel' +import { ConfirmModal } from '@/components/ui/ConfirmModal' + +const STRENGTH = [ + { label: 'Слабый', color: 'red' }, + { label: 'Средний', color: 'orange' }, + { label: 'Хороший', color: 'lime' }, + { label: 'Надёжный', color: 'green' }, +] + +// 0 — пусто, 1..4 — уровень +function strengthOf(p: string) { + if (!p) return 0 + let s = 1 + if (p.length >= 10) s++ + if (/[A-ZА-ЯЁ]/.test(p) && /[a-zа-яё]/.test(p)) s++ + if (/\d/.test(p) && /[^\p{L}\d\s]/u.test(p)) s++ + return s +} + +function PasswordStrength({ value }: { value: string }) { + const level = strengthOf(value) + if (level === 0) return null + const meta = STRENGTH[level - 1] + return ( + + + {STRENGTH.map((_, i) => ( + + ))} + + {meta.label} + + ) +} + +function Row({ label, children }: { label: string; children: React.ReactNode }) { + return ( + + {label} + {children} + + ) +} export default function SettingsPage() { + const { user, logout } = useAuth() + const { colorScheme, setColorScheme } = useMantineColorScheme() const [loading, setLoading] = useState(false) - const { user } = useAuth() + const [pending, setPending] = useState(null) + + const role = user?.is_root ? 'Суперадмин' : user?.is_observer ? 'Наблюдатель' : 'Администратор' const form = useForm({ - initialValues: { - current_password: '', - new_password: '', - confirm_password: '', - }, + initialValues: { current_password: '', new_password: '', confirm_password: '' }, validate: { - current_password: (value) => - value.length === 0 ? 'Введите текущий пароль' : null, - new_password: (value) => { - if (value.length === 0) return 'Введите новый пароль' - if (value.length < 6) return 'Пароль должен содержать минимум 6 символов' + current_password: (v) => (v ? null : 'Введите текущий пароль'), + new_password: (v, values) => { + if (!v) return 'Введите новый пароль' + if (v.length < 6) return 'Минимум 6 символов' + if (v === values.current_password) return 'Новый пароль совпадает с текущим' return null }, - confirm_password: (value, values) => - value !== values.new_password ? 'Пароли не совпадают' : null, + confirm_password: (v, values) => (v !== values.new_password ? 'Пароли не совпадают' : null), }, }) - const handleSubmit = async (values: typeof form.values) => { - // Подтверждение через модальное окно - modals.openConfirmModal({ - title: 'Подтвердите смену пароля', - children: ( - - Вы уверены, что хотите изменить пароль? После смены пароля вам нужно будет - войти заново на всех устройствах. - - ), - labels: { confirm: 'Изменить пароль', cancel: 'Отмена' }, - confirmProps: { color: 'red' }, - onConfirm: async () => { - setLoading(true) - try { - await authApi.updateProfile({ password: values.new_password }) - - notifications.show({ - title: 'Успешно', - message: 'Пароль успешно изменен', - color: 'green', - }) - - form.reset() - - // Разлогиниваем пользователя, чтобы он вошёл заново - setTimeout(() => { - localStorage.removeItem('token') - window.location.href = '/login' - }, 1500) - - } catch (error: any) { - notifications.show({ - title: 'Ошибка', - message: error.response?.data?.error_description || 'Не удалось изменить пароль', - color: 'red', - }) - } finally { - setLoading(false) - } - }, - }) + const handleConfirm = async () => { + setLoading(true) + try { + await authApi.updateProfile({ + current_password: form.values.current_password, + password: form.values.new_password, + }) + setPending(null) + form.reset() + notifications.show({ + title: 'Пароль изменён', + message: 'Сейчас вы будете перенаправлены на страницу входа', + color: 'green', + }) + setTimeout(() => logout(), 1500) + } catch (e: any) { + setPending(null) + notifications.show({ + title: 'Ошибка', + message: e.response?.data?.error_description || 'Не удалось изменить пароль', + color: 'red', + }) + } finally { + setLoading(false) + } } return ( - - -
- Настройки - - Управление вашим аккаунтом - -
- - {/* Информация о профиле */} - - - - Логин: - {user?.login || '—'} - - {user?.last_login && ( - - Последний вход: - - {new Date(user.last_login).toLocaleString('ru-RU')} - - - )} - {user?.last_ip_login && ( - - Последний IP: - {user.last_ip_login} - - )} - - - - {/* Смена пароля */} - - - - Смена пароля - - - } - color="yellow" - variant="light" - mb="md" - > - - После смены пароля вам нужно будет войти заново на всех устройствах. - - - -
- - + + + {role}}> + + {user?.login || '—'} + {user?.last_login && ( + <> + + {dayjs(user.last_login).format('D MMM YYYY, HH:mm')} + + + )} + {user?.last_ip_login && ( + <> + + + {user.last_ip_login} + + + )} + + + + + + Тема интерфейса + «Системная» следует настройкам вашей ОС + + setColorScheme(v as 'light' | 'dark' | 'auto')} + data={[ + { value: 'light', label:
Светлая
}, + { value: 'dark', label:
Тёмная
}, + { value: 'auto', label:
Системная
}, + ]} + /> +
+
+ + + setPending(v.new_password))}> + + + + + + - - - - - - + - -
-
-
+ + + + + После смены пароля потребуется войти заново + + + + + + + setPending(null)} + onConfirm={handleConfirm} + title="Изменить пароль?" + message="Вы будете разлогинены на всех устройствах и должны будете войти заново." + confirmLabel="Изменить" + danger + loading={loading} + /> + ) } \ No newline at end of file