ConceptPortal-public/rsconcept/frontend/src/pages/LoginPage.tsx

76 lines
2.5 KiB
TypeScript
Raw Normal View History

2023-07-15 17:46:19 +03:00
import { useEffect, useState } from 'react';
2023-07-25 20:27:29 +03:00
import { useLocation, useNavigate } from 'react-router-dom';
2023-07-15 17:46:19 +03:00
2023-07-25 20:27:29 +03:00
import BackendError from '../components/BackendError';
2023-07-15 17:46:19 +03:00
import Form from '../components/Common/Form';
import SubmitButton from '../components/Common/SubmitButton';
2023-07-25 20:27:29 +03:00
import TextInput from '../components/Common/TextInput';
2023-07-15 17:46:19 +03:00
import TextURL from '../components/Common/TextURL';
2023-07-25 20:27:29 +03:00
import InfoMessage from '../components/InfoMessage';
import { useAuth } from '../context/AuthContext';
import { IUserLoginData } from '../utils/models';
2023-07-15 17:46:19 +03:00
function LoginPage() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const { user, login, loading, error, setError } = useAuth()
2023-07-25 20:27:29 +03:00
2023-07-15 17:46:19 +03:00
const navigate = useNavigate();
const search = useLocation().search;
useEffect(() => {
const name = new URLSearchParams(search).get('username');
2023-07-25 20:27:29 +03:00
setUsername(name ?? '');
setPassword('');
2023-07-15 17:46:19 +03:00
}, [search]);
useEffect(() => {
setError(undefined);
}, [username, password, setError]);
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!loading) {
const data: IUserLoginData = {
username: username,
password: password
};
login(data, () => { navigate('/rsforms?filter=personal'); });
2023-07-15 17:46:19 +03:00
}
};
return (
2023-07-25 20:27:29 +03:00
<div className='w-full py-2'> { user
? <InfoMessage message={`Вы вошли в систему как ${user.username}`} />
: <Form title='Ввод данных пользователя' onSubmit={handleSubmit} widthClass='w-[20rem]'>
2023-07-15 17:46:19 +03:00
<TextInput id='username'
label='Имя пользователя'
required
type='text'
value={username}
autoFocus
2023-07-25 20:27:29 +03:00
onChange={event => { setUsername(event.target.value); }}
2023-07-15 17:46:19 +03:00
/>
<TextInput id='password'
label='Пароль'
required
type='password'
value={password}
2023-07-25 20:27:29 +03:00
onChange={event => { setPassword(event.target.value); }}
2023-07-15 17:46:19 +03:00
/>
<div className='flex items-center justify-between mt-4'>
2023-07-15 17:46:19 +03:00
<SubmitButton text='Вход' loading={loading}/>
<TextURL text='Восстановить пароль...' href='/restore-password' />
2023-07-15 17:46:19 +03:00
</div>
2023-07-15 18:25:31 +03:00
<div className='mt-2'>
<TextURL text='Нет аккаунта? Зарегистрируйтесь...' href='/signup' />
</div>
2023-07-15 17:46:19 +03:00
{ error && <BackendError error={error} />}
</Form>
}</div>
);
}
2023-07-25 20:27:29 +03:00
export default LoginPage;