Added QR auth method
Deploy Frontend / build-and-deploy (push) Successful in 45s
Details
Deploy Frontend / build-and-deploy (push) Successful in 45s
Details
This commit is contained in:
parent
906c05b519
commit
97b77a3ea5
|
|
@ -21,4 +21,10 @@ export const telegramManagersApi = {
|
|||
|
||||
delete: (managerId: number) =>
|
||||
managerApiClient.delete(`/managers/${managerId}`),
|
||||
|
||||
startQr: () =>
|
||||
managerApiClient.post('/managers/auth/qr/start'),
|
||||
|
||||
checkQrStatus: (token: string) =>
|
||||
managerApiClient.get(`/managers/auth/qr/status?token=${token}`),
|
||||
}
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
import { useState } from 'react'
|
||||
import { Modal, Stack, TextInput, Button, Text, Alert, Group } from '@mantine/core'
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { Modal, Stack, TextInput, Button, Text, Alert, Group, Tabs, Image, Center, Loader } from '@mantine/core'
|
||||
import { useForm } from '@mantine/form'
|
||||
import { notifications } from '@mantine/notifications'
|
||||
import { IconDeviceMobile, IconLock } from '@tabler/icons-react'
|
||||
import { IconDeviceMobile, IconQrcode, IconMessageCircle } from '@tabler/icons-react'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import {telegramManagersApi} from "@/api/telegramManagers.ts";
|
||||
|
||||
|
|
@ -12,8 +12,17 @@ interface AddManagerModalProps {
|
|||
}
|
||||
|
||||
export default function AddManagerModal({ opened, onClose }: AddManagerModalProps) {
|
||||
const [step, setStep] = useState<'phone' | 'code'>('phone')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [activeTab, setActiveTab] = useState<string | null>('qr')
|
||||
|
||||
// Состояния для авторизации по номеру
|
||||
const [stepPhone, setStepPhone] = useState<'phone' | 'code'>('phone')
|
||||
const [loadingPhone, setLoadingPhone] = useState(false)
|
||||
|
||||
// Состояния для авторизации по QR
|
||||
const [qrData, setQrData] = useState<{ token: string, img: string } | null>(null)
|
||||
const [loadingQr, setLoadingQr] = useState(false)
|
||||
const pollingIntervalRef = useRef<number | null>(null)
|
||||
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const form = useForm({
|
||||
|
|
@ -25,88 +34,176 @@ export default function AddManagerModal({ opened, onClose }: AddManagerModalProp
|
|||
},
|
||||
})
|
||||
|
||||
// ── ЛОГИКА АВТОРИЗАЦИИ ПО НОМЕРУ ──────────────────────────────
|
||||
const handleSendCode = async (values: typeof form.values) => {
|
||||
setLoading(true)
|
||||
setLoadingPhone(true)
|
||||
try {
|
||||
await telegramManagersApi.sendCode(values.phone, values.name)
|
||||
notifications.show({ title: 'Код отправлен', message: 'Проверьте Telegram-аккаунт менеджера', color: 'green' })
|
||||
setStep('code')
|
||||
notifications.show({ title: 'Код отправлен', message: 'Проверьте Telegram-аккаунт', color: 'green' })
|
||||
setStepPhone('code')
|
||||
} catch (error: any) {
|
||||
notifications.show({ title: 'Ошибка', message: error.response?.data?.detail || 'Не удалось отправить код', color: 'red' })
|
||||
} finally {
|
||||
setLoading(false)
|
||||
setLoadingPhone(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleVerifyCode = async (values: typeof form.values) => {
|
||||
setLoading(true)
|
||||
setLoadingPhone(true)
|
||||
try {
|
||||
await telegramManagersApi.verifyCode(values.phone, values.code, values.password || undefined)
|
||||
notifications.show({ title: 'Успешно', message: 'Менеджер успешно авторизован и добавлен', color: 'green' })
|
||||
notifications.show({ title: 'Успешно', message: 'Менеджер подключен', color: 'green' })
|
||||
queryClient.invalidateQueries({ queryKey: ['telegram-managers-status'] })
|
||||
handleClose()
|
||||
} catch (error: any) {
|
||||
notifications.show({ title: 'Ошибка', message: error.response?.data?.detail || 'Неверный код или ошибка входа', color: 'red' })
|
||||
notifications.show({ title: 'Ошибка', message: error.response?.data?.detail || 'Неверный код', color: 'red' })
|
||||
} finally {
|
||||
setLoading(false)
|
||||
setLoadingPhone(false)
|
||||
}
|
||||
}
|
||||
|
||||
// ── ЛОГИКА АВТОРИЗАЦИИ ПО QR ──────────────────────────────────
|
||||
const fetchQr = async () => {
|
||||
setLoadingQr(true)
|
||||
stopPolling()
|
||||
try {
|
||||
const res = await telegramManagersApi.startQr()
|
||||
setQrData({ token: res.data.token, img: res.data.qr_base64 })
|
||||
startPolling(res.data.token)
|
||||
} catch (error: any) {
|
||||
notifications.show({ title: 'Ошибка', message: 'Не удалось сгенерировать QR-код', color: 'red' })
|
||||
} finally {
|
||||
setLoadingQr(false)
|
||||
}
|
||||
}
|
||||
|
||||
const startPolling = (token: string) => {
|
||||
pollingIntervalRef.current = window.setInterval(async () => {
|
||||
try {
|
||||
const res = await telegramManagersApi.checkQrStatus(token)
|
||||
if (res.data.status === 'success') {
|
||||
stopPolling()
|
||||
notifications.show({ title: 'Успешно', message: `Менеджер ${res.data.name} подключен!`, color: 'green' })
|
||||
queryClient.invalidateQueries({ queryKey: ['telegram-managers-status'] })
|
||||
handleClose()
|
||||
} else if (res.data.status === 'failed') {
|
||||
stopPolling()
|
||||
notifications.show({ title: 'Ошибка', message: res.data.error || 'Ошибка сканирования', color: 'red' })
|
||||
setQrData(null) // Сбрасываем QR, чтобы пользователь мог запросить новый
|
||||
}
|
||||
} catch (err) {
|
||||
stopPolling()
|
||||
}
|
||||
}, 3000) // Проверяем статус каждые 3 секунды
|
||||
}
|
||||
|
||||
const stopPolling = () => {
|
||||
if (pollingIntervalRef.current) {
|
||||
clearInterval(pollingIntervalRef.current)
|
||||
pollingIntervalRef.current = null
|
||||
}
|
||||
}
|
||||
|
||||
// Обработка открытия/закрытия модалки
|
||||
useEffect(() => {
|
||||
if (opened && activeTab === 'qr' && !qrData) {
|
||||
fetchQr()
|
||||
}
|
||||
if (!opened) {
|
||||
stopPolling()
|
||||
setQrData(null)
|
||||
}
|
||||
return stopPolling
|
||||
}, [opened, activeTab])
|
||||
|
||||
const handleClose = () => {
|
||||
setStep('phone')
|
||||
setStepPhone('phone')
|
||||
form.reset()
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal opened={opened} onClose={handleClose} title="Подключение менеджера Telegram" size="sm">
|
||||
{step === 'phone' ? (
|
||||
<form onSubmit={form.onSubmit(handleSendCode)}>
|
||||
<Stack gap="md">
|
||||
<TextInput
|
||||
label="Имя менеджера"
|
||||
placeholder="Иван Иванов"
|
||||
required
|
||||
{...form.getInputProps('name')}
|
||||
/>
|
||||
<TextInput
|
||||
label="Номер телефона"
|
||||
placeholder="+79991234567"
|
||||
required
|
||||
description="В международном формате с плюсом"
|
||||
{...form.getInputProps('phone')}
|
||||
/>
|
||||
<Group justify="flex-end" mt="md">
|
||||
<Button variant="default" onClick={handleClose}>Отмена</Button>
|
||||
<Button type="submit" loading={loading}>Далее (Запросить код)</Button>
|
||||
</Group>
|
||||
<Modal opened={opened} onClose={handleClose} title="Подключение менеджера Telegram" size="md">
|
||||
<Tabs value={activeTab} onChange={setActiveTab}>
|
||||
<Tabs.List mb="md">
|
||||
<Tabs.Tab value="qr" leftSection={<IconQrcode size={16} />}>По QR-коду</Tabs.Tab>
|
||||
<Tabs.Tab value="phone" leftSection={<IconMessageCircle size={16} />}>По номеру и коду</Tabs.Tab>
|
||||
</Tabs.List>
|
||||
|
||||
{/* ВКЛАДКА: QR КОД */}
|
||||
<Tabs.Panel value="qr">
|
||||
<Stack gap="md" align="center">
|
||||
<Text size="sm" c="dimmed" ta="center">
|
||||
Откройте Telegram на телефоне менеджера → Настройки → Устройства → Подключить устройство, и отсканируйте этот код.
|
||||
</Text>
|
||||
|
||||
<Center style={{ width: 250, height: 250, border: '1px solid #eee', borderRadius: 8 }}>
|
||||
{loadingQr ? (
|
||||
<Loader />
|
||||
) : qrData ? (
|
||||
<Image src={qrData.img} w={230} h={230} fit="contain" />
|
||||
) : (
|
||||
<Button variant="light" onClick={fetchQr}>Сгенерировать новый QR</Button>
|
||||
)}
|
||||
</Center>
|
||||
|
||||
{qrData && (
|
||||
<Loader type="dots" size="sm" /> // Визуальный индикатор ожидания сканирования
|
||||
)}
|
||||
</Stack>
|
||||
</form>
|
||||
) : (
|
||||
<form onSubmit={form.onSubmit(handleVerifyCode)}>
|
||||
<Stack gap="md">
|
||||
<Alert icon={<IconDeviceMobile size={16} />} color="blue" variant="light">
|
||||
Код подтверждения отправлен в официальное приложение Telegram на номер {form.values.phone}
|
||||
</Alert>
|
||||
<TextInput
|
||||
label="Код из Telegram"
|
||||
placeholder="12345"
|
||||
required
|
||||
{...form.getInputProps('code')}
|
||||
/>
|
||||
<TextInput
|
||||
label="Облачный пароль 2FA (если установлен)"
|
||||
placeholder="Пароль двухэтапной аутентификации"
|
||||
type="password"
|
||||
{...form.getInputProps('password')}
|
||||
/>
|
||||
<Group justify="flex-end" mt="md">
|
||||
<Button variant="default" onClick={() => setStep('phone')}>Назад</Button>
|
||||
<Button type="submit" loading={loading} color="green">Подтвердить и войти</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</form>
|
||||
)}
|
||||
</Tabs.Panel>
|
||||
|
||||
{/* ВКЛАДКА: НОМЕР ТЕЛЕФОНА */}
|
||||
<Tabs.Panel value="phone">
|
||||
{stepPhone === 'phone' ? (
|
||||
<form onSubmit={form.onSubmit(handleSendCode)}>
|
||||
<Stack gap="md">
|
||||
<TextInput
|
||||
label="Имя менеджера"
|
||||
placeholder="Иван Иванов"
|
||||
required
|
||||
{...form.getInputProps('name')}
|
||||
/>
|
||||
<TextInput
|
||||
label="Номер телефона"
|
||||
placeholder="+79991234567"
|
||||
required
|
||||
description="В международном формате с плюсом"
|
||||
{...form.getInputProps('phone')}
|
||||
/>
|
||||
<Group justify="flex-end" mt="md">
|
||||
<Button variant="default" onClick={handleClose}>Отмена</Button>
|
||||
<Button type="submit" loading={loadingPhone}>Далее (Запросить код)</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</form>
|
||||
) : (
|
||||
<form onSubmit={form.onSubmit(handleVerifyCode)}>
|
||||
<Stack gap="md">
|
||||
<Alert icon={<IconDeviceMobile size={16} />} color="blue" variant="light">
|
||||
Код отправлен в официальное приложение Telegram на номер {form.values.phone}
|
||||
</Alert>
|
||||
<TextInput
|
||||
label="Код из Telegram"
|
||||
placeholder="12345"
|
||||
required
|
||||
{...form.getInputProps('code')}
|
||||
/>
|
||||
<TextInput
|
||||
label="Облачный пароль 2FA (если установлен)"
|
||||
placeholder="Пароль двухэтапной аутентификации"
|
||||
type="password"
|
||||
{...form.getInputProps('password')}
|
||||
/>
|
||||
<Group justify="flex-end" mt="md">
|
||||
<Button variant="default" onClick={() => setStepPhone('phone')}>Назад</Button>
|
||||
<Button type="submit" loading={loadingPhone} color="green">Подтвердить и войти</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</form>
|
||||
)}
|
||||
</Tabs.Panel>
|
||||
</Tabs>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
Loading…
Reference in New Issue