Files
tests/frontend_reactjs/src/pages/auth/SignIn.tsx
2024-06-24 17:48:01 +09:00

91 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.

import React, { useState, ChangeEvent, FormEvent } from 'react';
import { useForm, SubmitHandler } from 'react-hook-form';
import { TextField, Button, Container, Typography, Box } from '@mui/material';
import axios, { AxiosResponse } from 'axios';
import { SignInFormData, ApiResponse } from '../../types/auth';
import { UserData, useAuthStore } from '../../store/auth';
import { useNavigate } from 'react-router-dom';
import axiosInstance from '../../http/axiosInstance';
import AuthService from '../../services/AuthService';
const SignIn = () => {
const { register, handleSubmit, formState: { errors } } = useForm<SignInFormData>({
defaultValues: {
username: '',
password: '',
grant_type: 'password',
scope: '',
client_id: '',
client_secret: ''
}
})
const authStore = useAuthStore();
const navigate = useNavigate();
const onSubmit: SubmitHandler<SignInFormData> = async (data) => {
const formBody = new URLSearchParams();
for (const key in data) {
formBody.append(key, data[key as keyof SignInFormData] as string);
}
try {
const response: AxiosResponse<ApiResponse> = await axiosInstance.post(`/auth/login`, formBody, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
console.log('Вход произошел успешно:', response.data);
const token = response.data.access_token
const userDataResponse: AxiosResponse<ApiResponse> = await AuthService.getCurrentUser(token)
console.log('Пользователь:', userDataResponse.data)
authStore.setUserData(JSON.stringify(userDataResponse.data))
authStore.login(token)
navigate('/');
} catch (error) {
console.error('Ошибка при входе:', error);
}
};
return (
<Container maxWidth="sm">
<Box my={4}>
<Typography variant="h4" component="h1" gutterBottom>
Вход
</Typography>
<form onSubmit={handleSubmit(onSubmit)}>
<TextField
fullWidth
margin="normal"
label="Логин"
{...register('username', { required: 'Логин обязателен' })}
error={!!errors.username}
helperText={errors.username?.message}
/>
<TextField
fullWidth
margin="normal"
type="password"
label="Пароль"
{...register('password', { required: 'Пароль обязателен' })}
error={!!errors.password}
helperText={errors.password?.message}
/>
<Button type="submit" variant="contained" color="primary">
Вход
</Button>
<Button href="/auth/signup" type="button" variant="text" color="primary">
Регистрация
</Button>
</form>
</Box>
</Container>
);
};
export default SignIn;