99 lines
2.1 KiB
JavaScript
99 lines
2.1 KiB
JavaScript
import React, { useState } from 'react';
|
|
import { Redirect } from 'react-router-dom';
|
|
import {
|
|
Panel,
|
|
Form,
|
|
FormGroup,
|
|
FormControl,
|
|
ControlLabel,
|
|
Button,
|
|
Message,
|
|
} from 'rsuite';
|
|
|
|
import { NavBar } from './../components';
|
|
import { backend } from '../helpers/http-common';
|
|
import { useAuth } from '../helpers/authContext';
|
|
import './styles/layout.less';
|
|
|
|
export default function Login() {
|
|
const [error, setError] = useState(false);
|
|
const [credentials, setCredentials] = useState({
|
|
email: '',
|
|
password: '',
|
|
});
|
|
|
|
const {
|
|
setAuthToken,
|
|
setIsAuthenticated,
|
|
setCurrentUser,
|
|
isAuthenticated,
|
|
} = useAuth();
|
|
|
|
const handleChange = (value, evt) => {
|
|
setCredentials({
|
|
...credentials,
|
|
[evt.target.name]: value,
|
|
});
|
|
};
|
|
|
|
const handleLogin = () => {
|
|
backend
|
|
.post('/auth/login', credentials)
|
|
.then((response) => {
|
|
setAuthToken(response.data.token);
|
|
setCurrentUser(response.data.user);
|
|
setIsAuthenticated(true);
|
|
})
|
|
.catch((error) => {
|
|
if (error.response.status === 401) {
|
|
setError('The credentials provided were incorrect.');
|
|
} else
|
|
setError('Something went wrong. Please try again later.');
|
|
});
|
|
};
|
|
|
|
if (isAuthenticated) {
|
|
return <Redirect to='/dashboard' />;
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<NavBar title='Login' />
|
|
<Panel bordered className={'form-container'}>
|
|
{error && <Message type='error' description={error} />}
|
|
<Form>
|
|
<FormGroup>
|
|
<ControlLabel>Email</ControlLabel>
|
|
<FormControl
|
|
name='email'
|
|
type='email'
|
|
formValue={credentials.email}
|
|
onChange={handleChange}
|
|
/>
|
|
</FormGroup>
|
|
<ControlLabel>Password</ControlLabel>
|
|
<FormGroup>
|
|
<FormControl
|
|
name='password'
|
|
type='password'
|
|
formValue={credentials.password}
|
|
onChange={handleChange}
|
|
/>
|
|
</FormGroup>
|
|
<FormGroup>
|
|
<Button
|
|
appearance='primary'
|
|
block
|
|
size='lg'
|
|
onClick={handleLogin}
|
|
>
|
|
Sign in
|
|
</Button>
|
|
</FormGroup>
|
|
<Button appearance='link'>Forgot password?</Button>
|
|
</Form>
|
|
</Panel>
|
|
</>
|
|
);
|
|
}
|