Страницы входа и регистрации упрощены

This commit is contained in:
goodmice 2021-12-07 19:41:32 +05:00
parent f389097439
commit 91a9bf9c9f
3 changed files with 122 additions and 272 deletions

View File

@ -1,20 +1,16 @@
import { Card, Form, Input, Button, notification } from 'antd';
import { Card, Form, Input, Button } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import logo from '../images/logo_32.png'
import Loader from '../components/Loader'
import { useState } from 'react'
import {Link, useHistory} from "react-router-dom";
import { Link, useHistory } from 'react-router-dom'
import { AuthService, OpenAPI } from '../services/api/'
import LoaderPortal from '../components/LoaderPortal'
import { invokeWebApiWrapperAsync } from '../components/factory'
import { loginRules, passwordRules } from '../utils/validationRules'
import '../styles/index.css'
import logo from '../images/logo_32.png'
const { login } = AuthService
const openNotificationError = (message, title) => {
notification['error']({
message: title||'Ошибка',
description: message,
});
};
const logoIcon = <img src={logo} alt={'АСБ'} className={'logo'} width={130}/>
const setUser = (user) => {
OpenAPI.TOKEN = user.token
@ -24,100 +20,40 @@ const setUser = (user) =>{
}
export default function Login() {
const [loader, setLoader] = useState(false);
const [isErrorVisible, setErrorVisible] = useState(false);
const history = useHistory();
const [form] = Form.useForm();
const history = useHistory()
const [showLoader, setShowLoader] = useState(false)
const logoIcon = <img src={logo} alt="АСБ" className="logo"/>
let handleLogin = async (formData) =>{
setLoader(true)
try{
let user = await login(formData)
const handleLogin = (formData) => invokeWebApiWrapperAsync(
async () => {
const user = await AuthService.login(formData)
if (!user) throw Error('Неправильный логин или пароль')
setUser(user)
setLoader(false)
history.push('well')
}catch(e){
if(e.status === 400)
openNotificationError(e.body)
console.error(`Error ${e}`)
setErrorVisible(true)
form.validateFields()
setLoader(false)
}
}
const showError = (isErrorVisible, errorObj) => {
if (isErrorVisible)
return Promise.reject(errorObj)
return Promise.resolve()
}
},
setShowLoader,
(ex) => ex?.message ?? 'Ошибка входа'
)
return (
<div className='login_page shadow'>
<Card title="Система мониторинга" className='shadow' bordered={true} style={{ width: 350 }} extra={logoIcon}>
<Form form={form} onFinish={handleLogin}>
<Form.Item
name="login"
validateStatus={isErrorVisible ? "error" : "validating"}
rules={[
{ required: true, message: 'Пожалуйста, введите имя пользователя' },
() => ({
validator() {
return showError(isErrorVisible, new Error('Неправильные логин или пароль!'))
}
})
]}
>
<Input
placeholder="Пользователь"
prefix={<UserOutlined />}
onChange={() => {
setErrorVisible(false)
form.validateFields()
}}
/>
<LoaderPortal show={showLoader} className={'loader-container login_page shadow'}>
<Card title={'Система мониторинга'} className={'shadow'} bordered={true} style={{ width: 350 }} extra={logoIcon}>
<Form onFinish={handleLogin}>
<Form.Item name={'login'} rules={loginRules}>
<Input placeholder={'Пользователь'} prefix={<UserOutlined />} />
</Form.Item>
<Form.Item
name="password"
rules={[
{ required: true, message: 'Пожалуйста, введите пароль' },
() => ({
validator() {
return showError(isErrorVisible)
}
})
]}
>
<Input.Password
placeholder='пароль'
prefix={<LockOutlined />}
onChange={() => {
setErrorVisible(false)
form.validateFields()
}}
/>
<Form.Item name={'password'} rules={passwordRules}>
<Input.Password placeholder={'Пароль'} prefix={<LockOutlined />} />
</Form.Item>
<Form.Item>
<div className='login-button'>
<Button type="primary" htmlType="submit">
Вход
</Button>
<div className={'login-button'}>
<Button type={'primary'} htmlType={'submit'}>Вход</Button>
</div>
</Form.Item>
<div className='text-align-center'>
<div className={'text-align-center'}>
<Link to={`/register`}>Отправить заявку на регистрацию</Link>
</div>
</Form>
</Card>
{loader && <Loader/>}
</div>
</LoaderPortal>
)
}

View File

@ -1,198 +1,101 @@
import { Card, Form, Input, Select, Button, notification } from 'antd';
import { UserOutlined,
import { memo, useState } from 'react'
import { Link, useHistory } from 'react-router-dom'
import { Card, Form, Input, Select, Button } from 'antd'
import {
UserOutlined,
LockOutlined,
EyeInvisibleOutlined,
EyeTwoTone } from '@ant-design/icons'
import logo from '../images/logo_32.png'
import Loader from '../components/Loader'
import { useState } from 'react'
import { Link, useHistory } from "react-router-dom";
EyeTwoTone
} from '@ant-design/icons'
import { AuthService } from '../services/api/'
const openNotification = (message, type, title) => {
notification[type]({
message: title||'Ошибка',
description: message,
});
};
const { Option } = Select;
import LoaderPortal from '../components/LoaderPortal'
import { invokeWebApiWrapperAsync } from '../components/factory'
import {
createLoginRules,
createPasswordRules,
emailRules,
loginRules,
nameRules,
passwordRules,
phoneRules
} from '../utils/validationRules'
import logo from '../images/logo_32.png'
const companies = [
{ name: "ООО «Газпромнефть-Хантос» ", value: 1 },
{ name: "АО «НафтаГаз»", value: 2 },
{ name: "ООО «Нафтагаз Бурение»", value: 3 },
{ name: "ООО «Газпромнефть-ННГ»", value: 4 }
];
const showError = (isErrorVisible, errorObj) => {
if (isErrorVisible)
return Promise.reject(errorObj)
{ label: 'ООО «Газпромнефть-Хантос» ', value: 1 },
{ label: 'АО «НафтаГаз»', value: 2 },
{ label: 'ООО «Нафтагаз Бурение»', value: 3 },
{ label: 'ООО «Газпромнефть-ННГ»', value: 4 }
]
const surnameRules = [...nameRules, { required: true, message: 'Пожалуйста, введите фамилию!' }]
const regEmailRules = [{ required: true, message: 'Пожалуйста, введите email!' }, ...emailRules]
const confirmPasswordRules = [
...createPasswordRules,
{ required: true, message: 'Пожалуйста, введите пароль повторно!' },
({ getFieldValue }) => ({
validator(_, value) {
if (!value || getFieldValue('password') === value)
return Promise.resolve()
}
const getValidationRules = (isRequired, message, isErrorVisible, errorObj) => {
return [
{ required: isRequired, message: message },
() => ({
validator() {
return showError(isErrorVisible, errorObj)
return Promise.reject(new Error('Пароли не совпадают!'))
}
})
]
}
const logoIcon = <img src={logo} alt={'АСБ'} className={'logo'} width={130}/>
const showPasswordIcon = visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)
export default function Register() {
const [loader, setLoader] = useState(false);
const [isLengthErrorVisible, setIsLengthErrorVisible] = useState(false);
const [isPasswordLengthErrorVisible, setIsPasswordLengthErrorVisible] = useState(false);
const [isPasswordMismatchErrorVisible, setIsPasswordMismatchErrorVisible] = useState(false);
const [selectedCompanyId, setSelectedCompanyId] = useState(companies[0].value);
const history = useHistory();
const [form] = Form.useForm();
const createInput = (name, placeholder, rules, isPassword, dependencies) => (
<Form.Item name={name} rules={rules ?? []} dependencies={dependencies ?? []}>
{isPassword ? (
<Input.Password placeholder={placeholder} prefix={<LockOutlined />} iconRender={showPasswordIcon} />
) : (
<Input placeholder={placeholder} prefix={<UserOutlined />} />
)}
</Form.Item>
)
const logoIcon = <img src={logo} alt="АСБ" className="logo"/>
export const Register = memo(() => {
const [showLoader, setShowLoader] = useState(false)
const history = useHistory()
const children = companies.map((line) => (
<Option key={line.value}>{line.name}</Option>
));
const checkFormErrors = (formData) => {
if(formData.login.length < 4 || formData.login.length > 50){
setIsLengthErrorVisible(true)
form.validateFields()
return true
}
if(formData.password.length < 4 || formData.password.length > 50) {
setIsPasswordLengthErrorVisible(true)
form.validateFields()
return true
}
if(formData.password !== formData.confirmPassword) {
setIsPasswordMismatchErrorVisible(true)
form.validateFields()
return true
}
return false
}
let handleRegister = async (formData) =>{
if(checkFormErrors(formData))
return
formData.idCompany = +selectedCompanyId
setLoader(true)
try{
const handleRegister = (formData) => invokeWebApiWrapperAsync(
async () => {
await AuthService.register(formData)
setLoader(false)
openNotification("Заявка на регистрацию отправлена.", 'success')
history.push("/login");
}catch(e){
openNotification(e.body, 'error')
console.error(`Error ${e}`)
setLoader(false)
}
}
const createInput = (name, placeholder, isRequired, requiredValidationMessage, lengthValidationMessage) => {
const rules = getValidationRules(true, requiredValidationMessage,
isLengthErrorVisible, new Error(lengthValidationMessage))
return (
<Form.Item
name={name}
rules={isRequired ? rules : []}
>
<Input
placeholder={placeholder}
prefix={<UserOutlined />}
onChange={() => {
setIsLengthErrorVisible(false)
form.validateFields()
}}
/>
</Form.Item>
history.push('/login')
},
setShowLoader,
`Ошибка отправки заявки на регистрацию`
)
}
const createPasswordInput = (name, message, errorObj, isErrorVisible, setIsErrorVisible) => {
return (
<Form.Item
name={name}
rules={getValidationRules(true, message, isErrorVisible, errorObj)}
>
<Input.Password
placeholder='Подтверждение пароля'
iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
prefix={<LockOutlined />}
onChange={() => {
setIsErrorVisible(false)
form.validateFields()
}}
/>
</Form.Item>
)
}
return (
<div className='login_page shadow'>
<Card title="Система мониторинга" className='shadow' bordered={true} style={{ width: 350 }} extra={logoIcon}>
<Form form={form} onFinish={handleRegister}>
{createInput('login', 'Пользователь', true,
'Пожалуйста, введите имя!',
'Допустимая длина логина от 3 до 50 символов!')}
{createPasswordInput('password', 'Пожалуйста, введите пароль!',
new Error('Допускаются пароли от 3х до 50ти символов'),
isPasswordLengthErrorVisible, setIsPasswordLengthErrorVisible)}
{createPasswordInput('confirmPassword', 'Пожалуйста, введите пароль повторно!',
new Error('Пароли не совпадают!'), isPasswordMismatchErrorVisible,
setIsPasswordMismatchErrorVisible)}
{createInput('name', 'Имя', false)}
{createInput('surName', 'Фамилия', false)}
{createInput('patronymic', 'Отчество',false)}
{createInput('email', 'Email',false)}
{createInput('phone', 'Номер телефона',false)}
<Form.Item
name="idCompany"
initialValue={companies[0].name}
>
<Select
placeholder="Выберите компанию"
className="m-0"
value={selectedCompanyId}
onChange={setSelectedCompanyId}
>
{children}
</Select>
<LoaderPortal show={showLoader} className={'loader-container login_page shadow'}>
<Card title={'Система мониторинга'} className={'shadow'} bordered={true} style={{ width: 350 }} extra={logoIcon}>
<Form onFinish={handleRegister}>
{createInput('login', 'Пользователь', [...loginRules, ...createLoginRules])}
{createInput('password', 'Пароль', [...passwordRules, ...createPasswordRules], true, null)}
{createInput('confirmPassword', 'Подтверждение пароля', confirmPasswordRules, true, ['password'])}
{createInput('name', 'Имя', nameRules)}
{createInput('surName', 'Фамилия', surnameRules)}
{createInput('patronymic', 'Отчество', nameRules)}
{createInput('email', 'Email', regEmailRules)}
{createInput('phone', 'Номер телефона', phoneRules)}
<Form.Item name={'idCompany'} initialValue={companies[0].value}>
<Select placeholder={'Выберите компанию'} className={'m-0'} options={companies} />
</Form.Item>
{createInput('position', 'Должность',false)}
{createInput('position', 'Должность')}
<Form.Item>
<div className='register-button'>
<Button
type="primary"
htmlType="submit"
>
Зарегистрироваться
</Button>
<div className={'register-button'}>
<Button type={'primary'} htmlType={'submit'}>Зарегистрироваться</Button>
</div>
</Form.Item>
<div className='text-align-center'>
<div className={'text-align-center'}>
<Link to={`/login`}>Назад</Link>
</div>
</Form>
</Card>
{loader && <Loader/>}
</div>
</LoaderPortal>
)
}
})
export default Register

View File

@ -1,6 +1,6 @@
import { Rule } from 'rc-field-form/lib/interface'
export const loginRules: Rule[] = [{
export const createLoginRules: Rule[] = [{
min: 3,
max: 255,
message: 'Допустимая длина 3-255 символов'
@ -10,6 +10,11 @@ export const loginRules: Rule[] = [{
message: 'Логин должен начинаться с русской или латинской буквы, содержать только (А-яA-z0-9_-.)!'
}]
export const loginRules: Rule[] = [{
required: true,
message: 'Пожалуйста, введите имя пользователя'
}]
export const nameRules: Rule[] = [{
min: 1,
max: 255,
@ -31,5 +36,11 @@ export const emailRules: Rule[] = [{
export const passwordRules: Rule[] = [{
required: true,
message: 'Поле не может быть пустым!'
message: 'Пожалуйста, введите пароль!'
}]
export const createPasswordRules: Rule[] = [{
min: 8,
max: 255,
message: 'Допустимая длина пароля 8-255'
}]