Auth: SignIn, SignUp (TODO: rewrite into react-hook-form)

This commit is contained in:
cracklesparkle
2024-06-24 17:06:41 +09:00
parent d6906503d1
commit 62695acf74
20 changed files with 617 additions and 71 deletions

View File

@ -2,22 +2,43 @@ import { useEffect, useState } from "react"
import UserService from "../services/UserService"
import AuthService from "../services/AuthService"
import { Button } from "@mui/material"
import DataTable from "../components/DataTable"
import { GridColDef } from "@mui/x-data-grid"
export default function ApiTest() {
const [temp, setTemp] = useState<any>(null)
const [users, setUsers] = useState<any>(null)
const hello = async () => {
await AuthService.hello().then(response => {
setTemp(response)
const getUsers = async () => {
await AuthService.getUsers().then(response => {
setUsers(response.data)
})
}
const columns: GridColDef[] = [
{ field: 'id', headerName: 'ID', type: "number", width: 70 },
{ field: 'email', headerName: 'Email', width: 130 },
{ field: 'login', headerName: 'Логин', width: 130 },
{ field: 'phone', headerName: 'Телефон', width: 90 },
{ field: 'name', headerName: 'Имя', width: 90 },
{ field: 'surname', headerName: 'Фамилия', width: 90 },
{ field: 'is_active', headerName: 'Активен', type: "boolean", width: 90 },
{
field: 'role_id',
headerName: 'Роль',
valueGetter: (value, row) => `${value}`,
width: 90
},
];
return (
<>
<div>{JSON.stringify(temp)}</div>
<Button onClick={() => hello()}>
Hello
<Button onClick={() => getUsers()}>
Get users
</Button>
{users &&
<DataTable rows={users} columns={columns}/>
}
</>
)
}

View File

@ -2,6 +2,10 @@ import { useState } from 'react'
import RoleCard from '../components/RoleCard'
import Modal from '../components/Modal'
import useDataFetching from '../components/FetchingData'
import RoleService from '../services/RoleService'
import { Box, Button } from '@mui/material'
import DataTable from '../components/DataTable'
import { GridColDef } from '@mui/x-data-grid'
interface IRoleCard {
id: number
@ -11,12 +15,38 @@ interface Props {
showModal: boolean;
}
function Roles() {
const [roles, setRoles] = useState<any>(null)
const getRoles = async () => {
await RoleService.getRoles().then(response => {
setRoles(response.data)
})
}
const [showModal, setShowModal] = useState<Props>({ showModal: false });
const cards = useDataFetching<IRoleCard[]>(`${import.meta.env.VITE_API_URL}/auth/role/`, [])
const cards = useDataFetching<IRoleCard[]>(`${import.meta.env.VITE_API_AUTH_URL}/auth/roles/`, [])
const columns: GridColDef[] = [
{ field: 'id', headerName: 'ID', type: "number", width: 70 },
{ field: 'name', headerName: 'Название', width: 90 },
{ field: 'description', headerName: 'Описание', width: 90 },
];
return (
<Box>
<Button onClick={() => getRoles()}>
Get roles
</Button>
{roles &&
<DataTable rows={roles} columns={columns} />
}
</Box>
)
return (
<div>
{cards.map((card, index) => <RoleCard key={index} {...card} />)}
{cards.length > 0 && cards.map((card, index) => <RoleCard key={index} {...card} />)}
<button className='absolute w-0 h-0' onClick={() => setShowModal({ showModal: true })}>+</button>
<Modal {...showModal} />
</div>

View File

@ -1,18 +1,43 @@
import Card from '../components/Card'
import useDataFetching from '../components/FetchingData'
interface ICard {
firstname: string
lastname: string
email: string
}
import { useEffect, useState } from "react"
import AuthService from "../services/AuthService"
import { Box, Button } from "@mui/material"
import DataTable from "../components/DataTable"
import { GridColDef } from "@mui/x-data-grid"
function Users() {
const cards = useDataFetching<ICard[]>(`${import.meta.env.VITE_API_URL}/auth/user/`, [])
return (
<div>
{cards.map((card, index) => <Card key={index} {...card} />)}
</div>
)
}
export default function Users() {
const [users, setUsers] = useState<any>(null)
export default Users
const getUsers = async () => {
await AuthService.getUsers().then(response => {
setUsers(response.data)
})
}
const columns: GridColDef[] = [
{ field: 'id', headerName: 'ID', type: "number", width: 70 },
{ field: 'email', headerName: 'Email', width: 130 },
{ field: 'login', headerName: 'Логин', width: 130 },
{ field: 'phone', headerName: 'Телефон', width: 90 },
{ field: 'name', headerName: 'Имя', width: 90 },
{ field: 'surname', headerName: 'Фамилия', width: 90 },
{ field: 'is_active', headerName: 'Активен', type: "boolean", width: 90 },
{
field: 'role_id',
headerName: 'Роль',
valueGetter: (value, row) => `${value}`,
width: 90
},
];
return (
<Box>
<Button onClick={() => getUsers()}>
Get users
</Button>
{users &&
<DataTable rows={users} columns={columns}/>
}
</Box>
)
}

View File

@ -1,9 +1,99 @@
import React from 'react'
import React, { useState, ChangeEvent, FormEvent } from 'react';
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 = () => {
return (
<div>SignIn</div>
)
}
const [formData, setFormData] = useState<SignInFormData>({
username: '',
password: '',
grant_type: 'password',
scope: '',
client_id: '',
client_secret: ''
});
export default SignIn
const authStore = useAuthStore();
const navigate = useNavigate();
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
setFormData({
...formData,
[e.target.name]: e.target.value,
});
};
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
const formBody = new URLSearchParams();
for (const key in formData) {
formBody.append(key, formData[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}>
<TextField
fullWidth
margin="normal"
name="username"
label="Логин"
value={formData.username}
onChange={handleChange}
required
/>
<TextField
fullWidth
margin="normal"
type="password"
name="password"
label="Пароль"
value={formData.password}
onChange={handleChange}
required
/>
<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;

View File

@ -0,0 +1,105 @@
// src/components/SignUp.tsx
import React, { useState, ChangeEvent, FormEvent } from 'react';
import { TextField, Button, Container, Typography, Box } from '@mui/material';
import axios, { AxiosResponse } from 'axios';
import { SignUpFormData, ApiResponse } from '../../types/auth';
import axiosInstance from '../../http/axiosInstance';
const SignUp: React.FC = () => {
const [formData, setFormData] = useState<SignUpFormData>({
email: '',
login: '',
phone: '',
name: '',
surname: '',
is_active: true,
password: '',
});
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
setFormData({
...formData,
[e.target.name]: e.target.value,
});
};
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
try {
const response: AxiosResponse<ApiResponse> = await axiosInstance.post(`${import.meta.env.VITE_API_AUTH_URL}/auth/user`, formData);
console.log('Успешная регистрация:', response.data);
} catch (error) {
console.error('Ошибка регистрации:', error);
}
};
return (
<Container maxWidth="sm">
<Box my={4}>
<Typography variant="h4" component="h1" gutterBottom>
Регистрация
</Typography>
<form onSubmit={handleSubmit}>
<TextField
fullWidth
margin="normal"
name="email"
label="Email"
value={formData.email}
onChange={handleChange}
required
/>
<TextField
fullWidth
margin="normal"
name="login"
label="Логин"
value={formData.login}
onChange={handleChange}
required
/>
<TextField
fullWidth
margin="normal"
name="phone"
label="Телефон"
value={formData.phone}
onChange={handleChange}
/>
<TextField
fullWidth
margin="normal"
name="name"
label="Имя"
value={formData.name}
onChange={handleChange}
/>
<TextField
fullWidth
margin="normal"
name="surname"
label="Фамилия"
value={formData.surname}
onChange={handleChange}
/>
<TextField
fullWidth
margin="normal"
type="password"
name="password"
label="Пароль"
value={formData.password}
onChange={handleChange}
required
/>
<Button type="submit" variant="contained" color="primary">
Зарегистрироваться
</Button>
</form>
</Box>
</Container>
);
};
export default SignUp;