102 lines
2.1 KiB
JavaScript
102 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/Navbar/NavBar';
|
|
import { backend } from '../helpers/http-common';
|
|
import { useAuth } from '../helpers/authContext';
|
|
|
|
export default function Login() {
|
|
const [error, setError] = useState(false);
|
|
const [credentials, setCredentials] = useState({
|
|
email: '',
|
|
password: '',
|
|
});
|
|
|
|
const { setAuthToken, authToken } = useAuth();
|
|
|
|
const handleChange = (value, evt) => {
|
|
setCredentials({
|
|
...credentials,
|
|
[evt.target.name]: value,
|
|
});
|
|
};
|
|
|
|
const handleLogin = () => {
|
|
backend
|
|
.post('/auth/login', credentials)
|
|
.then((response) => {
|
|
setAuthToken(response.data.token);
|
|
})
|
|
.catch((error) => {
|
|
if (error.response.status === 401) {
|
|
setError('The credentials provided were incorrect.');
|
|
} else
|
|
setError('Something went wrong. Please try again later.');
|
|
});
|
|
};
|
|
|
|
if (authToken) {
|
|
return <Redirect to='/dashboard' />;
|
|
}
|
|
|
|
return (
|
|
<>
|
|
<NavBar title='Login' />
|
|
<Panel bordered style={boxStyle}>
|
|
{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>
|
|
</>
|
|
);
|
|
}
|
|
|
|
// TODO Move to a .less file
|
|
const boxStyle = {
|
|
maxWidth: 373,
|
|
margin: '0 auto',
|
|
borderRadius: 7,
|
|
background: 'white',
|
|
marginTop: '10vh',
|
|
marginBottom: '10vh',
|
|
padding: '1rem',
|
|
};
|