216 lines
8.5 KiB
TypeScript
216 lines
8.5 KiB
TypeScript
import { useState } from 'react'
|
||
import {
|
||
Badge,
|
||
Box,
|
||
Button,
|
||
Center,
|
||
Divider,
|
||
Group,
|
||
PasswordInput,
|
||
SegmentedControl,
|
||
Stack,
|
||
Text,
|
||
useMantineColorScheme,
|
||
} from '@mantine/core'
|
||
import { useForm } from '@mantine/form'
|
||
import { notifications } from '@mantine/notifications'
|
||
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 (
|
||
<Box>
|
||
<Group gap={4} grow>
|
||
{STRENGTH.map((_, i) => (
|
||
<Box
|
||
key={i}
|
||
h={4}
|
||
style={{
|
||
borderRadius: 2,
|
||
background:
|
||
i < level
|
||
? `var(--mantine-color-${meta.color}-filled)`
|
||
: 'var(--mantine-color-default-border)',
|
||
}}
|
||
/>
|
||
))}
|
||
</Group>
|
||
<Text size="xs" c="dimmed" mt={4}>{meta.label}</Text>
|
||
</Box>
|
||
)
|
||
}
|
||
|
||
function Row({ label, children }: { label: string; children: React.ReactNode }) {
|
||
return (
|
||
<Group justify="space-between" wrap="nowrap" py={10}>
|
||
<Text size="sm" c="dimmed">{label}</Text>
|
||
<Box>{children}</Box>
|
||
</Group>
|
||
)
|
||
}
|
||
|
||
export default function SettingsPage() {
|
||
const { user, logout } = useAuth()
|
||
const { colorScheme, setColorScheme } = useMantineColorScheme()
|
||
const [loading, setLoading] = useState(false)
|
||
const [pending, setPending] = useState<string | null>(null)
|
||
|
||
const role = user?.is_root ? 'Суперадмин' : user?.is_observer ? 'Наблюдатель' : 'Администратор'
|
||
|
||
const form = useForm({
|
||
initialValues: { current_password: '', new_password: '', confirm_password: '' },
|
||
validate: {
|
||
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: (v, values) => (v !== values.new_password ? 'Пароли не совпадают' : null),
|
||
},
|
||
})
|
||
|
||
const handleConfirm = async () => {
|
||
setLoading(true)
|
||
try {
|
||
await authApi.updateProfile({
|
||
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 (
|
||
<Stack gap="lg" maw={640}>
|
||
<PageHeader title="Настройки" description="Профиль, оформление и безопасность" />
|
||
|
||
<Panel title="Профиль" extra={<Badge color="gray">{role}</Badge>}>
|
||
<Box mx={-0}>
|
||
<Row label="Логин"><Text size="sm" fw={500}>{user?.login || '—'}</Text></Row>
|
||
{user?.last_login && (
|
||
<>
|
||
<Divider />
|
||
<Row label="Последний вход">
|
||
<Text size="sm">{dayjs(user.last_login).format('D MMM YYYY, HH:mm')}</Text>
|
||
</Row>
|
||
</>
|
||
)}
|
||
{user?.last_ip_login && (
|
||
<>
|
||
<Divider />
|
||
<Row label="Последний IP">
|
||
<Text size="sm" ff="monospace">{user.last_ip_login}</Text>
|
||
</Row>
|
||
</>
|
||
)}
|
||
</Box>
|
||
</Panel>
|
||
|
||
<Panel title="Оформление">
|
||
<Group justify="space-between" wrap="wrap" gap="sm">
|
||
<Box>
|
||
<Text size="sm">Тема интерфейса</Text>
|
||
<Text size="xs" c="dimmed">«Системная» следует настройкам вашей ОС</Text>
|
||
</Box>
|
||
<SegmentedControl
|
||
value={colorScheme}
|
||
onChange={(v) => setColorScheme(v as 'light' | 'dark' | 'auto')}
|
||
data={[
|
||
{ value: 'light', label: <Center style={{ gap: 6 }}><IconSun size={14} />Светлая</Center> },
|
||
{ value: 'dark', label: <Center style={{ gap: 6 }}><IconMoon size={14} />Тёмная</Center> },
|
||
{ value: 'auto', label: <Center style={{ gap: 6 }}><IconDeviceDesktop size={14} />Системная</Center> },
|
||
]}
|
||
/>
|
||
</Group>
|
||
</Panel>
|
||
|
||
<Panel title="Смена пароля">
|
||
<form onSubmit={form.onSubmit((v) => setPending(v.new_password))}>
|
||
<Stack gap="md">
|
||
<PasswordInput
|
||
label="Текущий пароль"
|
||
autoComplete="current-password"
|
||
{...form.getInputProps('current_password')}
|
||
/>
|
||
|
||
<Divider />
|
||
|
||
<Stack gap="xs">
|
||
<PasswordInput
|
||
label="Новый пароль"
|
||
description="Минимум 6 символов"
|
||
autoComplete="new-password"
|
||
{...form.getInputProps('new_password')}
|
||
/>
|
||
<PasswordStrength value={form.values.new_password} />
|
||
</Stack>
|
||
|
||
<PasswordInput
|
||
label="Повторите новый пароль"
|
||
autoComplete="new-password"
|
||
{...form.getInputProps('confirm_password')}
|
||
/>
|
||
|
||
<Group justify="space-between" mt="xs" wrap="nowrap">
|
||
<Text size="xs" c="dimmed">После смены пароля потребуется войти заново</Text>
|
||
<Button type="submit">Изменить пароль</Button>
|
||
</Group>
|
||
</Stack>
|
||
</form>
|
||
</Panel>
|
||
|
||
<ConfirmModal
|
||
opened={pending !== null}
|
||
onClose={() => setPending(null)}
|
||
onConfirm={handleConfirm}
|
||
title="Изменить пароль?"
|
||
message="Вы будете разлогинены на всех устройствах и должны будете войти заново."
|
||
confirmLabel="Изменить"
|
||
danger
|
||
loading={loading}
|
||
/>
|
||
</Stack>
|
||
)
|
||
} |