Files
Tg-job/mtucijobsweb2/fsd/widgets/Login/Login.tsx

97 lines
2.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use client';
import { useState } from 'react';
import { Button, Form, Input, notification } from 'antd';
import { LoginData } from '../../../types/types';
import { login } from '@/api/api';
import { useRouter } from 'next/navigation';
import { useForm } from 'antd/es/form/Form';
import { useAuth } from '@/fsd/app/provider/AuthContext';
import style from './Login.module.scss'
const LoginComponent = () => {
const router = useRouter();
const { login: authLogin } = useAuth(); // Получаем метод login из контекста
const [form] = useForm();
const [loading, setLoading] = useState(false);
const onFinish = async (values: LoginData) => {
setLoading(true);
try {
const response = await login(values); // Отправляем запрос на логин
if (response) {
// Проверяем статус ответа
const token = response.access_token;
authLogin(token, 3600); // Устанавливаем токен в контексте
notification.success({
message: 'Вход в систему прошел успешно',
description: 'Вы успешно вошли в систему.',
});
await router.push('/create'); // Перенаправляем на страницу после успешного входа
await form.resetFields();
} else {
// Если сервер возвращает ошибку с кодом 200 (например, если в теле ответа есть ошибка)
notification.error({
message: 'Ошибка входа',
description:
'Произошла ошибка при входе в систему. Пожалуйста, попробуйте снова.',
});
}
} catch (error) {
console.error('Login error:', error);
notification.error({
message: 'Ошибка входа',
description:
'Произошла ошибка при входе в систему. Пожалуйста, попробуйте снова.',
});
} finally {
setLoading(false);
}
};
return (
<div style={{ maxWidth: '400px', margin: 'auto', padding: '20px' }}>
<h2>Вход</h2>
<Form
form={form}
name='login'
initialValues={{ remember: true }}
onFinish={onFinish}
layout='vertical'
>
<Form.Item
label='Имя пользователя'
name='username'
rules={[
{
required: true,
message: 'Пожалуйста, введите свое имя пользователя!',
},
]}
>
<Input />
</Form.Item>
<Form.Item
label='Пароль'
name='password'
rules={[
{ required: true, message: 'Пожалуйста, введите свой пароль!' },
]}
>
<Input.Password />
</Form.Item>
<Form.Item>
<Button type='primary' htmlType='submit' loading={loading} className={style.loginButton}>
Войти
</Button>
</Form.Item>
</Form>
</div>
);
};
export default LoginComponent;